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
9b487641c2b43813f9056084e9251009c816e210
3,287
//! //! The constant array element tests. //! use num::BigInt; use crate::error::Error; use crate::semantic::element::constant::array::error::Error as ArrayConstantError; use crate::semantic::element::constant::error::Error as ConstantError; use crate::semantic::element::error::Error as ElementError; use crate::semantic::element::r#type::Type; use crate::semantic::error::Error as SemanticError; use zinc_lexical::Location; #[test] fn error_pushing_invalid_type() { let input = r#" fn main() { const ARRAY: [u8; 2] = [1, false]; } "#; let expected = Err(Error::Semantic(SemanticError::Element( ElementError::Constant(ConstantError::Array( ArrayConstantError::PushingInvalidType { location: Location::test(3, 32), expected: Type::integer_unsigned(None, zinc_const::bitlength::BYTE).to_string(), found: Type::boolean(None).to_string(), }, )), ))); let result = crate::semantic::tests::compile_entry(input); assert_eq!(result, expected); } #[test] fn error_index_out_of_range() { let input = r#" fn main() { const VALUE: u8 = [1, 2, 3, 4, 5][5]; } "#; let expected = Err(Error::Semantic(SemanticError::Element( ElementError::Constant(ConstantError::Array(ArrayConstantError::IndexOutOfRange { location: Location::test(3, 39), index: BigInt::from(5).to_string(), size: 5, })), ))); let result = crate::semantic::tests::compile_entry(input); assert_eq!(result, expected); } #[test] fn error_slice_start_out_of_range() { let input = r#" fn main() { const ARRAY: [u8; 2] = [1, 2, 3, 4, 5][-1 .. 1]; } "#; let expected = Err(Error::Semantic(SemanticError::Element( ElementError::Constant(ConstantError::Array( ArrayConstantError::SliceStartOutOfRange { location: Location::test(3, 45), start: BigInt::from(-1).to_string(), }, )), ))); let result = crate::semantic::tests::compile_entry(input); assert_eq!(result, expected); } #[test] fn error_slice_end_out_of_range() { let input = r#" fn main() { const ARRAY: [u8; 6] = [1, 2, 3, 4, 5][0 .. 6]; } "#; let expected = Err(Error::Semantic(SemanticError::Element( ElementError::Constant(ConstantError::Array( ArrayConstantError::SliceEndOutOfRange { location: Location::test(3, 44), end: BigInt::from(6).to_string(), size: 5, }, )), ))); let result = crate::semantic::tests::compile_entry(input); assert_eq!(result, expected); } #[test] fn error_slice_end_lesser_than_start() { let input = r#" fn main() { const ARRAY: [u8; 1] = [1, 2, 3, 4, 5][2 .. 1]; } "#; let expected = Err(Error::Semantic(SemanticError::Element( ElementError::Constant(ConstantError::Array( ArrayConstantError::SliceEndLesserThanStart { location: Location::test(3, 44), start: BigInt::from(2).to_string(), end: BigInt::from(1).to_string(), }, )), ))); let result = crate::semantic::tests::compile_entry(input); assert_eq!(result, expected); }
26.087302
96
0.594463
e41e85bece498b8ec8d2ca6ebed404575e48b54c
363
// if1.rs pub fn bigger(a: i32, b: i32) -> i32 { return if a > b { a } else { b } } // Don't mind this for now :) #[cfg(test)] mod tests { use super::*; #[test] fn ten_is_bigger_than_eight() { assert_eq!(10, bigger(10, 8)); } #[test] fn fortytwo_is_bigger_than_thirtytwo() { assert_eq!(42, bigger(32, 42)); } }
16.5
44
0.534435
fc2747fe3e74767fd691cb99a67bc1fdff6a3b87
663
use ink_lang as ink; #[ink::contract( version = "0.1.0", compile_as_dependency = true, )] mod flipper { #[ink(storage)] struct Flipper { value: bool, } impl Flipper { #[ink(constructor)] fn new(init_value: bool) -> Self { Self { value: init_value, } } #[ink(constructor)] fn default() -> Self { Self::new(false) } #[ink(message)] fn flip(&mut self) { self.value = !self.value; } #[ink(message)] fn get(&self) -> bool { self.value } } } fn main() {}
17
42
0.435897
e28bc810a5bf0d5736d4c3f2e5835301b58fe84e
4,229
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module defines representation of Diem core data structures at physical level via schemas //! that implement [`schemadb::schema::Schema`]. //! //! All schemas are `pub(crate)` so not shown in rustdoc, refer to the source code to see details. pub(crate) mod epoch_by_version; pub(crate) mod event; pub(crate) mod event_accumulator; pub(crate) mod event_by_key; pub(crate) mod event_by_version; pub(crate) mod jellyfish_merkle_node; pub(crate) mod ledger_counters; pub(crate) mod ledger_info; pub(crate) mod stale_node_index; pub(crate) mod transaction; pub(crate) mod transaction_accumulator; pub(crate) mod transaction_by_account; pub(crate) mod transaction_by_hash; pub(crate) mod transaction_info; pub(crate) mod write_set; use anyhow::{ensure, Result}; use schemadb::ColumnFamilyName; pub const EPOCH_BY_VERSION_CF_NAME: ColumnFamilyName = "epoch_by_version"; pub const EVENT_ACCUMULATOR_CF_NAME: ColumnFamilyName = "event_accumulator"; pub const EVENT_BY_KEY_CF_NAME: ColumnFamilyName = "event_by_key"; pub const EVENT_BY_VERSION_CF_NAME: ColumnFamilyName = "event_by_version"; pub const EVENT_CF_NAME: ColumnFamilyName = "event"; pub const JELLYFISH_MERKLE_NODE_CF_NAME: ColumnFamilyName = "jellyfish_merkle_node"; pub const LEDGER_COUNTERS_CF_NAME: ColumnFamilyName = "ledger_counters"; pub const STALE_NODE_INDEX_CF_NAME: ColumnFamilyName = "stale_node_index"; pub const TRANSACTION_CF_NAME: ColumnFamilyName = "transaction"; pub const TRANSACTION_ACCUMULATOR_CF_NAME: ColumnFamilyName = "transaction_accumulator"; pub const TRANSACTION_BY_ACCOUNT_CF_NAME: ColumnFamilyName = "transaction_by_account"; pub const TRANSACTION_BY_HASH_CF_NAME: ColumnFamilyName = "transaction_by_hash"; pub const TRANSACTION_INFO_CF_NAME: ColumnFamilyName = "transaction_info"; pub const WRITE_SET_CF_NAME: ColumnFamilyName = "write_set"; fn ensure_slice_len_eq(data: &[u8], len: usize) -> Result<()> { ensure!( data.len() == len, "Unexpected data len {}, expected {}.", data.len(), len, ); Ok(()) } fn ensure_slice_len_gt(data: &[u8], len: usize) -> Result<()> { ensure!( data.len() > len, "Unexpected data len {}, expected to be greater than {}.", data.len(), len, ); Ok(()) } #[cfg(feature = "fuzzing")] pub mod fuzzing { use schemadb::schema::{KeyCodec, Schema, ValueCodec}; macro_rules! decode_key_value { ($schema_type: ty, $data: ident) => { <<$schema_type as Schema>::Key as KeyCodec<$schema_type>>::decode_key($data); <<$schema_type as Schema>::Value as ValueCodec<$schema_type>>::decode_value($data); }; } pub fn fuzz_decode(data: &[u8]) { #[allow(unused_must_use)] { decode_key_value!(super::epoch_by_version::EpochByVersionSchema, data); decode_key_value!(super::event::EventSchema, data); decode_key_value!(super::event_accumulator::EventAccumulatorSchema, data); decode_key_value!(super::event_by_key::EventByKeySchema, data); decode_key_value!(super::event_by_version::EventByVersionSchema, data); decode_key_value!( super::jellyfish_merkle_node::JellyfishMerkleNodeSchema, data ); decode_key_value!(super::ledger_counters::LedgerCountersSchema, data); decode_key_value!(super::ledger_info::LedgerInfoSchema, data); decode_key_value!(super::stale_node_index::StaleNodeIndexSchema, data); decode_key_value!(super::transaction::TransactionSchema, data); decode_key_value!( super::transaction_accumulator::TransactionAccumulatorSchema, data ); decode_key_value!( super::transaction_by_account::TransactionByAccountSchema, data ); decode_key_value!(super::transaction_by_hash::TransactionByHashSchema, data); decode_key_value!(super::transaction_info::TransactionInfoSchema, data); decode_key_value!(super::write_set::WriteSetSchema, data); } } }
40.663462
98
0.700166
ccc837052bd2d8920de6fba95b743326b3403263
16,411
use influxdb_line_protocol::ParsedLine; use chrono::{DateTime, TimeZone, Utc}; use serde::{Deserialize, Serialize}; use snafu::Snafu; #[derive(Debug, Snafu)] pub enum Error { #[snafu(display("Error in {}: {}", source_module, source))] PassThrough { source_module: &'static str, source: Box<dyn std::error::Error + Send + Sync + 'static>, }, } pub type Result<T, E = Error> = std::result::Result<T, E>; /// DatabaseRules contains the rules for replicating data, sending data to /// subscribers, and querying data for a single database. #[derive(Debug, Serialize, Deserialize, Default, Eq, PartialEq, Clone)] pub struct DatabaseRules { /// Template that generates a partition key for each row inserted into the /// db #[serde(default)] pub partition_template: PartitionTemplate, /// If `store_locally` is set to `true`, this server will store writes and /// replicated writes in a local write buffer database. This is step #4 /// from the diagram. #[serde(default)] pub store_locally: bool, /// The set of host groups that data should be replicated to. Which host a /// write goes to within a host group is determined by consistent hashing of /// the partition key. We'd use this to create a host group per /// availability zone, so you might have 5 availability zones with 2 /// hosts in each. Replication will ensure that N of those zones get a /// write. For each zone, only a single host needs to get the write. /// Replication is for ensuring a write exists across multiple hosts /// before returning success. Its purpose is to ensure write durability, /// rather than write availability for query (this is covered by /// subscriptions). #[serde(default)] pub replication: Vec<HostGroupId>, /// The minimum number of host groups to replicate a write to before success /// is returned. This can be overridden on a per request basis. /// Replication will continue to write to the other host groups in the /// background. #[serde(default)] pub replication_count: u8, /// How long the replication queue can get before either rejecting writes or /// dropping missed writes. The queue is kept in memory on a /// per-database basis. A queue size of zero means it will only try to /// replicate synchronously and drop any failures. #[serde(default)] pub replication_queue_max_size: usize, /// `subscriptions` are used for query servers to get data via either push /// or pull as it arrives. They are separate from replication as they /// have a different purpose. They're for query servers or other clients /// that want to subscribe to some subset of data being written in. This /// could either be specific partitions, ranges of partitions, tables, or /// rows matching some predicate. This is step #3 from the diagram. #[serde(default)] pub subscriptions: Vec<Subscription>, /// If set to `true`, this server should answer queries from one or more of /// of its local write buffer and any read-only partitions that it knows /// about. In this case, results will be merged with any others from the /// remote goups or read only partitions. #[serde(default)] pub query_local: bool, /// Set `primary_query_group` to a host group if remote servers should be /// issued queries for this database. All hosts in the group should be /// queried with this server acting as the coordinator that merges /// results together. If a specific host in the group is unavailable, /// another host in the same position from a secondary group should be /// queried. For example, imagine we've partitioned the data in this DB into /// 4 partitions and we are replicating the data across 3 availability /// zones. We have 4 hosts in each of those AZs, thus they each have 1 /// partition. We'd set the primary group to be the 4 hosts in the same /// AZ as this one, and the secondary groups as the hosts in the other 2 /// AZs. #[serde(default)] pub primary_query_group: Option<HostGroupId>, #[serde(default)] pub secondary_query_groups: Vec<HostGroupId>, /// Use `read_only_partitions` when a server should answer queries for /// partitions that come from object storage. This can be used to start /// up a new query server to handle queries by pointing it at a /// collection of partitions and then telling it to also pull /// data from the replication servers (writes that haven't been snapshotted /// into a partition). #[serde(default)] pub read_only_partitions: Vec<PartitionId>, /// When set this will buffer WAL writes in memory based on the /// configuration. #[serde(default)] pub wal_buffer_config: Option<WalBufferConfig>, } impl DatabaseRules { pub fn partition_key( &self, line: &ParsedLine<'_>, default_time: &DateTime<Utc>, ) -> Result<String> { self.partition_template.partition_key(line, default_time) } } /// WalBufferConfig defines the configuration for buffering data from the WAL in /// memory. This buffer is used for asynchronous replication and to collect /// segments before sending them to object storage. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] pub struct WalBufferConfig { /// The size the WAL buffer should be limited to. Once the buffer gets to /// this size it will drop old segments to remain below this size, but /// still try to hold as much in memory as possible while remaining /// below this threshold pub buffer_size: Option<u64>, /// WAL segments become read only after crossing over this size. Which means /// that segments will always be >= this size. When old segments are /// dropped from of memory, at least this much space will be freed from /// the buffer. pub segment_size: Option<u64>, /// What should happen if a write comes in that would exceed the WAL buffer /// size and the oldest segment that could be dropped hasn't yet been /// persisted to object storage. If the oldest segment has been /// persisted, then it will be dropped from the buffer so that new writes /// can be accepted. This option is only for defining the behavior of what /// happens if that segment hasn't been persisted. pub buffer_rollover: WalBufferRollover, } /// WalBufferRollover defines the behavior of what should happen if a write /// comes in that would cause the buffer to exceed its max size AND the oldest /// segment can't be dropped because it has not yet been persisted. #[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] pub enum WalBufferRollover { /// Drop the old segment even though it hasn't been persisted. This part of /// the WAl will be lost on this server. DropOldSegment, /// Drop the incoming write and fail silently. This favors making sure that /// older WAL data will be backed up. DropIncoming, /// Reject the incoming write and return an error. The client may retry the /// request, which will succeed once the oldest segment has been /// persisted to object storage. ReturnError, } /// `PartitionTemplate` is used to compute the partition key of each row that /// gets written. It can consist of the table name, a column name and its value, /// a formatted time, or a string column and regex captures of its value. For /// columns that do not appear in the input row, a blank value is output. /// /// The key is constructed in order of the template parts; thus ordering changes /// what partition key is generated. #[derive(Debug, Serialize, Deserialize, Default, Eq, PartialEq, Clone)] pub struct PartitionTemplate { pub parts: Vec<TemplatePart>, } impl PartitionTemplate { pub fn partition_key( &self, line: &ParsedLine<'_>, default_time: &DateTime<Utc>, ) -> Result<String> { let parts: Vec<_> = self .parts .iter() .map(|p| match p { TemplatePart::Table => line.series.measurement.to_string(), TemplatePart::Column(column) => match line.tag_value(&column) { Some(v) => format!("{}_{}", column, v), None => match line.field_value(&column) { Some(v) => format!("{}_{}", column, v), None => "".to_string(), }, }, TemplatePart::TimeFormat(format) => match line.timestamp { Some(t) => Utc.timestamp_nanos(t).format(&format).to_string(), None => default_time.format(&format).to_string(), }, _ => unimplemented!(), }) .collect(); Ok(parts.join("-")) } } /// `TemplatePart` specifies what part of a row should be used to compute this /// part of a partition key. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] pub enum TemplatePart { Table, Column(String), TimeFormat(String), RegexCapture(RegexCapture), StrftimeColumn(StrftimeColumn), } /// `RegexCapture` is for pulling parts of a string column into the partition /// key. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] pub struct RegexCapture { column: String, regex: String, } /// `StrftimeColumn` can be used to create a time based partition key off some /// column other than the builtin `time` column. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] pub struct StrftimeColumn { column: String, format: String, } /// `PartitionId` is the object storage identifier for a specific partition. It /// should be a path that can be used against an object store to locate all the /// files and subdirectories for a partition. It takes the form of `/<writer /// ID>/<database>/<partition key>/`. pub type PartitionId = String; pub type WriterId = u32; /// `Subscription` represents a group of hosts that want to receive data as it /// arrives. The subscription has a matcher that is used to determine what data /// will match it, and an optional queue for storing matched writes. Subscribers /// that recieve some subeset of an individual replicated write will get a new /// replicated write, but with the same originating writer ID and sequence /// number for the consuming subscriber's tracking purposes. /// /// For pull based subscriptions, the requester will send a matcher, which the /// receiver will execute against its in-memory WAL. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] pub struct Subscription { pub name: String, pub host_group_id: HostGroupId, pub matcher: Matcher, } /// `Matcher` specifies the rule against the table name and/or a predicate /// against the row to determine if it matches the write rule. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] pub struct Matcher { #[serde(flatten)] pub tables: MatchTables, // TODO: make this work with query::Predicate #[serde(skip_serializing_if = "Option::is_none")] pub predicate: Option<String>, } /// `MatchTables` looks at the table name of a row to determine if it should /// match the rule. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub enum MatchTables { #[serde(rename = "*")] All, Table(String), Regex(String), } pub type HostGroupId = String; #[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)] pub struct HostGroup { pub id: HostGroupId, /// `hosts` is a vector of connection strings for remote hosts. pub hosts: Vec<String>, } #[cfg(test)] mod tests { use super::*; use influxdb_line_protocol::parse_lines; #[allow(dead_code)] type TestError = Box<dyn std::error::Error + Send + Sync + 'static>; #[allow(dead_code)] type Result<T = (), E = TestError> = std::result::Result<T, E>; #[test] fn partition_key_with_table() -> Result { let template = PartitionTemplate { parts: vec![TemplatePart::Table], }; let line = parse_line("cpu foo=1 10"); assert_eq!("cpu", template.partition_key(&line, &Utc::now()).unwrap()); Ok(()) } #[test] fn partition_key_with_int_field() -> Result { let template = PartitionTemplate { parts: vec![TemplatePart::Column("foo".to_string())], }; let line = parse_line("cpu foo=1 10"); assert_eq!("foo_1", template.partition_key(&line, &Utc::now()).unwrap()); Ok(()) } #[test] fn partition_key_with_float_field() -> Result { let template = PartitionTemplate { parts: vec![TemplatePart::Column("foo".to_string())], }; let line = parse_line("cpu foo=1.1 10"); assert_eq!( "foo_1.1", template.partition_key(&line, &Utc::now()).unwrap() ); Ok(()) } #[test] fn partition_key_with_string_field() -> Result { let template = PartitionTemplate { parts: vec![TemplatePart::Column("foo".to_string())], }; let line = parse_line("cpu foo=\"asdf\" 10"); assert_eq!( "foo_asdf", template.partition_key(&line, &Utc::now()).unwrap() ); Ok(()) } #[test] fn partition_key_with_bool_field() -> Result { let template = PartitionTemplate { parts: vec![TemplatePart::Column("bar".to_string())], }; let line = parse_line("cpu bar=true 10"); assert_eq!( "bar_true", template.partition_key(&line, &Utc::now()).unwrap() ); Ok(()) } #[test] fn partition_key_with_tag_column() -> Result { let template = PartitionTemplate { parts: vec![TemplatePart::Column("region".to_string())], }; let line = parse_line("cpu,region=west usage_user=23.2 10"); assert_eq!( "region_west", template.partition_key(&line, &Utc::now()).unwrap() ); Ok(()) } #[test] fn partition_key_with_missing_column() -> Result { let template = PartitionTemplate { parts: vec![TemplatePart::Column("not_here".to_string())], }; let line = parse_line("cpu,foo=asdf bar=true 10"); assert_eq!("", template.partition_key(&line, &Utc::now()).unwrap()); Ok(()) } #[test] fn partition_key_with_time() -> Result { let template = PartitionTemplate { parts: vec![TemplatePart::TimeFormat("%Y-%m-%d %H:%M:%S".to_string())], }; let line = parse_line("cpu,foo=asdf bar=true 1602338097000000000"); assert_eq!( "2020-10-10 13:54:57", template.partition_key(&line, &Utc::now()).unwrap() ); Ok(()) } #[test] fn partition_key_with_default_time() -> Result { let format_string = "%Y-%m-%d %H:%M:%S"; let template = PartitionTemplate { parts: vec![TemplatePart::TimeFormat(format_string.to_string())], }; let default_time = Utc::now(); let line = parse_line("cpu,foo=asdf bar=true"); assert_eq!( default_time.format(format_string).to_string(), template.partition_key(&line, &default_time).unwrap() ); Ok(()) } #[test] fn partition_key_with_many_parts() -> Result { let template = PartitionTemplate { parts: vec![ TemplatePart::Table, TemplatePart::Column("region".to_string()), TemplatePart::Column("usage_system".to_string()), TemplatePart::TimeFormat("%Y-%m-%d %H:%M:%S".to_string()), ], }; let line = parse_line( "cpu,host=a,region=west usage_user=22.1,usage_system=53.1 1602338097000000000", ); assert_eq!( "cpu-region_west-usage_system_53.1-2020-10-10 13:54:57", template.partition_key(&line, &Utc::now()).unwrap() ); Ok(()) } fn parsed_lines(lp: &str) -> Vec<ParsedLine<'_>> { parse_lines(lp).map(|l| l.unwrap()).collect() } fn parse_line(line: &str) -> ParsedLine<'_> { parsed_lines(line).pop().unwrap() } }
37.045147
91
0.643471
0a1b2817a9de91cd4a9ddc0825f957bdc061d472
9,544
use std::marker::PhantomData; use std::mem; use libc::c_int; use libusb::*; use io::IoType; use device_list::{self, DeviceList}; use device_handle::{self, DeviceHandle}; use error; /// A `libusb` context. pub struct Context<Io> { context: *mut libusb_context, io: Io, } impl<Io> Drop for Context<Io> { /// Closes the `libusb` context. fn drop(&mut self) { unsafe { libusb_exit(self.context); } } } unsafe impl<Io> Sync for Context<Io> {} unsafe impl<Io> Send for Context<Io> {} impl<Io> Context<Io> where for<'ctx> Io: IoType<'ctx> { /// Opens a new `libusb` context. pub fn new() -> ::Result<Self> { let mut context = unsafe { mem::uninitialized() }; try_unsafe!(libusb_init(&mut context)); Ok(Context { io: Io::new(context), context: context }) } /// Sets the log level of a `libusb` context. pub fn set_log_level(&mut self, level: LogLevel) { unsafe { libusb_set_debug(self.context, level.as_c_int()); } } pub fn has_capability(&self) -> bool { unsafe { libusb_has_capability(LIBUSB_CAP_HAS_CAPABILITY) != 0 } } /// Tests whether the running `libusb` library supports hotplug. pub fn has_hotplug(&self) -> bool { unsafe { libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG) != 0 } } /// Tests whether the running `libusb` library has HID access. pub fn has_hid_access(&self) -> bool { unsafe { libusb_has_capability(LIBUSB_CAP_HAS_HID_ACCESS) != 0 } } /// Tests whether the running `libusb` library supports detaching the kernel driver. pub fn supports_detach_kernel_driver(&self) -> bool { unsafe { libusb_has_capability(LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER) != 0 } } /// Returns a list of the current USB devices. The context must outlive the device list. pub fn devices<'ctx>(&'ctx self) -> ::Result<DeviceList<'ctx, Io>> { let mut list: *const *mut libusb_device = unsafe { mem::uninitialized() }; let n = unsafe { libusb_get_device_list(self.context, &mut list) }; if n < 0 { Err(error::from_libusb(n as c_int)) } else { Ok(unsafe { device_list::from_libusb(self, self.io.handle(), list, n as usize) }) } } /// Convenience function to open a device by its vendor ID and product ID. /// /// This function is provided as a convenience for building prototypes without having to /// iterate a [`DeviceList`](struct.DeviceList.html). It is not meant for production /// applications. /// /// Returns a device handle for the first device found matching `vendor_id` and `product_id`. /// On error, or if the device could not be found, it returns `None`. pub fn open_device_with_vid_pid<'ctx>(&'ctx self, vendor_id: u16, product_id: u16) -> Option<DeviceHandle<'ctx, Io>> { let handle = unsafe { libusb_open_device_with_vid_pid(self.context, vendor_id, product_id) }; if handle.is_null() { None } else { Some(unsafe { device_handle::from_libusb(PhantomData, (&self.io).handle(), handle) }) } } } #[cfg(any(target_os = "linux", target_os = "macos"))] mod unix_async_io { use std::io; use std::slice; use std::os::unix::io::RawFd; use std::thread::sleep; use std::time::Duration; use mio::event::Evented; use mio::unix::EventedFd; use mio::{Poll, Token, Ready, PollOpt}; use libc::{POLLIN, POLLOUT, timeval}; use libusb::*; use ::io::unix_async::{UnixAsyncIo, UnixAsyncIoTransferResult}; use ::error::from_libusb; use super::Context; impl Context<UnixAsyncIo> { pub fn handle(&self, poll: &Poll, complete: &mut Vec<(usize, UnixAsyncIoTransferResult)>) -> ::Result<()> { let mut ir = self.io.reg.lock().expect("Could not unlock UnixAsyncIo reg mutex"); match (*ir).as_mut() { None => return Err("Register in Poll before calling handle".into()), Some(ofds) => { let tv = timeval { tv_sec: 0, tv_usec: 0 }; let res = match unsafe { libusb_handle_events_locked(self.context, &tv as *const timeval) } { 0 => { let mut tr = self.io.state.lock().expect("Could not unlock UnixAsyncIo state mutex"); ::std::mem::swap(&mut tr.complete, complete); Ok(()) }, e => Err(from_libusb(e)) }; if unsafe { libusb_event_handling_ok(self.context) } == 0 { unsafe { libusb_unlock_events(self.context) }; self.spin_until_locked_and_ok_to_handle_events(); } let fds = self.get_pollfd_list(); if ofds.1 != fds { for &(ref fd, _) in ofds.1.iter() { poll.deregister(&EventedFd(fd)).map_err(|e| e.to_string())?; } for &(ref fd, ref rdy) in fds.iter() { poll.register(&EventedFd(fd), ofds.0, *rdy, PollOpt::level()).map_err(|e| e.to_string())?; } } ofds.1 = fds; res } } } fn get_pollfd_list(&self) -> Vec<(RawFd, Ready)> { let pfdl = unsafe { libusb_get_pollfds(self.context) }; let mut v = Vec::new(); let sl: &[*mut libusb_pollfd] = unsafe { slice::from_raw_parts(pfdl, 1024) }; let mut iter = sl.iter(); while let Some(x) = iter.next() { if x.is_null() { break; } let pfd = unsafe { &**x as &libusb_pollfd }; let mut rdy = Ready::empty(); if (pfd.events & POLLIN ) != 0 { rdy = rdy | Ready::readable(); } if (pfd.events & POLLOUT) != 0 { rdy = rdy | Ready::writable(); } v.push((pfd.fd, rdy)); } unsafe { libusb_free_pollfds(pfdl) }; v.sort(); debug!("get_pollfd_list: {:?}", v); v } fn spin_until_locked_and_ok_to_handle_events(&self) { 'retry: loop { if unsafe { libusb_try_lock_events(self.context) } == 0 { // got lock if unsafe { libusb_event_handling_ok(self.context) } == 0 { unsafe { libusb_unlock_events(self.context) }; warn!("libusb_event_handling_ok returned not ok, busy wait until ok (with 10ms sleep)"); sleep(Duration::from_millis(10)); continue 'retry; } break } else { warn!("could not get events lock with libusb_try_lock_events, busy wait until ok (with 10ms sleep)"); sleep(Duration::from_millis(10)); } } } } impl Evented for Context<UnixAsyncIo> { fn register(&self, poll: &Poll, token: Token, _interest: Ready, _opts: PollOpt) -> io::Result<()> { let mut ir = self.io.reg.lock().expect("Could not unlock UnixAsyncIo reg mutex"); if ir.is_some() { panic!("It is not safe to register libusb file descriptors multiple times") } self.spin_until_locked_and_ok_to_handle_events(); let fds = self.get_pollfd_list(); for &(ref fd, ref rdy) in fds.iter() { poll.register(&EventedFd(fd), token, *rdy, PollOpt::level())?; } *ir = Some((token, fds)); Ok(()) } fn reregister(&self, poll: &Poll, token: Token, interest: Ready, _opts: PollOpt) -> io::Result<()> { self.deregister(poll)?; self.register(poll, token, interest, PollOpt::level()) } fn deregister(&self, poll: &Poll) -> io::Result<()> { let mut ir = self.io.reg.lock().expect("Could not unlock UnixAsyncIo reg mutex"); match ir.take() { Some((_, fds)) => for (fd, _) in fds.into_iter() { poll.deregister(&EventedFd(&fd))?; }, None => panic!("Unable to deregister libusb file descriptors when they are not registered") } unsafe { libusb_unlock_events(self.context) }; Ok(()) } } } /// Library logging levels. pub enum LogLevel { /// No messages are printed by `libusb` (default). None, /// Error messages printed to `stderr`. Error, /// Warning and error messages are printed to `stderr`. Warning, /// Informational messages are printed to `stdout`. Warnings and error messages are printed to /// `stderr`. Info, /// Debug and informational messages are printed to `stdout`. Warnings and error messages are /// printed to `stderr`. Debug, } impl LogLevel { fn as_c_int(&self) -> c_int { match *self { LogLevel::None => LIBUSB_LOG_LEVEL_NONE, LogLevel::Error => LIBUSB_LOG_LEVEL_ERROR, LogLevel::Warning => LIBUSB_LOG_LEVEL_WARNING, LogLevel::Info => LIBUSB_LOG_LEVEL_INFO, LogLevel::Debug => LIBUSB_LOG_LEVEL_DEBUG, } } }
36.707692
122
0.544635
67feec61c820ad805c42cf4ad807d5c702bee2bc
18,290
// Copyright 2020 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. #![cfg(test)] use anyhow::Context as _; use fuchsia_async::TimeoutExt as _; use futures::stream::{self, StreamExt as _, TryStreamExt as _}; use net_declare::{fidl_ip, fidl_ip_v4, fidl_subnet}; use netstack_testing_common::environments::{KnownServices, Netstack2, TestSandboxExt as _}; use netstack_testing_common::Result; use netstack_testing_macros::variants_test; /// Endpoints in DHCP tests are either /// 1. attached to the server stack, which will have DHCP servers serving on them. /// 2. or attached to the client stack, which will have DHCP clients started on /// them to request addresses. enum DhcpTestEnv { Client, Server, } struct DhcpTestEndpoint<'a> { name: &'a str, env: DhcpTestEnv, /// static_addr is the static address configured on the endpoint before any /// server or client is started. static_addr: Option<fidl_fuchsia_net::Subnet>, /// want_addr is the address expected after a successfull address acquisition /// from a DHCP client. want_addr: Option<fidl_fuchsia_net::Subnet>, } /// A network can have multiple endpoints. Each endpoint can be attached to a /// different stack. struct DhcpTestNetwork<'a> { name: &'a str, eps: &'a mut [DhcpTestEndpoint<'a>], } // TODO(fxbug.dev/62554): the tests below are awful and contain lots of repetition. Reduce // repetition. #[variants_test] async fn acquire_dhcp<E: netemul::Endpoint>(name: &str) -> Result { test_dhcp::<E>( name, &mut [DhcpTestNetwork { name: "net", eps: &mut [ DhcpTestEndpoint { name: "server-ep", env: DhcpTestEnv::Server, static_addr: Some(fidl_subnet!(192.168.0.1/24)), want_addr: None, }, DhcpTestEndpoint { name: "client-ep", env: DhcpTestEnv::Client, static_addr: None, want_addr: Some(fidl_fuchsia_net::Subnet { addr: fidl_ip!(192.168.0.2), prefix_len: 25, }), }, ], }], &mut [&mut [ fidl_fuchsia_net_dhcp::Parameter::IpAddrs(vec![fidl_ip_v4!(192.168.0.1)]), fidl_fuchsia_net_dhcp::Parameter::AddressPool(fidl_fuchsia_net_dhcp::AddressPool { network_id: Some(fidl_ip_v4!(192.168.0.0)), broadcast: Some(fidl_ip_v4!(192.168.0.127)), mask: Some(fidl_ip_v4!(255.255.255.128)), pool_range_start: Some(fidl_ip_v4!(192.168.0.2)), pool_range_stop: Some(fidl_ip_v4!(192.168.0.5)), }), ]], 3, ) .await } #[variants_test] async fn acquire_dhcp_with_dhcpd_bound_device<E: netemul::Endpoint>(name: &str) -> Result { test_dhcp::<E>( name, &mut [DhcpTestNetwork { name: "net", eps: &mut [ DhcpTestEndpoint { name: "server-ep", env: DhcpTestEnv::Server, static_addr: Some(fidl_subnet!(192.168.0.1/24)), want_addr: None, }, DhcpTestEndpoint { name: "client-ep", env: DhcpTestEnv::Client, static_addr: None, want_addr: Some(fidl_fuchsia_net::Subnet { addr: fidl_ip!(192.168.0.2), prefix_len: 25, }), }, ], }], &mut [&mut [ fidl_fuchsia_net_dhcp::Parameter::IpAddrs(vec![fidl_ip_v4!(192.168.0.1)]), fidl_fuchsia_net_dhcp::Parameter::AddressPool(fidl_fuchsia_net_dhcp::AddressPool { network_id: Some(fidl_ip_v4!(192.168.0.0)), broadcast: Some(fidl_ip_v4!(192.168.0.127)), mask: Some(fidl_ip_v4!(255.255.255.128)), pool_range_start: Some(fidl_ip_v4!(192.168.0.2)), pool_range_stop: Some(fidl_ip_v4!(192.168.0.5)), }), fidl_fuchsia_net_dhcp::Parameter::BoundDeviceNames(vec!["eth2".to_string()]), ]], 1, ) .await } #[variants_test] async fn acquire_dhcp_with_multiple_network<E: netemul::Endpoint>(name: &str) -> Result { test_dhcp::<E>( name, &mut [ DhcpTestNetwork { name: "net1", eps: &mut [ DhcpTestEndpoint { name: "server-ep1", env: DhcpTestEnv::Server, static_addr: Some(fidl_subnet!(192.168.0.1/24)), want_addr: None, }, DhcpTestEndpoint { name: "client-ep1", env: DhcpTestEnv::Client, static_addr: None, want_addr: Some(fidl_fuchsia_net::Subnet { addr: fidl_ip!(192.168.0.2), prefix_len: 25, }), }, ], }, DhcpTestNetwork { name: "net2", eps: &mut [ DhcpTestEndpoint { name: "server-ep2", env: DhcpTestEnv::Server, static_addr: Some(fidl_subnet!(192.168.1.1/24)), want_addr: None, }, DhcpTestEndpoint { name: "client-ep2", env: DhcpTestEnv::Client, static_addr: None, want_addr: Some(fidl_fuchsia_net::Subnet { addr: fidl_ip!(192.168.1.2), prefix_len: 24, }), }, ], }, ], &mut [ &mut [ fidl_fuchsia_net_dhcp::Parameter::IpAddrs(vec![fidl_ip_v4!(192.168.0.1)]), fidl_fuchsia_net_dhcp::Parameter::AddressPool(fidl_fuchsia_net_dhcp::AddressPool { network_id: Some(fidl_ip_v4!(192.168.0.0)), broadcast: Some(fidl_ip_v4!(192.168.0.127)), mask: Some(fidl_ip_v4!(255.255.255.128)), pool_range_start: Some(fidl_ip_v4!(192.168.0.2)), pool_range_stop: Some(fidl_ip_v4!(192.168.0.5)), }), fidl_fuchsia_net_dhcp::Parameter::BoundDeviceNames(vec!["eth2".to_string()]), ], &mut [ fidl_fuchsia_net_dhcp::Parameter::IpAddrs(vec![fidl_ip_v4!(192.168.1.1)]), fidl_fuchsia_net_dhcp::Parameter::AddressPool(fidl_fuchsia_net_dhcp::AddressPool { network_id: Some(fidl_ip_v4!(192.168.1.0)), broadcast: Some(fidl_ip_v4!(192.168.1.255)), mask: Some(fidl_ip_v4!(255.255.255.0)), pool_range_start: Some(fidl_ip_v4!(192.168.1.2)), pool_range_stop: Some(fidl_ip_v4!(192.168.1.5)), }), fidl_fuchsia_net_dhcp::Parameter::BoundDeviceNames(vec!["eth3".to_string()]), ], ], 1, ) .await } /// test_dhcp starts 2 netstacks, client and server, and attaches endpoints to /// them in potentially multiple networks based on the input network /// configuration. /// /// DHCP servers are started on the server side, based on the dhcpd config files /// from the input paths. Notice based on the configuration, it is possible that /// multiple servers are started and bound to different endpoints. /// /// DHCP clients are started on each client endpoint, attempt to acquire /// addresses through DHCP and compare them to expected address. async fn test_dhcp<E: netemul::Endpoint>( name: &str, network_configs: &mut [DhcpTestNetwork<'_>], dhcp_parameters: &mut [&mut [fidl_fuchsia_net_dhcp::Parameter]], cycles: u32, ) -> Result { let sandbox = netemul::TestSandbox::new().context("failed to create sandbox")?; let sandbox_ref = &sandbox; let server_environments = stream::iter(dhcp_parameters) .enumerate() .then(|(id, parameters)| async move { let server_environment = sandbox_ref .create_netstack_environment_with::<Netstack2, _, _>( format!("{}_server_{}", name, id), &[KnownServices::SecureStash], ) .context("failed to create server environment")?; let launcher = server_environment.get_launcher().context("failed to create launcher")?; let dhcpd = fuchsia_component::client::launch( &launcher, KnownServices::DhcpServer.get_url().to_string(), None, ) .context("failed to start dhcpd")?; let dhcp_server = dhcpd .connect_to_service::<fidl_fuchsia_net_dhcp::Server_Marker>() .context("failed to connect to DHCP server")?; let dhcp_server_ref = &dhcp_server; let () = stream::iter(parameters.iter_mut()) .map(Ok) .try_for_each_concurrent(None, |parameter| async move { dhcp_server_ref .set_parameter(parameter) .await .context("failed to call dhcp/Server.SetParameter")? .map_err(fuchsia_zircon::Status::from_raw) .with_context(|| { format!("dhcp/Server.SetParameter({:?}) returned error", parameter) }) }) .await?; Result::Ok((server_environment, dhcpd)) }) .try_collect::<Vec<_>>() .await?; let client_environment = sandbox .create_netstack_environment::<Netstack2, _>(format!("{}_client", name)) .context("failed to create client environment")?; let client_env_ref = &client_environment; let server_environments_ref = &server_environments; let networks = stream::iter(network_configs) .then(|DhcpTestNetwork { name, eps }| async move { let network = sandbox_ref.create_network(*name).await.context("failed to create network")?; // `network` is returned at the end of the scope so it is not // dropped. let network_ref = &network; let eps = stream::iter(eps.into_iter()) .then(|DhcpTestEndpoint { name, env, static_addr, want_addr }| async move { let test_environments = match env { DhcpTestEnv::Client => { stream::iter(std::iter::once(client_env_ref)).left_stream() } DhcpTestEnv::Server => { stream::iter(server_environments_ref.iter().map(|(env, _dhcpd)| env)) .right_stream() } }; let config = match static_addr { Some(addr) => { // NOTE: InterfaceAddress does not currently // implement Clone, it probably will at some point // as FIDL bindings evolve. netemul::InterfaceConfig::StaticIp(fidl_fuchsia_net::Subnet { addr: addr.addr, prefix_len: addr.prefix_len, }) } None => netemul::InterfaceConfig::None, }; let name = &*name; let config = &config; let interfaces = test_environments .enumerate() .then(|(id, test_environment)| async move { let name = format!("{}-{}", name, id); test_environment .join_network::<E, _>(network_ref, name, config) .await .context("failed to create endpoint") }) .try_collect::<Vec<_>>() .await?; Result::Ok((env, want_addr, interfaces)) }) .try_collect::<Vec<_>>() .await?; Result::Ok((network, eps)) }) .try_collect::<Vec<_>>() .await?; let () = stream::iter(server_environments.iter()) .map(Ok) .try_for_each_concurrent(None, |(_env, dhcpd)| async move { let dhcp_server = dhcpd .connect_to_service::<fidl_fuchsia_net_dhcp::Server_Marker>() .context("failed to connect to DHCP server")?; dhcp_server .start_serving() .await .context("failed to call dhcp/Server.StartServing")? .map_err(fuchsia_zircon::Status::from_raw) .context("dhcp/Server.StartServing returned error") }) .await?; let () = stream::iter( // Iterate over references to prevent filter from dropping endpoints. networks .iter() .flat_map(|(_, eps)| eps) .filter(|(env, _, _)| match env { // We only care about whether client endpoints can acquire // addresses through DHCP client or not. DhcpTestEnv::Client => true, _ => false, }) .map(Result::Ok), ) .try_for_each(|(_, addr, interfaces)| async move { let want_addr = addr.ok_or(anyhow::format_err!("expected address must be set for client endpoints"))?; let bind = || { use netemul::EnvironmentUdpSocket as _; let fidl_fuchsia_net::Subnet { addr, prefix_len: _ } = want_addr; let fidl_fuchsia_net_ext::IpAddress(ip_address) = addr.into(); std::net::UdpSocket::bind_in_env( client_env_ref, std::net::SocketAddr::new(ip_address, 0), ) }; let client_interface_state = client_env_ref .connect_to_service::<fidl_fuchsia_net_interfaces::StateMarker>() .context("failed to connect to client fuchsia.net.interfaces/State")?; let (watcher, watcher_server) = ::fidl::endpoints::create_proxy::<fidl_fuchsia_net_interfaces::WatcherMarker>()?; let () = client_interface_state .get_watcher(fidl_fuchsia_net_interfaces::WatcherOptions {}, watcher_server) .context("failed to initialize interface watcher")?; for interface in interfaces.iter() { let mut properties = fidl_fuchsia_net_interfaces_ext::InterfaceState::Unknown(interface.id()); for _ in 0..cycles { // Enable the interface and assert that binding fails before the address is acquired. let () = interface.stop_dhcp().await.context("failed to stop DHCP")?; let () = interface.set_link_up(true).await.context("failed to bring link up")?; matches::assert_matches!(bind().await, Err(_)); let () = interface.start_dhcp().await.context("failed to start DHCP")?; let addr = fidl_fuchsia_net_interfaces_ext::wait_interface_with_id( fidl_fuchsia_net_interfaces_ext::event_stream(watcher.clone()), &mut properties, |properties| { properties.addresses.as_ref()?.iter().filter_map(|a| a.addr).find(|a| { match a.addr { fidl_fuchsia_net::IpAddress::Ipv4(_) => true, fidl_fuchsia_net::IpAddress::Ipv6(_) => false, } }) }, ) .on_timeout( // Netstack's DHCP client retries every 3 seconds. At the time of writing, dhcpd loses // the race here and only starts after the first request from the DHCP client, which // results in a 3 second toll. This test typically takes ~4.5 seconds; we apply a large // multiple to be safe. fuchsia_async::Time::after(fuchsia_zircon::Duration::from_seconds(60)), || Err(anyhow::anyhow!("timed out")), ) .await .context("failed to observe DHCP acquisition on client ep {}")?; assert_eq!(addr, want_addr); // Address acquired; bind is expected to succeed. matches::assert_matches!(bind().await, Ok(_)); // Set interface online signal to down and wait for address to be removed. let () = interface.set_link_up(false).await.context("failed to bring link down")?; let () = fidl_fuchsia_net_interfaces_ext::wait_interface_with_id( fidl_fuchsia_net_interfaces_ext::event_stream(watcher.clone()), &mut properties, |properties| { properties.addresses.as_ref().map_or(Some(()), |addresses| { if addresses.iter().any(|a| a.addr == Some(addr)) { None } else { Some(()) } }) }, ) .await .context("failed to wait for address removal")?; } } Result::Ok(()) }) .await?; Ok(()) }
41.757991
107
0.510279
89becdf2e650e8cf474b68960ebe6307626cb379
1,916
use std::sync::Arc; use consensus::{Consensus, ConsensusEvent, ConsensusProtocol}; use parking_lot::RwLock; use json::JsonValue; use crate::handler::Method; use crate::handlers::Module; pub struct ConsensusHandler<P> where P: ConsensusProtocol + 'static { pub consensus: Arc<Consensus<P>>, state: Arc<RwLock<ConsensusHandlerState>>, } pub struct ConsensusHandlerState { consensus: &'static str, } impl<P> ConsensusHandler<P> where P: ConsensusProtocol + 'static { pub fn new(consensus: Arc<Consensus<P>>) -> Self { let state = ConsensusHandlerState { consensus: "syncing", }; let state = Arc::new(RwLock::new(state)); let this = Self { consensus: Arc::clone(&consensus), state: Arc::clone(&state), }; // Register for consensus events. { trace!("Register listener for consensus"); let state = Arc::downgrade(&state); consensus.notifier.write().register(move |e: &ConsensusEvent| { trace!("Consensus Event: {:?}", e); if let Some(state) = state.upgrade() { match e { ConsensusEvent::Established => { state.write().consensus = "established" }, ConsensusEvent::Lost => { state.write().consensus = "lost" }, ConsensusEvent::Syncing => { state.write().consensus = "syncing" }, _ => () } } else { // TODO Remove listener } }); } this } fn consensus(&self, _params: &[JsonValue]) -> Result<JsonValue, JsonValue> { Ok(self.state.read().consensus.into()) } } impl<P: ConsensusProtocol + 'static> Module for ConsensusHandler<P> { rpc_module_methods! { "consensus" => consensus, } }
29.030303
99
0.546973
69f3bf44043fd6de8c0129cb952665f5df7837f8
19,838
//! Server launchers use std::{net::IpAddr, path::PathBuf, process, time::Duration}; use clap::{Arg, ArgGroup, ArgMatches, Command, ErrorKind as ClapErrorKind}; use futures::future::{self, Either}; use log::{info, trace}; use tokio::{self, runtime::Builder}; use shadowsocks_service::{ acl::AccessControl, config::{read_variable_field_value, Config, ConfigType, ManagerConfig}, run_server, shadowsocks::{ config::{ManagerAddr, Mode, ServerAddr, ServerConfig}, crypto::{available_ciphers, CipherKind}, plugin::PluginConfig, }, }; #[cfg(feature = "logging")] use crate::logging; use crate::{ config::{Config as ServiceConfig, RuntimeMode}, monitor, validator, }; /// Defines command line options pub fn define_command_line_options(mut app: Command<'_>) -> Command<'_> { app = app .arg( Arg::new("CONFIG") .short('c') .long("config") .takes_value(true) .help("Shadowsocks configuration file (https://shadowsocks.org/en/config/quick-guide.html)"), ) .arg( Arg::new("OUTBOUND_BIND_ADDR") .short('b') .long("outbound-bind-addr") .takes_value(true) .alias("bind-addr") .validator(validator::validate_ip_addr) .help("Bind address, outbound socket will bind this address"), ) .arg( Arg::new("OUTBOUND_BIND_INTERFACE") .long("outbound-bind-interface") .takes_value(true) .help("Set SO_BINDTODEVICE / IP_BOUND_IF / IP_UNICAST_IF option for outbound socket"), ) .arg( Arg::new("SERVER_ADDR") .short('s') .long("server-addr") .takes_value(true) .validator(validator::validate_server_addr) .requires("ENCRYPT_METHOD") .help("Server address"), ) .arg( Arg::new("PASSWORD") .short('k') .long("password") .takes_value(true) .requires("SERVER_ADDR") .help("Server's password"), ) .arg( Arg::new("ENCRYPT_METHOD") .short('m') .long("encrypt-method") .takes_value(true) .requires("SERVER_ADDR") .possible_values(available_ciphers()) .help("Server's encryption method"), ) .arg( Arg::new("TIMEOUT") .long("timeout") .takes_value(true) .validator(validator::validate_u64) .requires("SERVER_ADDR") .help("Server's timeout seconds for TCP relay"), ) .group( ArgGroup::new("SERVER_CONFIG").arg("SERVER_ADDR") ) .arg( Arg::new("UDP_ONLY") .short('u') .conflicts_with("TCP_AND_UDP") .requires("SERVER_ADDR") .help("Server mode UDP_ONLY"), ) .arg( Arg::new("TCP_AND_UDP") .short('U') .requires("SERVER_ADDR") .help("Server mode TCP_AND_UDP"), ) .arg( Arg::new("PLUGIN") .long("plugin") .takes_value(true) .requires("SERVER_ADDR") .help("SIP003 (https://shadowsocks.org/en/wiki/Plugin.html) plugin"), ) .arg( Arg::new("PLUGIN_OPT") .long("plugin-opts") .takes_value(true) .requires("PLUGIN") .help("Set SIP003 plugin options"), ) .arg(Arg::new("MANAGER_ADDR").long("manager-addr").takes_value(true).alias("manager-address").help("ShadowSocks Manager (ssmgr) address, could be \"IP:Port\", \"Domain:Port\" or \"/path/to/unix.sock\"")) .arg(Arg::new("ACL").long("acl").takes_value(true).help("Path to ACL (Access Control List)")) .arg(Arg::new("DNS").long("dns").takes_value(true).help("DNS nameservers, formatted like [(tcp|udp)://]host[:port][,host[:port]]..., or unix:///path/to/dns, or predefined keys like \"google\", \"cloudflare\"")) .arg(Arg::new("TCP_NO_DELAY").long("tcp-no-delay").alias("no-delay").help("Set TCP_NODELAY option for sockets")) .arg(Arg::new("TCP_FAST_OPEN").long("tcp-fast-open").alias("fast-open").help("Enable TCP Fast Open (TFO)")) .arg(Arg::new("TCP_KEEP_ALIVE").long("tcp-keep-alive").takes_value(true).validator(validator::validate_u64).help("Set TCP keep alive timeout seconds")) .arg(Arg::new("UDP_TIMEOUT").long("udp-timeout").takes_value(true).validator(validator::validate_u64).help("Timeout seconds for UDP relay")) .arg(Arg::new("UDP_MAX_ASSOCIATIONS").long("udp-max-associations").takes_value(true).validator(validator::validate_u64).help("Maximum associations to be kept simultaneously for UDP relay")) .arg(Arg::new("INBOUND_SEND_BUFFER_SIZE").long("inbound-send-buffer-size").takes_value(true).validator(validator::validate_u32).help("Set inbound sockets' SO_SNDBUF option")) .arg(Arg::new("INBOUND_RECV_BUFFER_SIZE").long("inbound-recv-buffer-size").takes_value(true).validator(validator::validate_u32).help("Set inbound sockets' SO_RCVBUF option")) .arg(Arg::new("OUTBOUND_SEND_BUFFER_SIZE").long("outbound-send-buffer-size").takes_value(true).validator(validator::validate_u32).help("Set outbound sockets' SO_SNDBUF option")) .arg(Arg::new("OUTBOUND_RECV_BUFFER_SIZE").long("outbound-recv-buffer-size").takes_value(true).validator(validator::validate_u32).help("Set outbound sockets' SO_RCVBUF option")) .arg( Arg::new("IPV6_FIRST") .short('6') .help("Resolve hostname to IPv6 address first"), ); #[cfg(feature = "logging")] { app = app .arg( Arg::new("VERBOSE") .short('v') .multiple_occurrences(true) .help("Set log level"), ) .arg( Arg::new("LOG_WITHOUT_TIME") .long("log-without-time") .help("Log without datetime prefix"), ) .arg( Arg::new("LOG_CONFIG") .long("log-config") .takes_value(true) .help("log4rs configuration file"), ); } #[cfg(unix)] { app = app .arg(Arg::new("DAEMONIZE").short('d').long("daemonize").help("Daemonize")) .arg( Arg::new("DAEMONIZE_PID_PATH") .long("daemonize-pid") .takes_value(true) .help("File path to store daemonized process's PID"), ); } #[cfg(all(unix, not(target_os = "android")))] { app = app.arg( Arg::new("NOFILE") .short('n') .long("nofile") .takes_value(true) .help("Set RLIMIT_NOFILE with both soft and hard limit"), ); } #[cfg(any(target_os = "linux", target_os = "android"))] { app = app.arg( Arg::new("OUTBOUND_FWMARK") .long("outbound-fwmark") .takes_value(true) .validator(validator::validate_u32) .help("Set SO_MARK option for outbound sockets"), ); } #[cfg(target_os = "freebsd")] { app = app.arg( Arg::new("OUTBOUND_USER_COOKIE") .long("outbound-user-cookie") .takes_value(true) .validator(validator::validate_u32) .help("Set SO_USER_COOKIE option for outbound sockets"), ); } #[cfg(feature = "multi-threaded")] { app = app .arg( Arg::new("SINGLE_THREADED") .long("single-threaded") .help("Run the program all in one thread"), ) .arg( Arg::new("WORKER_THREADS") .long("worker-threads") .takes_value(true) .validator(validator::validate_usize) .help("Sets the number of worker threads the `Runtime` will use"), ); } app } /// Program entrance `main` pub fn main(matches: &ArgMatches) { let (config, runtime) = { let config_path_opt = matches.value_of("CONFIG").map(PathBuf::from).or_else(|| { if !matches.is_present("SERVER_CONFIG") { match crate::config::get_default_config_path() { None => None, Some(p) => { println!("loading default config {:?}", p); Some(p) } } } else { None } }); let mut service_config = match config_path_opt { Some(ref config_path) => match ServiceConfig::load_from_file(config_path) { Ok(c) => c, Err(err) => { eprintln!("loading config {:?}, {}", config_path, err); process::exit(crate::EXIT_CODE_LOAD_CONFIG_FAILURE); } }, None => ServiceConfig::default(), }; service_config.set_options(matches); #[cfg(feature = "logging")] match service_config.log.config_path { Some(ref path) => { logging::init_with_file(path); } None => { logging::init_with_config("sslocal", &service_config.log); } } trace!("{:?}", service_config); let mut config = match config_path_opt { Some(cpath) => match Config::load_from_file(&cpath, ConfigType::Server) { Ok(cfg) => cfg, Err(err) => { eprintln!("loading config {:?}, {}", cpath, err); process::exit(crate::EXIT_CODE_LOAD_CONFIG_FAILURE); } }, None => Config::new(ConfigType::Server), }; if let Some(svr_addr) = matches.value_of("SERVER_ADDR") { let method = matches.value_of_t_or_exit::<CipherKind>("ENCRYPT_METHOD"); let password = match matches.value_of_t::<String>("PASSWORD") { Ok(pwd) => read_variable_field_value(&pwd).into(), Err(err) => { // NOTE: svr_addr should have been checked by crate::validator if method.is_none() { // If method doesn't need a key (none, plain), then we can leave it empty String::new() } else { match crate::password::read_server_password(svr_addr) { Ok(pwd) => pwd, Err(..) => err.exit(), } } } }; let svr_addr = svr_addr.parse::<ServerAddr>().expect("server-addr"); let timeout = match matches.value_of_t::<u64>("TIMEOUT") { Ok(t) => Some(Duration::from_secs(t)), Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => None, Err(err) => err.exit(), }; let mut sc = ServerConfig::new(svr_addr, password, method); if let Some(timeout) = timeout { sc.set_timeout(timeout); } if let Some(p) = matches.value_of("PLUGIN") { let plugin = PluginConfig { plugin: p.to_owned(), plugin_opts: matches.value_of("PLUGIN_OPT").map(ToOwned::to_owned), plugin_args: Vec::new(), }; sc.set_plugin(plugin); } // For historical reason, servers that are created from command-line have to be tcp_only. sc.set_mode(Mode::TcpOnly); if matches.is_present("UDP_ONLY") { sc.set_mode(Mode::UdpOnly); } if matches.is_present("TCP_AND_UDP") { sc.set_mode(Mode::TcpAndUdp); } config.server.push(sc); } if matches.is_present("TCP_NO_DELAY") { config.no_delay = true; } if matches.is_present("TCP_FAST_OPEN") { config.fast_open = true; } match matches.value_of_t::<u64>("TCP_KEEP_ALIVE") { Ok(keep_alive) => config.keep_alive = Some(Duration::from_secs(keep_alive)), Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => {} Err(err) => err.exit(), } #[cfg(any(target_os = "linux", target_os = "android"))] match matches.value_of_t::<u32>("OUTBOUND_FWMARK") { Ok(mark) => config.outbound_fwmark = Some(mark), Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => {} Err(err) => err.exit(), } #[cfg(target_os = "freebsd")] match matches.value_of_t::<u32>("OUTBOUND_USER_COOKIE") { Ok(user_cookie) => config.outbound_user_cookie = Some(user_cookie), Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => {} Err(err) => err.exit(), } match matches.value_of_t::<String>("OUTBOUND_BIND_INTERFACE") { Ok(iface) => config.outbound_bind_interface = Some(iface), Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => {} Err(err) => err.exit(), } match matches.value_of_t::<ManagerAddr>("MANAGER_ADDR") { Ok(addr) => { if let Some(ref mut manager_config) = config.manager { manager_config.addr = addr; } else { config.manager = Some(ManagerConfig::new(addr)); } } Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => {} Err(err) => err.exit(), } #[cfg(all(unix, not(target_os = "android")))] match matches.value_of_t::<u64>("NOFILE") { Ok(nofile) => config.nofile = Some(nofile), Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => { crate::sys::adjust_nofile(); } Err(err) => err.exit(), } if let Some(acl_file) = matches.value_of("ACL") { let acl = match AccessControl::load_from_file(acl_file) { Ok(acl) => acl, Err(err) => { eprintln!("loading ACL \"{}\", {}", acl_file, err); process::exit(crate::EXIT_CODE_LOAD_ACL_FAILURE); } }; config.acl = Some(acl); } if let Some(dns) = matches.value_of("DNS") { config.set_dns_formatted(dns).expect("dns"); } if matches.is_present("IPV6_FIRST") { config.ipv6_first = true; } match matches.value_of_t::<u64>("UDP_TIMEOUT") { Ok(udp_timeout) => config.udp_timeout = Some(Duration::from_secs(udp_timeout)), Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => {} Err(err) => err.exit(), } match matches.value_of_t::<usize>("UDP_MAX_ASSOCIATIONS") { Ok(udp_max_assoc) => config.udp_max_associations = Some(udp_max_assoc), Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => {} Err(err) => err.exit(), } match matches.value_of_t::<u32>("INBOUND_SEND_BUFFER_SIZE") { Ok(bs) => config.inbound_send_buffer_size = Some(bs), Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => {} Err(err) => err.exit(), } match matches.value_of_t::<u32>("INBOUND_RECV_BUFFER_SIZE") { Ok(bs) => config.inbound_recv_buffer_size = Some(bs), Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => {} Err(err) => err.exit(), } match matches.value_of_t::<u32>("OUTBOUND_SEND_BUFFER_SIZE") { Ok(bs) => config.outbound_send_buffer_size = Some(bs), Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => {} Err(err) => err.exit(), } match matches.value_of_t::<u32>("OUTBOUND_RECV_BUFFER_SIZE") { Ok(bs) => config.outbound_recv_buffer_size = Some(bs), Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => {} Err(err) => err.exit(), } match matches.value_of_t::<IpAddr>("OUTBOUND_BIND_ADDR") { Ok(bind_addr) => config.outbound_bind_addr = Some(bind_addr), Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => {} Err(err) => err.exit(), } // DONE READING options if config.server.is_empty() { eprintln!( "missing proxy servers, consider specifying it by \ --server-addr, --encrypt-method, --password command line option, \ or configuration file, check more details in https://shadowsocks.org/en/config/quick-guide.html" ); return; } if let Err(err) = config.check_integrity() { eprintln!("config integrity check failed, {}", err); return; } #[cfg(unix)] if matches.is_present("DAEMONIZE") || matches.is_present("DAEMONIZE_PID_PATH") { use crate::daemonize; daemonize::daemonize(matches.value_of("DAEMONIZE_PID_PATH")); } info!("shadowsocks server {} build {}", crate::VERSION, crate::BUILD_TIME); let mut worker_count = 1; let mut builder = match service_config.runtime.mode { RuntimeMode::SingleThread => Builder::new_current_thread(), #[cfg(feature = "multi-threaded")] RuntimeMode::MultiThread => { let mut builder = Builder::new_multi_thread(); if let Some(worker_threads) = service_config.runtime.worker_count { worker_count = worker_threads; builder.worker_threads(worker_threads); } else { worker_count = num_cpus::get(); } builder } }; config.worker_count = worker_count; let runtime = builder.enable_all().build().expect("create tokio Runtime"); (config, runtime) }; runtime.block_on(async move { let abort_signal = monitor::create_signal_monitor(); let server = run_server(config); tokio::pin!(abort_signal); tokio::pin!(server); match future::select(server, abort_signal).await { // Server future resolved without an error. This should never happen. Either::Left((Ok(..), ..)) => { eprintln!("server exited unexpectedly"); process::exit(crate::EXIT_CODE_SERVER_EXIT_UNEXPECTEDLY); } // Server future resolved with error, which are listener errors in most cases Either::Left((Err(err), ..)) => { eprintln!("server aborted with {}", err); process::exit(crate::EXIT_CODE_SERVER_ABORTED); } // The abort signal future resolved. Means we should just exit. Either::Right(_) => (), } }); }
38.670565
218
0.520365
5b3fe4ea86a5e89fbe9cbb160564b969c23cbbe4
225
#![feature(test)] extern crate test; extern crate incoming; #[bench] fn universe_ticks(b: &mut test::Bencher) { let mut universe = wasm_game_of_life::Universe::new(); b.iter(|| { universe.tick(); }); }
16.071429
58
0.622222
e884bc4d5c413f18ed1f98376009a9c69541dea6
1,839
// 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. // run-pass // If `Mul` used an associated type for its output, this test would // work more smoothly. use std::ops::Mul; #[derive(Copy, Clone)] struct Vec2 { x: f64, y: f64 } // methods we want to export as methods as well as operators impl Vec2 { #[inline(always)] fn vmul(self, other: f64) -> Vec2 { Vec2 { x: self.x * other, y: self.y * other } } } // Right-hand-side operator visitor pattern trait RhsOfVec2Mul { type Result; fn mul_vec2_by(&self, lhs: &Vec2) -> Self::Result; } // Vec2's implementation of Mul "from the other side" using the above trait impl<Res, Rhs: RhsOfVec2Mul<Result=Res>> Mul<Rhs> for Vec2 { type Output = Res; fn mul(self, rhs: Rhs) -> Res { rhs.mul_vec2_by(&self) } } // Implementation of 'f64 as right-hand-side of Vec2::Mul' impl RhsOfVec2Mul for f64 { type Result = Vec2; fn mul_vec2_by(&self, lhs: &Vec2) -> Vec2 { lhs.vmul(*self) } } // Usage with failing inference pub fn main() { let a = Vec2 { x: 3.0f64, y: 4.0f64 }; // the following compiles and works properly let v1: Vec2 = a * 3.0f64; println!("{} {}", v1.x, v1.y); // the following compiles but v2 will not be Vec2 yet and // using it later will cause an error that the type of v2 // must be known let v2 = a * 3.0f64; println!("{} {}", v2.x, v2.y); // error regarding v2's type }
27.863636
75
0.656335
fef7b172016fd6a17fd23f9c2cdc9b4ef7505458
2,934
// Copyright 2018 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT // http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD // https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied, // modified, or distributed except according to those terms. Please review the Licences for the // specific language governing permissions and limitations relating to use of the SAFE Network // Software. //! # crust //! //! Reliable peer-to-peer network connections in Rust with NAT traversal. //! See [`Service`] documentation which is the main structure to use crust services. //! //! [`Service`]: struct.Service.html #![doc( html_logo_url = "https://raw.githubusercontent.com/maidsafe/QA/master/Images/maidsafe_logo.png", html_favicon_url = "https://maidsafe.net/img/favicon.ico", test(attr(forbid(warnings))) )] // For explanation of lint checks, run `rustc -W help` or see // https://github.com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md #![forbid( exceeding_bitshifts, mutable_transmutes, no_mangle_const_items, unknown_crate_types, warnings )] #![deny( deprecated, improper_ctypes, missing_docs, non_shorthand_field_patterns, overflowing_literals, plugin_as_library, stable_features, unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, unused_attributes, unused_comparisons, unused_features, unused_parens, while_true )] #![warn( trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] #![allow( box_pointers, missing_copy_implementations, missing_debug_implementations, variant_size_differences )] // FIXME: `needless_pass_by_value` and `clone_on_ref_ptr` required to make no intrusive changes // on code in the master branch #![allow( clippy::clone_on_ref_ptr, clippy::decimal_literal_representation, clippy::needless_pass_by_value, clippy::too_many_arguments )] #![recursion_limit = "128"] #[macro_use] extern crate log; #[allow(clippy::useless_attribute)] #[macro_use] extern crate quick_error; #[macro_use] extern crate serde_derive; #[macro_use] extern crate unwrap; #[cfg(test)] extern crate serde_json; #[cfg(test)] #[macro_use] mod tests; mod common; mod main; mod nat; mod service_discovery; pub use crate::common::{CrustUser, PeerInfo, Uid}; pub use crate::main::{ read_config_file, Config, ConnectionInfoResult, CrustError, Event, PrivConnectionInfo, PubConnectionInfo, Service, }; pub use socket_collection::Priority; /// Used to receive events from a `Service`. pub type CrustEventSender<UID> = ::maidsafe_utilities::event_sender::MaidSafeObserver<Event<UID>>; /// Crust's result type pub type Res<T> = Result<T, CrustError>;
27.679245
100
0.740968
d6ec8f0d979e0cde74402f03afdcc9dfa10cdb3f
42,825
// 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. // // ignore-lexer-test FIXME #15679 //! An owned, growable string that enforces that its contents are valid UTF-8. #![stable(feature = "rust1", since = "1.0.0")] use core::prelude::*; use core::default::Default; use core::error::Error; use core::fmt; use core::hash; use core::iter::{IntoIterator, FromIterator}; use core::mem; use core::ops::{self, Deref, Add, Index}; use core::ptr; use core::raw::Slice as RawSlice; use unicode::str as unicode_str; use unicode::str::Utf16Item; use borrow::{Cow, IntoCow}; use str::{self, CharRange, FromStr, Utf8Error}; use vec::{DerefVec, Vec, as_vec}; /// A growable string stored as a UTF-8 encoded buffer. #[derive(Clone, PartialOrd, Eq, Ord)] #[stable(feature = "rust1", since = "1.0.0")] pub struct String { vec: Vec<u8>, } /// A possible error value from the `String::from_utf8` function. #[stable(feature = "rust1", since = "1.0.0")] #[derive(Debug)] pub struct FromUtf8Error { bytes: Vec<u8>, error: Utf8Error, } /// A possible error value from the `String::from_utf16` function. #[stable(feature = "rust1", since = "1.0.0")] #[derive(Debug)] pub struct FromUtf16Error(()); impl String { /// Creates a new string buffer initialized with the empty string. /// /// # Examples /// /// ``` /// let mut s = String::new(); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn new() -> String { String { vec: Vec::new(), } } /// Creates a new string buffer with the given capacity. /// The string will be able to hold exactly `capacity` bytes without /// reallocating. If `capacity` is 0, the string will not allocate. /// /// # Examples /// /// ``` /// let mut s = String::with_capacity(10); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn with_capacity(capacity: usize) -> String { String { vec: Vec::with_capacity(capacity), } } /// Creates a new string buffer from the given string. /// /// # Examples /// /// ``` /// let s = String::from_str("hello"); /// assert_eq!(s.as_slice(), "hello"); /// ``` #[inline] #[unstable(feature = "collections", reason = "needs investigation to see if to_string() can match perf")] pub fn from_str(string: &str) -> String { String { vec: ::slice::SliceExt::to_vec(string.as_bytes()) } } /// Returns the vector as a string buffer, if possible, taking care not to /// copy it. /// /// # Failure /// /// If the given vector is not valid UTF-8, then the original vector and the /// corresponding error is returned. /// /// # Examples /// /// ```rust /// use std::str::Utf8Error; /// /// let hello_vec = vec![104, 101, 108, 108, 111]; /// let s = String::from_utf8(hello_vec).unwrap(); /// assert_eq!(s, "hello"); /// /// let invalid_vec = vec![240, 144, 128]; /// let s = String::from_utf8(invalid_vec).err().unwrap(); /// assert_eq!(s.utf8_error(), Utf8Error::TooShort); /// assert_eq!(s.into_bytes(), [240, 144, 128]); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> { match str::from_utf8(&vec) { Ok(..) => Ok(String { vec: vec }), Err(e) => Err(FromUtf8Error { bytes: vec, error: e }) } } /// Converts a vector of bytes to a new UTF-8 string. /// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER. /// /// # Examples /// /// ```rust /// let input = b"Hello \xF0\x90\x80World"; /// let output = String::from_utf8_lossy(input); /// assert_eq!(output.as_slice(), "Hello \u{FFFD}World"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> Cow<'a, str> { let mut i = 0; match str::from_utf8(v) { Ok(s) => return Cow::Borrowed(s), Err(e) => { if let Utf8Error::InvalidByte(firstbad) = e { i = firstbad; } } } const TAG_CONT_U8: u8 = 128; const REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8 let total = v.len(); fn unsafe_get(xs: &[u8], i: usize) -> u8 { unsafe { *xs.get_unchecked(i) } } fn safe_get(xs: &[u8], i: usize, total: usize) -> u8 { if i >= total { 0 } else { unsafe_get(xs, i) } } let mut res = String::with_capacity(total); if i > 0 { unsafe { res.as_mut_vec().push_all(&v[..i]) }; } // subseqidx is the index of the first byte of the subsequence we're looking at. // It's used to copy a bunch of contiguous good codepoints at once instead of copying // them one by one. let mut subseqidx = i; while i < total { let i_ = i; let byte = unsafe_get(v, i); i += 1; macro_rules! error { () => ({ unsafe { if subseqidx != i_ { res.as_mut_vec().push_all(&v[subseqidx..i_]); } subseqidx = i; res.as_mut_vec().push_all(REPLACEMENT); } })} if byte < 128 { // subseqidx handles this } else { let w = unicode_str::utf8_char_width(byte); match w { 2 => { if safe_get(v, i, total) & 192 != TAG_CONT_U8 { error!(); continue; } i += 1; } 3 => { match (byte, safe_get(v, i, total)) { (0xE0 , 0xA0 ... 0xBF) => (), (0xE1 ... 0xEC, 0x80 ... 0xBF) => (), (0xED , 0x80 ... 0x9F) => (), (0xEE ... 0xEF, 0x80 ... 0xBF) => (), _ => { error!(); continue; } } i += 1; if safe_get(v, i, total) & 192 != TAG_CONT_U8 { error!(); continue; } i += 1; } 4 => { match (byte, safe_get(v, i, total)) { (0xF0 , 0x90 ... 0xBF) => (), (0xF1 ... 0xF3, 0x80 ... 0xBF) => (), (0xF4 , 0x80 ... 0x8F) => (), _ => { error!(); continue; } } i += 1; if safe_get(v, i, total) & 192 != TAG_CONT_U8 { error!(); continue; } i += 1; if safe_get(v, i, total) & 192 != TAG_CONT_U8 { error!(); continue; } i += 1; } _ => { error!(); continue; } } } } if subseqidx < total { unsafe { res.as_mut_vec().push_all(&v[subseqidx..total]) }; } Cow::Owned(res) } /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None` /// if `v` contains any invalid data. /// /// # Examples /// /// ```rust /// // 𝄞music /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075, /// 0x0073, 0x0069, 0x0063]; /// assert_eq!(String::from_utf16(v).unwrap(), /// "𝄞music".to_string()); /// /// // 𝄞mu<invalid>ic /// v[4] = 0xD800; /// assert!(String::from_utf16(v).is_err()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> { let mut s = String::with_capacity(v.len()); for c in unicode_str::utf16_items(v) { match c { Utf16Item::ScalarValue(c) => s.push(c), Utf16Item::LoneSurrogate(_) => return Err(FromUtf16Error(())), } } Ok(s) } /// Decode a UTF-16 encoded vector `v` into a string, replacing /// invalid data with the replacement character (U+FFFD). /// /// # Examples /// /// ```rust /// // 𝄞mus<invalid>ic<invalid> /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, /// 0x0073, 0xDD1E, 0x0069, 0x0063, /// 0xD834]; /// /// assert_eq!(String::from_utf16_lossy(v), /// "𝄞mus\u{FFFD}ic\u{FFFD}".to_string()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn from_utf16_lossy(v: &[u16]) -> String { unicode_str::utf16_items(v).map(|c| c.to_char_lossy()).collect() } /// Creates a new `String` from a length, capacity, and pointer. /// /// This is unsafe because: /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`; /// * We assume that the `Vec` contains valid UTF-8. #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String { String { vec: Vec::from_raw_parts(buf, length, capacity), } } /// Converts a vector of bytes to a new `String` without checking if /// it contains valid UTF-8. This is unsafe because it assumes that /// the UTF-8-ness of the vector has already been validated. #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String { String { vec: bytes } } /// Return the underlying byte buffer, encoded as UTF-8. /// /// # Examples /// /// ``` /// let s = String::from_str("hello"); /// let bytes = s.into_bytes(); /// assert_eq!(bytes, [104, 101, 108, 108, 111]); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn into_bytes(self) -> Vec<u8> { self.vec } /// Pushes the given string onto this string buffer. /// /// # Examples /// /// ``` /// let mut s = String::from_str("foo"); /// s.push_str("bar"); /// assert_eq!(s.as_slice(), "foobar"); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn push_str(&mut self, string: &str) { self.vec.push_all(string.as_bytes()) } /// Returns the number of bytes that this string buffer can hold without /// reallocating. /// /// # Examples /// /// ``` /// let s = String::with_capacity(10); /// assert!(s.capacity() >= 10); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn capacity(&self) -> usize { self.vec.capacity() } /// Reserves capacity for at least `additional` more bytes to be inserted /// in the given `String`. The collection may reserve more space to avoid /// frequent reallocations. /// /// # Panics /// /// Panics if the new capacity overflows `usize`. /// /// # Examples /// /// ``` /// let mut s = String::new(); /// s.reserve(10); /// assert!(s.capacity() >= 10); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn reserve(&mut self, additional: usize) { self.vec.reserve(additional) } /// Reserves the minimum capacity for exactly `additional` more bytes to be /// inserted in the given `String`. Does nothing if the capacity is already /// sufficient. /// /// Note that the allocator may give the collection more space than it /// requests. Therefore capacity can not be relied upon to be precisely /// minimal. Prefer `reserve` if future insertions are expected. /// /// # Panics /// /// Panics if the new capacity overflows `usize`. /// /// # Examples /// /// ``` /// let mut s = String::new(); /// s.reserve(10); /// assert!(s.capacity() >= 10); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn reserve_exact(&mut self, additional: usize) { self.vec.reserve_exact(additional) } /// Shrinks the capacity of this string buffer to match its length. /// /// # Examples /// /// ``` /// let mut s = String::from_str("foo"); /// s.reserve(100); /// assert!(s.capacity() >= 100); /// s.shrink_to_fit(); /// assert_eq!(s.capacity(), 3); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn shrink_to_fit(&mut self) { self.vec.shrink_to_fit() } /// Adds the given character to the end of the string. /// /// # Examples /// /// ``` /// let mut s = String::from_str("abc"); /// s.push('1'); /// s.push('2'); /// s.push('3'); /// assert_eq!(s.as_slice(), "abc123"); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn push(&mut self, ch: char) { if (ch as u32) < 0x80 { self.vec.push(ch as u8); return; } let cur_len = self.len(); // This may use up to 4 bytes. self.vec.reserve(4); unsafe { // Attempt to not use an intermediate buffer by just pushing bytes // directly onto this string. let slice = RawSlice { data: self.vec.as_ptr().offset(cur_len as isize), len: 4, }; let used = ch.encode_utf8(mem::transmute(slice)).unwrap_or(0); self.vec.set_len(cur_len + used); } } /// Works with the underlying buffer as a byte slice. /// /// # Examples /// /// ``` /// let s = String::from_str("hello"); /// let b: &[_] = &[104, 101, 108, 108, 111]; /// assert_eq!(s.as_bytes(), b); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn as_bytes(&self) -> &[u8] { &self.vec } /// Shortens a string to the specified length. /// /// # Panics /// /// Panics if `new_len` > current length, /// or if `new_len` is not a character boundary. /// /// # Examples /// /// ``` /// let mut s = String::from_str("hello"); /// s.truncate(2); /// assert_eq!(s.as_slice(), "he"); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn truncate(&mut self, new_len: usize) { assert!(self.is_char_boundary(new_len)); self.vec.truncate(new_len) } /// Removes the last character from the string buffer and returns it. /// Returns `None` if this string buffer is empty. /// /// # Examples /// /// ``` /// let mut s = String::from_str("foo"); /// assert_eq!(s.pop(), Some('o')); /// assert_eq!(s.pop(), Some('o')); /// assert_eq!(s.pop(), Some('f')); /// assert_eq!(s.pop(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn pop(&mut self) -> Option<char> { let len = self.len(); if len == 0 { return None } let CharRange {ch, next} = self.char_range_at_reverse(len); unsafe { self.vec.set_len(next); } Some(ch) } /// Removes the character from the string buffer at byte position `idx` and /// returns it. /// /// # Warning /// /// This is an O(n) operation as it requires copying every element in the /// buffer. /// /// # Panics /// /// If `idx` does not lie on a character boundary, or if it is out of /// bounds, then this function will panic. /// /// # Examples /// /// ``` /// let mut s = String::from_str("foo"); /// assert_eq!(s.remove(0), 'f'); /// assert_eq!(s.remove(1), 'o'); /// assert_eq!(s.remove(0), 'o'); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn remove(&mut self, idx: usize) -> char { let len = self.len(); assert!(idx <= len); let CharRange { ch, next } = self.char_range_at(idx); unsafe { ptr::copy(self.vec.as_mut_ptr().offset(idx as isize), self.vec.as_ptr().offset(next as isize), len - next); self.vec.set_len(len - (next - idx)); } ch } /// Insert a character into the string buffer at byte position `idx`. /// /// # Warning /// /// This is an O(n) operation as it requires copying every element in the /// buffer. /// /// # Panics /// /// If `idx` does not lie on a character boundary or is out of bounds, then /// this function will panic. #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn insert(&mut self, idx: usize, ch: char) { let len = self.len(); assert!(idx <= len); assert!(self.is_char_boundary(idx)); self.vec.reserve(4); let mut bits = [0; 4]; let amt = ch.encode_utf8(&mut bits).unwrap(); unsafe { ptr::copy(self.vec.as_mut_ptr().offset((idx + amt) as isize), self.vec.as_ptr().offset(idx as isize), len - idx); ptr::copy(self.vec.as_mut_ptr().offset(idx as isize), bits.as_ptr(), amt); self.vec.set_len(len + amt); } } /// Views the string buffer as a mutable sequence of bytes. /// /// This is unsafe because it does not check /// to ensure that the resulting string will be valid UTF-8. /// /// # Examples /// /// ``` /// let mut s = String::from_str("hello"); /// unsafe { /// let vec = s.as_mut_vec(); /// assert!(vec == &[104, 101, 108, 108, 111]); /// vec.reverse(); /// } /// assert_eq!(s.as_slice(), "olleh"); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> { &mut self.vec } /// Return the number of bytes in this string. /// /// # Examples /// /// ``` /// let a = "foo".to_string(); /// assert_eq!(a.len(), 3); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn len(&self) -> usize { self.vec.len() } /// Returns true if the string contains no bytes /// /// # Examples /// /// ``` /// let mut v = String::new(); /// assert!(v.is_empty()); /// v.push('a'); /// assert!(!v.is_empty()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Truncates the string, returning it to 0 length. /// /// # Examples /// /// ``` /// let mut s = "foo".to_string(); /// s.clear(); /// assert!(s.is_empty()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn clear(&mut self) { self.vec.clear() } } impl FromUtf8Error { /// Consume this error, returning the bytes that were attempted to make a /// `String` with. #[stable(feature = "rust1", since = "1.0.0")] pub fn into_bytes(self) -> Vec<u8> { self.bytes } /// Access the underlying UTF8-error that was the cause of this error. #[stable(feature = "rust1", since = "1.0.0")] pub fn utf8_error(&self) -> Utf8Error { self.error } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for FromUtf8Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.error, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl Error for FromUtf8Error { fn description(&self) -> &str { "invalid utf-8" } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for FromUtf16Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt("invalid utf-16: lone surrogate found", f) } } #[stable(feature = "rust1", since = "1.0.0")] impl Error for FromUtf16Error { fn description(&self) -> &str { "invalid utf-16" } } #[stable(feature = "rust1", since = "1.0.0")] impl FromIterator<char> for String { fn from_iter<I: IntoIterator<Item=char>>(iter: I) -> String { let mut buf = String::new(); buf.extend(iter); buf } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a> FromIterator<&'a str> for String { fn from_iter<I: IntoIterator<Item=&'a str>>(iter: I) -> String { let mut buf = String::new(); buf.extend(iter); buf } } #[unstable(feature = "collections", reason = "waiting on Extend stabilization")] impl Extend<char> for String { fn extend<I: IntoIterator<Item=char>>(&mut self, iterable: I) { let iterator = iterable.into_iter(); let (lower_bound, _) = iterator.size_hint(); self.reserve(lower_bound); for ch in iterator { self.push(ch) } } } #[unstable(feature = "collections", reason = "waiting on Extend stabilization")] impl<'a> Extend<&'a str> for String { fn extend<I: IntoIterator<Item=&'a str>>(&mut self, iterable: I) { let iterator = iterable.into_iter(); // A guess that at least one byte per iterator element will be needed. let (lower_bound, _) = iterator.size_hint(); self.reserve(lower_bound); for s in iterator { self.push_str(s) } } } #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for String { #[inline] fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &String) -> bool { PartialEq::ne(&**self, &**other) } } macro_rules! impl_eq { ($lhs:ty, $rhs: ty) => { #[stable(feature = "rust1", since = "1.0.0")] impl<'a> PartialEq<$rhs> for $lhs { #[inline] fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a> PartialEq<$lhs> for $rhs { #[inline] fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) } } } } impl_eq! { String, &'a str } impl_eq! { Cow<'a, str>, String } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, 'b> PartialEq<&'b str> for Cow<'a, str> { #[inline] fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&**self, &**other) } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, 'b> PartialEq<Cow<'a, str>> for &'b str { #[inline] fn eq(&self, other: &Cow<'a, str>) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &Cow<'a, str>) -> bool { PartialEq::ne(&**self, &**other) } } #[unstable(feature = "collections", reason = "waiting on Str stabilization")] impl Str for String { #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn as_slice(&self) -> &str { unsafe { mem::transmute(&*self.vec) } } } #[stable(feature = "rust1", since = "1.0.0")] impl Default for String { #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn default() -> String { String::new() } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Display for String { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for String { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] impl hash::Hash for String { #[inline] fn hash<H: hash::Hasher>(&self, hasher: &mut H) { (**self).hash(hasher) } } #[unstable(feature = "collections", reason = "recent addition, needs more experience")] impl<'a> Add<&'a str> for String { type Output = String; #[inline] fn add(mut self, other: &str) -> String { self.push_str(other); self } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index<ops::Range<usize>> for String { type Output = str; #[inline] fn index(&self, index: &ops::Range<usize>) -> &str { &self[..][*index] } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index<ops::RangeTo<usize>> for String { type Output = str; #[inline] fn index(&self, index: &ops::RangeTo<usize>) -> &str { &self[..][*index] } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index<ops::RangeFrom<usize>> for String { type Output = str; #[inline] fn index(&self, index: &ops::RangeFrom<usize>) -> &str { &self[..][*index] } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index<ops::RangeFull> for String { type Output = str; #[inline] fn index(&self, _index: &ops::RangeFull) -> &str { unsafe { mem::transmute(&*self.vec) } } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Deref for String { type Target = str; #[inline] fn deref(&self) -> &str { unsafe { mem::transmute(&self.vec[..]) } } } /// Wrapper type providing a `&String` reference via `Deref`. #[unstable(feature = "collections")] pub struct DerefString<'a> { x: DerefVec<'a, u8> } impl<'a> Deref for DerefString<'a> { type Target = String; #[inline] fn deref<'b>(&'b self) -> &'b String { unsafe { mem::transmute(&*self.x) } } } /// Convert a string slice to a wrapper type providing a `&String` reference. /// /// # Examples /// /// ``` /// use std::string::as_string; /// /// fn string_consumer(s: String) { /// assert_eq!(s, "foo".to_string()); /// } /// /// let string = as_string("foo").clone(); /// string_consumer(string); /// ``` #[unstable(feature = "collections")] pub fn as_string<'a>(x: &'a str) -> DerefString<'a> { DerefString { x: as_vec(x.as_bytes()) } } #[unstable(feature = "collections", reason = "associated error type may change")] impl FromStr for String { type Err = (); #[inline] fn from_str(s: &str) -> Result<String, ()> { Ok(String::from_str(s)) } } /// A generic trait for converting a value to a string #[stable(feature = "rust1", since = "1.0.0")] pub trait ToString { /// Converts the value of `self` to an owned string #[stable(feature = "rust1", since = "1.0.0")] fn to_string(&self) -> String; } #[stable(feature = "rust1", since = "1.0.0")] impl<T: fmt::Display + ?Sized> ToString for T { #[inline] fn to_string(&self) -> String { use core::fmt::Write; let mut buf = String::new(); let _ = buf.write_fmt(format_args!("{}", self)); buf.shrink_to_fit(); buf } } #[stable(feature = "rust1", since = "1.0.0")] impl IntoCow<'static, str> for String { #[inline] fn into_cow(self) -> Cow<'static, str> { Cow::Owned(self) } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a> IntoCow<'a, str> for &'a str { #[inline] fn into_cow(self) -> Cow<'a, str> { Cow::Borrowed(self) } } impl<'a> Str for Cow<'a, str> { #[inline] fn as_slice<'b>(&'b self) -> &'b str { &**self } } /// A clone-on-write string #[deprecated(since = "1.0.0", reason = "use Cow<'a, str> instead")] #[stable(feature = "rust1", since = "1.0.0")] pub type CowString<'a> = Cow<'a, str>; #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Write for String { #[inline] fn write_str(&mut self, s: &str) -> fmt::Result { self.push_str(s); Ok(()) } } #[cfg(test)] mod tests { use prelude::*; use test::Bencher; use str::Utf8Error; use core::iter::repeat; use super::{as_string, CowString}; #[test] fn test_as_string() { let x = "foo"; assert_eq!(x, &**as_string(x)); } #[test] fn test_from_str() { let owned: Option<::std::string::String> = "string".parse().ok(); assert_eq!(owned.as_ref().map(|s| &**s), Some("string")); } #[test] fn test_unsized_to_string() { let s: &str = "abc"; let _: String = (*s).to_string(); } #[test] fn test_from_utf8() { let xs = b"hello".to_vec(); assert_eq!(String::from_utf8(xs).unwrap(), String::from_str("hello")); let xs = "ศไทย中华Việt Nam".as_bytes().to_vec(); assert_eq!(String::from_utf8(xs).unwrap(), String::from_str("ศไทย中华Việt Nam")); let xs = b"hello\xFF".to_vec(); let err = String::from_utf8(xs).err().unwrap(); assert_eq!(err.utf8_error(), Utf8Error::TooShort); assert_eq!(err.into_bytes(), b"hello\xff".to_vec()); } #[test] fn test_from_utf8_lossy() { let xs = b"hello"; let ys: CowString = "hello".into_cow(); assert_eq!(String::from_utf8_lossy(xs), ys); let xs = "ศไทย中华Việt Nam".as_bytes(); let ys: CowString = "ศไทย中华Việt Nam".into_cow(); assert_eq!(String::from_utf8_lossy(xs), ys); let xs = b"Hello\xC2 There\xFF Goodbye"; assert_eq!(String::from_utf8_lossy(xs), String::from_str("Hello\u{FFFD} There\u{FFFD} Goodbye").into_cow()); let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye"; assert_eq!(String::from_utf8_lossy(xs), String::from_str("Hello\u{FFFD}\u{FFFD} There\u{FFFD} Goodbye").into_cow()); let xs = b"\xF5foo\xF5\x80bar"; assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}foo\u{FFFD}\u{FFFD}bar").into_cow()); let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz"; assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}foo\u{FFFD}bar\u{FFFD}baz").into_cow()); let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz"; assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}foo\u{FFFD}bar\u{FFFD}\u{FFFD}baz").into_cow()); let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar"; assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\ foo\u{10000}bar").into_cow()); // surrogates let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar"; assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}\u{FFFD}\u{FFFD}foo\ \u{FFFD}\u{FFFD}\u{FFFD}bar").into_cow()); } #[test] fn test_from_utf16() { let pairs = [(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"), vec![0xd800, 0xdf45, 0xd800, 0xdf3f, 0xd800, 0xdf3b, 0xd800, 0xdf46, 0xd800, 0xdf39, 0xd800, 0xdf3b, 0xd800, 0xdf30, 0x000a]), (String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"), vec![0xd801, 0xdc12, 0xd801, 0xdc49, 0xd801, 0xdc2e, 0xd801, 0xdc40, 0xd801, 0xdc32, 0xd801, 0xdc4b, 0x0020, 0xd801, 0xdc0f, 0xd801, 0xdc32, 0xd801, 0xdc4d, 0x000a]), (String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"), vec![0xd800, 0xdf00, 0xd800, 0xdf16, 0xd800, 0xdf0b, 0xd800, 0xdf04, 0xd800, 0xdf11, 0xd800, 0xdf09, 0x00b7, 0xd800, 0xdf0c, 0xd800, 0xdf04, 0xd800, 0xdf15, 0xd800, 0xdf04, 0xd800, 0xdf0b, 0xd800, 0xdf09, 0xd800, 0xdf11, 0x000a ]), (String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"), vec![0xd801, 0xdc8b, 0xd801, 0xdc98, 0xd801, 0xdc88, 0xd801, 0xdc91, 0xd801, 0xdc9b, 0xd801, 0xdc92, 0x0020, 0xd801, 0xdc95, 0xd801, 0xdc93, 0x0020, 0xd801, 0xdc88, 0xd801, 0xdc9a, 0xd801, 0xdc8d, 0x0020, 0xd801, 0xdc8f, 0xd801, 0xdc9c, 0xd801, 0xdc92, 0xd801, 0xdc96, 0xd801, 0xdc86, 0x0020, 0xd801, 0xdc95, 0xd801, 0xdc86, 0x000a ]), // Issue #12318, even-numbered non-BMP planes (String::from_str("\u{20000}"), vec![0xD840, 0xDC00])]; for p in &pairs { let (s, u) = (*p).clone(); let s_as_utf16 = s.utf16_units().collect::<Vec<u16>>(); let u_as_string = String::from_utf16(&u).unwrap(); assert!(::unicode::str::is_utf16(&u)); assert_eq!(s_as_utf16, u); assert_eq!(u_as_string, s); assert_eq!(String::from_utf16_lossy(&u), s); assert_eq!(String::from_utf16(&s_as_utf16).unwrap(), s); assert_eq!(u_as_string.utf16_units().collect::<Vec<u16>>(), u); } } #[test] fn test_utf16_invalid() { // completely positive cases tested above. // lead + eof assert!(String::from_utf16(&[0xD800]).is_err()); // lead + lead assert!(String::from_utf16(&[0xD800, 0xD800]).is_err()); // isolated trail assert!(String::from_utf16(&[0x0061, 0xDC00]).is_err()); // general assert!(String::from_utf16(&[0xD800, 0xd801, 0xdc8b, 0xD800]).is_err()); } #[test] fn test_from_utf16_lossy() { // completely positive cases tested above. // lead + eof assert_eq!(String::from_utf16_lossy(&[0xD800]), String::from_str("\u{FFFD}")); // lead + lead assert_eq!(String::from_utf16_lossy(&[0xD800, 0xD800]), String::from_str("\u{FFFD}\u{FFFD}")); // isolated trail assert_eq!(String::from_utf16_lossy(&[0x0061, 0xDC00]), String::from_str("a\u{FFFD}")); // general assert_eq!(String::from_utf16_lossy(&[0xD800, 0xd801, 0xdc8b, 0xD800]), String::from_str("\u{FFFD}𐒋\u{FFFD}")); } #[test] fn test_push_bytes() { let mut s = String::from_str("ABC"); unsafe { let mv = s.as_mut_vec(); mv.push_all(&[b'D']); } assert_eq!(s, "ABCD"); } #[test] fn test_push_str() { let mut s = String::new(); s.push_str(""); assert_eq!(&s[0..], ""); s.push_str("abc"); assert_eq!(&s[0..], "abc"); s.push_str("ประเทศไทย中华Việt Nam"); assert_eq!(&s[0..], "abcประเทศไทย中华Việt Nam"); } #[test] fn test_push() { let mut data = String::from_str("ประเทศไทย中"); data.push('华'); data.push('b'); // 1 byte data.push('¢'); // 2 byte data.push('€'); // 3 byte data.push('𤭢'); // 4 byte assert_eq!(data, "ประเทศไทย中华b¢€𤭢"); } #[test] fn test_pop() { let mut data = String::from_str("ประเทศไทย中华b¢€𤭢"); assert_eq!(data.pop().unwrap(), '𤭢'); // 4 bytes assert_eq!(data.pop().unwrap(), '€'); // 3 bytes assert_eq!(data.pop().unwrap(), '¢'); // 2 bytes assert_eq!(data.pop().unwrap(), 'b'); // 1 bytes assert_eq!(data.pop().unwrap(), '华'); assert_eq!(data, "ประเทศไทย中"); } #[test] fn test_str_truncate() { let mut s = String::from_str("12345"); s.truncate(5); assert_eq!(s, "12345"); s.truncate(3); assert_eq!(s, "123"); s.truncate(0); assert_eq!(s, ""); let mut s = String::from_str("12345"); let p = s.as_ptr(); s.truncate(3); s.push_str("6"); let p_ = s.as_ptr(); assert_eq!(p_, p); } #[test] #[should_fail] fn test_str_truncate_invalid_len() { let mut s = String::from_str("12345"); s.truncate(6); } #[test] #[should_fail] fn test_str_truncate_split_codepoint() { let mut s = String::from_str("\u{FC}"); // ü s.truncate(1); } #[test] fn test_str_clear() { let mut s = String::from_str("12345"); s.clear(); assert_eq!(s.len(), 0); assert_eq!(s, ""); } #[test] fn test_str_add() { let a = String::from_str("12345"); let b = a + "2"; let b = b + "2"; assert_eq!(b.len(), 7); assert_eq!(b, "1234522"); } #[test] fn remove() { let mut s = "ศไทย中华Việt Nam; foobar".to_string();; assert_eq!(s.remove(0), 'ศ'); assert_eq!(s.len(), 33); assert_eq!(s, "ไทย中华Việt Nam; foobar"); assert_eq!(s.remove(17), 'ệ'); assert_eq!(s, "ไทย中华Vit Nam; foobar"); } #[test] #[should_fail] fn remove_bad() { "ศ".to_string().remove(1); } #[test] fn insert() { let mut s = "foobar".to_string(); s.insert(0, 'ệ'); assert_eq!(s, "ệfoobar"); s.insert(6, 'ย'); assert_eq!(s, "ệfooยbar"); } #[test] #[should_fail] fn insert_bad1() { "".to_string().insert(1, 't'); } #[test] #[should_fail] fn insert_bad2() { "ệ".to_string().insert(1, 't'); } #[test] fn test_slicing() { let s = "foobar".to_string(); assert_eq!("foobar", &s[..]); assert_eq!("foo", &s[..3]); assert_eq!("bar", &s[3..]); assert_eq!("oob", &s[1..4]); } #[test] fn test_simple_types() { assert_eq!(1.to_string(), "1"); assert_eq!((-1).to_string(), "-1"); assert_eq!(200.to_string(), "200"); assert_eq!(2.to_string(), "2"); assert_eq!(true.to_string(), "true"); assert_eq!(false.to_string(), "false"); assert_eq!(("hi".to_string()).to_string(), "hi"); } #[test] fn test_vectors() { let x: Vec<i32> = vec![]; assert_eq!(format!("{:?}", x), "[]"); assert_eq!(format!("{:?}", vec![1]), "[1]"); assert_eq!(format!("{:?}", vec![1, 2, 3]), "[1, 2, 3]"); assert!(format!("{:?}", vec![vec![], vec![1], vec![1, 1]]) == "[[], [1], [1, 1]]"); } #[test] fn test_from_iterator() { let s = "ศไทย中华Việt Nam".to_string(); let t = "ศไทย中华"; let u = "Việt Nam"; let a: String = s.chars().collect(); assert_eq!(s, a); let mut b = t.to_string(); b.extend(u.chars()); assert_eq!(s, b); let c: String = vec![t, u].into_iter().collect(); assert_eq!(s, c); let mut d = t.to_string(); d.extend(vec![u].into_iter()); assert_eq!(s, d); } #[bench] fn bench_with_capacity(b: &mut Bencher) { b.iter(|| { String::with_capacity(100) }); } #[bench] fn bench_push_str(b: &mut Bencher) { let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb"; b.iter(|| { let mut r = String::new(); r.push_str(s); }); } const REPETITIONS: u64 = 10_000; #[bench] fn bench_push_str_one_byte(b: &mut Bencher) { b.bytes = REPETITIONS; b.iter(|| { let mut r = String::new(); for _ in 0..REPETITIONS { r.push_str("a") } }); } #[bench] fn bench_push_char_one_byte(b: &mut Bencher) { b.bytes = REPETITIONS; b.iter(|| { let mut r = String::new(); for _ in 0..REPETITIONS { r.push('a') } }); } #[bench] fn bench_push_char_two_bytes(b: &mut Bencher) { b.bytes = REPETITIONS * 2; b.iter(|| { let mut r = String::new(); for _ in 0..REPETITIONS { r.push('â') } }); } #[bench] fn from_utf8_lossy_100_ascii(b: &mut Bencher) { let s = b"Hello there, the quick brown fox jumped over the lazy dog! \ Lorem ipsum dolor sit amet, consectetur. "; assert_eq!(100, s.len()); b.iter(|| { let _ = String::from_utf8_lossy(s); }); } #[bench] fn from_utf8_lossy_100_multibyte(b: &mut Bencher) { let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes(); assert_eq!(100, s.len()); b.iter(|| { let _ = String::from_utf8_lossy(s); }); } #[bench] fn from_utf8_lossy_invalid(b: &mut Bencher) { let s = b"Hello\xC0\x80 There\xE6\x83 Goodbye"; b.iter(|| { let _ = String::from_utf8_lossy(s); }); } #[bench] fn from_utf8_lossy_100_invalid(b: &mut Bencher) { let s = repeat(0xf5).take(100).collect::<Vec<_>>(); b.iter(|| { let _ = String::from_utf8_lossy(&s); }); } #[bench] fn bench_exact_size_shrink_to_fit(b: &mut Bencher) { let s = "Hello there, the quick brown fox jumped over the lazy dog! \ Lorem ipsum dolor sit amet, consectetur. "; // ensure our operation produces an exact-size string before we benchmark it let mut r = String::with_capacity(s.len()); r.push_str(s); assert_eq!(r.len(), r.capacity()); b.iter(|| { let mut r = String::with_capacity(s.len()); r.push_str(s); r.shrink_to_fit(); r }); } }
29.616183
99
0.503678
0985ddc2fbe2e60d519047af1a7cc8c6089a82b1
3,495
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. // Insert std prelude in the top for the sgx feature #[cfg(feature = "mesalock_sgx")] use std::prelude::v1::*; use mesatee_core::{Error, ErrorKind, Result}; use ring::aead::{self, Aad, BoundKey, Nonce, UnboundKey}; use ring::digest; use std::fmt::Write; struct OneNonceSequence(Option<aead::Nonce>); impl OneNonceSequence { /// Constructs the sequence allowing `advance()` to be called /// `allowed_invocations` times. fn new(nonce: aead::Nonce) -> Self { Self(Some(nonce)) } } impl aead::NonceSequence for OneNonceSequence { fn advance(&mut self) -> core::result::Result<aead::Nonce, ring::error::Unspecified> { self.0.take().ok_or(ring::error::Unspecified) } } pub fn decrypt_data( mut data: Vec<u8>, aes_key: &[u8], aes_nonce: &[u8], aes_ad: &[u8], ) -> Result<Vec<u8>> { let aead_alg = &aead::AES_256_GCM; let ub = UnboundKey::new(aead_alg, aes_key).map_err(|_| Error::from(ErrorKind::CryptoError))?; let nonce = Nonce::try_assume_unique_for_key(aes_nonce) .map_err(|_| Error::from(ErrorKind::CryptoError))?; let filesequence = OneNonceSequence::new(nonce); let mut o_key = aead::OpeningKey::new(ub, filesequence); let ad = Aad::from(aes_ad); let result = o_key.open_in_place(ad, &mut data[..]); let decrypted_buffer = result.map_err(|_| Error::from(ErrorKind::CryptoError))?; Ok(decrypted_buffer.to_vec()) } pub fn encrypt_data( mut data: Vec<u8>, aes_key: &[u8], aes_nonce: &[u8], aes_ad: &[u8], ) -> Result<Vec<u8>> { let aead_alg = &aead::AES_256_GCM; if (aes_key.len() != 32) || (aes_nonce.len() != 12) || (aes_ad.len() != 5) { return Err(Error::from(ErrorKind::CryptoError)); } let ub = UnboundKey::new(aead_alg, aes_key).map_err(|_| Error::from(ErrorKind::CryptoError))?; let nonce = Nonce::try_assume_unique_for_key(aes_nonce) .map_err(|_| Error::from(ErrorKind::CryptoError))?; let filesequence = OneNonceSequence::new(nonce); let mut s_key = aead::SealingKey::new(ub, filesequence); let ad = Aad::from(aes_ad); let s_result = s_key.seal_in_place_append_tag(ad, &mut data); s_result.map_err(|_| Error::from(ErrorKind::CryptoError))?; Ok(data) } pub fn cal_hash(data: &[u8]) -> Result<String> { let digest_alg = &digest::SHA256; let mut ctx = digest::Context::new(digest_alg); ctx.update(data); let digest_result = ctx.finish(); let digest_bytes: &[u8] = digest_result.as_ref(); let mut digest_hex = String::new(); for &byte in digest_bytes { write!(&mut digest_hex, "{:02x}", byte).map_err(|_| Error::from(ErrorKind::Unknown))?; } Ok(digest_hex) }
35.30303
98
0.674678
e66b63bfe2b4c0b342c08a6664caa0d5abd58251
476
// clippy1.rs // The Clippy tool is a collection of lints to analyze your code // so you can catch common mistakes and improve your Rust code. // // For these exercises the code will fail to compile when there are clippy warnings // check clippy's suggestions from the output to solve the exercise. // Execute `rustlings hint clippy1` for hints :) fn main() { let x = 1.2331f64; let y = 1.2332f64; if (y - x).abs() > 0.001 { println!("Success!"); } }
29.75
83
0.670168
fe9750e45bb0841d281576ddc4333a470e2e5f2f
5,149
// Copyright 2020 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT // http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD // https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied, // modified, or distributed except according to those terms. Please review the Licences for the // specific language governing permissions and limitations relating to use of the SAFE Network // Software. use crdts::quickcheck::{Arbitrary, Gen}; use serde::{Deserialize, Serialize}; use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use crdts::Actor; use std::hash::{Hash, Hasher}; /// Implements a `Lamport Clock` consisting of an `Actor` and an integer counter. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Clock<A: Actor> { actor_id: A, counter: u64, } impl<A: Actor> Clock<A> { /// create new Clock instance /// /// typically counter should be None pub fn new(actor_id: A, counter: Option<u64>) -> Self { Self { actor_id, counter: counter.unwrap_or(0), } } /// returns a new Clock with same actor but counter incremented by 1. pub fn inc(&self) -> Self { Self::new(self.actor_id.clone(), Some(self.counter.saturating_add(1))) } /// increments clock counter and returns a clone pub fn tick(&mut self) -> Self { self.counter = self.counter.saturating_add(1); self.clone() } /// returns actor_id reference #[inline] pub fn actor_id(&self) -> &A { &self.actor_id } /// returns counter #[inline] pub fn counter(&self) -> u64 { self.counter } /// returns a new Clock with same actor but counter is /// max(this_counter, other_counter) pub fn merge(&self, other: &Self) -> Self { Self::new( self.actor_id.clone(), Some(std::cmp::max(self.counter, other.counter)), ) } } impl<A: Actor> Ord for Clock<A> { /// compares this Clock with another. /// if counters are unequal, returns -1 or 1 accordingly. /// if counters are equal, returns -1, 0, or 1 based on actor_id. /// (this is arbitrary, but deterministic.) fn cmp(&self, other: &Self) -> Ordering { match self.counter.cmp(&other.counter) { Ordering::Equal => self.actor_id.cmp(&other.actor_id), Ordering::Greater => Ordering::Greater, Ordering::Less => Ordering::Less, } } } impl<A: Actor> PartialOrd for Clock<A> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<A: Actor> PartialEq for Clock<A> { fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal } } impl<A: Actor> Eq for Clock<A> {} impl<A: Actor> Hash for Clock<A> { fn hash<H: Hasher>(&self, state: &mut H) { self.actor_id.hash(state); self.counter.hash(state); } } // Generate arbitrary (random) clocks. needed by quickcheck. impl<A: Actor + Arbitrary> Arbitrary for Clock<A> { fn arbitrary<G: Gen>(g: &mut G) -> Self { Self { actor_id: A::arbitrary(g), counter: u64::arbitrary(g), } } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { let mut shrunk_clocks = Vec::new(); if self.counter > 0 { shrunk_clocks.push(Self::new(self.actor_id.clone(), Some(self.counter - 1))); } Box::new(shrunk_clocks.into_iter()) } } #[cfg(test)] mod test { use super::*; use quickcheck::quickcheck; quickcheck! { fn inc_increments_only_the_counter(clock: Clock<u8>) -> bool { clock.inc() == Clock::new(clock.actor_id, Some(clock.counter + 1)) } fn test_total_order(a: Clock<u8>, b: Clock<u8>) -> bool { let cmp_ab = a.cmp(&b); let cmp_ba = b.cmp(&a); match (cmp_ab, cmp_ba) { (Ordering::Less, Ordering::Greater) => a.counter < b.counter || a.counter == b.counter && a.actor_id < b.actor_id, (Ordering::Greater, Ordering::Less) => a.counter > b.counter || a.counter == b.counter && a.actor_id > b.actor_id, (Ordering::Equal, Ordering::Equal) => a.actor_id == b.actor_id && a.counter == b.counter, _ => false, } } fn test_partial_order(a: Clock<u8>, b: Clock<u8>) -> bool { let cmp_ab = a.partial_cmp(&b); let cmp_ba = b.partial_cmp(&a); match (cmp_ab, cmp_ba) { (None, None) => a.actor_id != b.actor_id, (Some(Ordering::Less), Some(Ordering::Greater)) => a.counter < b.counter || a.counter == b.counter && a.actor_id < b.actor_id, (Some(Ordering::Greater), Some(Ordering::Less)) => a.counter > b.counter || a.counter == b.counter && a.actor_id > b.actor_id, (Some(Ordering::Equal), Some(Ordering::Equal)) => a.actor_id == b.actor_id && a.counter == b.counter, _ => false } } } }
32.796178
142
0.585551
f5d99e7772803fda738cf382811ef8b3cb4022f8
773
#![feature(proc_macro_non_items)] extern crate cedar; use cedar::hypertext; type Model = String; #[derive(PartialEq)] enum Message { NewContent(String), } fn update(_: Model, message: &Message) -> Model { match message { &Message::NewContent(ref content) => content.clone(), } } type Object = cedar::dom::Object<Message>; fn words(line: &str) -> Vec<Object> { line.split(' ') .filter(|s| !s.is_empty()) .map(|w| hypertext! { <div>{w}</div> }) .collect() } fn view(model: &Model) -> Object { hypertext! { <div> <input placeholder={"Words!"} input={Message::NewContent}></input> <div>{words(model)}</div> </div> } } fn main() { cedar::app("".into(), update, view) }
18.853659
78
0.564036
6215e51cb4faf3f6b4c5320596b790d1005d878a
9,789
use crate::crypto::ErrorReplication; use ic_types::crypto::canister_threshold_sig::error::{ IDkgVerifyComplaintError, IDkgVerifyDealingPrivateError, IDkgVerifyDealingPublicError, IDkgVerifyOpeningError, ThresholdEcdsaVerifySigShareError, }; use ic_types::crypto::threshold_sig::ni_dkg::errors::create_transcript_error::DkgCreateTranscriptError; use ic_types::crypto::threshold_sig::ni_dkg::errors::verify_dealing_error::DkgVerifyDealingError; use ic_types::crypto::CryptoError; use ic_types::registry::RegistryClientError; // An implementation for the consensus component. impl ErrorReplication for CryptoError { fn is_replicated(&self) -> bool { // The match below is intentionally explicit on all possible values, // to avoid defaults, which might be error-prone. // Upon addition of any new error this match has to be updated. match self { // true, as validity checks of arguments are stable across replicas CryptoError::InvalidArgument { .. } => true, // true, as the registry is guaranteed to be consistent across replicas CryptoError::PublicKeyNotFound { .. } | CryptoError::TlsCertNotFound { .. } => true, // panic, as during signature verification no secret keys are involved CryptoError::SecretKeyNotFound { .. } | CryptoError::TlsSecretKeyNotFound { .. } => { panic!("Unexpected error {}, no secret keys involved", &self) } // true tentatively, but may change to panic! in the future: // this error indicates either globally corrupted registry, or a local // data corruption, and in either case we should not use the key anymore CryptoError::MalformedPublicKey { .. } => true, // panic, as during signature verification no secret keys are involved CryptoError::MalformedSecretKey { .. } => { panic!("Unexpected error {}, no secret keys involved", &self) } // true, but this error may be removed TODO(CRP-224) CryptoError::MalformedSignature { .. } => true, // true, but this error may be removed TODO(CRP-224) CryptoError::MalformedPop { .. } => true, // true, as signature verification is stable across replicas CryptoError::SignatureVerification { .. } => true, // true, as PoP verification is stable across replicas CryptoError::PopVerification { .. } => true, // true, as it indicates inconsistent data in multi-sigs // (individual signatures of a multi sig belong to differing algorithms) CryptoError::InconsistentAlgorithms { .. } => true, // true, as the set of supported algorithms is stable (bound to code version) CryptoError::AlgorithmNotSupported { .. } => true, // false, as the result may change if the DKG transcript is reloaded. CryptoError::ThresholdSigDataNotFound { .. } => false, CryptoError::RegistryClient(registry_client_error) => { error_replication_of_registry_client_error(registry_client_error) } // true, as the registry is guaranteed to be consistent across replicas CryptoError::DkgTranscriptNotFound { .. } => true, // true, as the registry is guaranteed to be consistent across replicas CryptoError::RootSubnetPublicKeyNotFound { .. } => true, } } } impl ErrorReplication for DkgVerifyDealingError { fn is_replicated(&self) -> bool { // The match below is intentionally explicit on all possible values, // to avoid defaults, which might be error-prone. // Upon addition of any new error this match has to be updated. match self { DkgVerifyDealingError::NotADealer(_) => { // true, as the node cannot become a dealer through retrying true } DkgVerifyDealingError::FsEncryptionPublicKeyNotInRegistry(_) => { // true, as the registry is guaranteed to be consistent across replicas true } DkgVerifyDealingError::Registry(registry_client_error) => { error_replication_of_registry_client_error(registry_client_error) } DkgVerifyDealingError::MalformedFsEncryptionPublicKey(_) => { // true, as the encryption public key is fetched from the registry and the // registry is guaranteed to be consistent across replicas true } DkgVerifyDealingError::MalformedResharingTranscriptInConfig(_) => { // true, coefficients remain malformed when retrying true } DkgVerifyDealingError::InvalidDealingError(_) => { // true, the dealing does not become valid through retrying true } } } } impl ErrorReplication for DkgCreateTranscriptError { fn is_replicated(&self) -> bool { // The match below is intentionally explicit on all possible values, // to avoid defaults, which might be error-prone. // Upon addition of any new error this match has to be updated. match self { DkgCreateTranscriptError::InsufficientDealings(_) => { // true, the number of dealings remains insufficient when retrying true } DkgCreateTranscriptError::MalformedResharingTranscriptInConfig(_) => { // true, coefficients remain malformed when retrying true } } } } impl ErrorReplication for IDkgVerifyDealingPublicError { fn is_replicated(&self) -> bool { // TODO correctly implement this function false } } impl ErrorReplication for IDkgVerifyComplaintError { fn is_replicated(&self) -> bool { // The match below is intentionally explicit on all possible values, // to avoid defaults, which might be error-prone. // Upon addition of any new error this match has to be updated. match self { // true, as the complaint does not become valid through retrying IDkgVerifyComplaintError::InvalidComplaint => true, // true, as validity checks of arguments are stable across replicas IDkgVerifyComplaintError::InvalidArgument { .. } => true, // true, as validity checks of arguments are stable across replicas IDkgVerifyComplaintError::InvalidArgumentMismatchingTranscriptIDs => true, // true, as validity checks of arguments are stable across replicas IDkgVerifyComplaintError::InvalidArgumentMissingDealingInTranscript { .. } => true, // true, as validity checks of arguments are stable across replicas IDkgVerifyComplaintError::InvalidArgumentMissingComplainerInTranscript { .. } => true, // true, as the registry is guaranteed to be consistent across replicas IDkgVerifyComplaintError::ComplainerPublicKeyNotInRegistry { .. } => true, // true, as the public key is fetched from the registry and the // registry is guaranteed to be consistent across replicas IDkgVerifyComplaintError::MalformedComplainerPublicKey { .. } => true, // true, as the set of supported algorithms is stable (bound to code version) IDkgVerifyComplaintError::UnsupportedComplainerPublicKeyAlgorithm { .. } => true, // true, as (de)serialization is stable across replicas IDkgVerifyComplaintError::SerializationError { .. } => true, IDkgVerifyComplaintError::Registry(registry_client_error) => { error_replication_of_registry_client_error(registry_client_error) } // true, as the types of internal errors that may occur during complaint // verification are stable IDkgVerifyComplaintError::InternalError { .. } => true, } } } impl ErrorReplication for IDkgVerifyDealingPrivateError { fn is_replicated(&self) -> bool { // The match below is intentionally explicit on all possible values, // to avoid defaults, which might be error-prone. // Upon addition of any new error this match has to be updated. match self { IDkgVerifyDealingPrivateError::NotAReceiver => { // Logic error. Everyone thinks a non-receiver is a receiver. true } } } } impl ErrorReplication for ThresholdEcdsaVerifySigShareError { fn is_replicated(&self) -> bool { // TODO correctly implement this function false } } impl ErrorReplication for IDkgVerifyOpeningError { fn is_replicated(&self) -> bool { // TODO correctly implement this function false } } fn error_replication_of_registry_client_error(registry_client_error: &RegistryClientError) -> bool { match registry_client_error { // false, as depends on the data available to the registry RegistryClientError::VersionNotAvailable { .. } => false, // false in both cases, these may be transient errors RegistryClientError::DataProviderQueryFailed { source } => match source { ic_types::registry::RegistryDataProviderError::Timeout => false, ic_types::registry::RegistryDataProviderError::Transfer { .. } => false, }, // may be a transient error RegistryClientError::PollLockFailed { .. } => false, // may be transient errors RegistryClientError::PollingLatestVersionFailed { .. } => false, } }
49.690355
103
0.64409
76310d2825b548618c33857194efeb488dfd58ae
14,366
//! HAL interface to the SPIM peripheral //! //! See product specification, chapter 31. use core::ops::Deref; use core::sync::atomic::{compiler_fence, Ordering::SeqCst}; #[cfg(feature="9160")] use crate::target::{spim0_ns as spim0, SPIM0_NS as SPIM0 }; #[cfg(not(feature="9160"))] use crate::target::{spim0, SPIM0}; pub use spim0::frequency::FREQUENCY_A as Frequency; pub use embedded_hal::spi::{Mode, Phase, Polarity, MODE_0, MODE_1, MODE_2, MODE_3}; use core::iter::repeat_with; #[cfg(any(feature = "52832", feature = "52840"))] use crate::target::{SPIM1, SPIM2}; use crate::gpio::{Floating, Input, Output, Pin, PushPull}; use embedded_hal::digital::v2::OutputPin; use crate::target_constants::{EASY_DMA_SIZE, FORCE_COPY_BUFFER_SIZE}; use crate::{slice_in_ram, DmaSlice}; /// Interface to a SPIM instance /// /// This is a very basic interface that comes with the following limitations: /// - The SPIM instances share the same address space with instances of SPIS, /// SPI, TWIM, TWIS, and TWI. You need to make sure that conflicting instances /// are disabled before using `Spim`. See product specification, section 15.2. pub struct Spim<T>(T); impl<T> embedded_hal::blocking::spi::Transfer<u8> for Spim<T> where T: Instance, { type Error = Error; fn transfer<'w>(&mut self, words: &'w mut [u8]) -> Result<&'w [u8], Error> { // If the slice isn't in RAM, we can't write back to it at all ram_slice_check(words)?; words.chunks(EASY_DMA_SIZE).try_for_each(|chunk| { self.do_spi_dma_transfer( DmaSlice::from_slice(chunk), DmaSlice::from_slice(chunk), ) })?; Ok(words) } } impl<T> embedded_hal::blocking::spi::Write<u8> for Spim<T> where T: Instance, { type Error = Error; fn write<'w>(&mut self, words: &'w [u8]) -> Result<(), Error> { // Mask on segment where Data RAM is located on nrf52840 and nrf52832 // Upper limit is choosen to entire area where DataRam can be placed let needs_copy = !slice_in_ram(words); let chunk_sz = if needs_copy { FORCE_COPY_BUFFER_SIZE } else { EASY_DMA_SIZE }; let step = if needs_copy { Self::spi_dma_copy } else { Self::spi_dma_no_copy }; words.chunks(chunk_sz).try_for_each(|c| step(self, c)) } } impl<T> Spim<T> where T: Instance, { fn spi_dma_no_copy(&mut self, chunk: &[u8]) -> Result<(), Error> { self.do_spi_dma_transfer(DmaSlice::from_slice(chunk), DmaSlice::null()) } fn spi_dma_copy(&mut self, chunk: &[u8]) -> Result<(), Error> { let mut buf = [0u8; FORCE_COPY_BUFFER_SIZE]; buf[..chunk.len()].copy_from_slice(chunk); self.do_spi_dma_transfer( DmaSlice::from_slice(&buf[..chunk.len()]), DmaSlice::null(), ) } pub fn new(spim: T, pins: Pins, frequency: Frequency, mode: Mode, orc: u8) -> Self { // Select pins spim.psel.sck.write(|w| { let w = unsafe { w.pin().bits(pins.sck.pin) }; #[cfg(feature = "52840")] let w = w.port().bit(pins.sck.port); w.connect().connected() }); match pins.mosi { Some(mosi) => spim.psel.mosi.write(|w| { let w = unsafe { w.pin().bits(mosi.pin) }; #[cfg(feature = "52840")] let w = w.port().bit(mosi.port); w.connect().connected() }), None => spim.psel.mosi.write(|w| w.connect().disconnected()), } match pins.miso { Some(miso) => spim.psel.miso.write(|w| { let w = unsafe { w.pin().bits(miso.pin) }; #[cfg(feature = "52840")] let w = w.port().bit(miso.port); w.connect().connected() }), None => spim.psel.miso.write(|w| w.connect().disconnected()), } // Enable SPIM instance spim.enable.write(|w| w.enable().enabled()); // Configure mode spim.config.write(|w| { // Can't match on `mode` due to embedded-hal, see https://github.com/rust-embedded/embedded-hal/pull/126 if mode == MODE_0 { w.order().msb_first().cpol().active_high().cpha().leading() } else if mode == MODE_1 { w.order().msb_first().cpol().active_high().cpha().trailing() } else if mode == MODE_2 { w.order().msb_first().cpol().active_low().cpha().leading() } else { w.order().msb_first().cpol().active_low().cpha().trailing() } }); // Configure frequency spim.frequency.write(|w| w.frequency().variant(frequency)); // Set over-read character to `0` spim.orc.write(|w| // The ORC field is 8 bits long, so `0` is a valid value to write // there. unsafe { w.orc().bits(orc) }); Spim(spim) } /// Internal helper function to setup and execute SPIM DMA transfer fn do_spi_dma_transfer( &mut self, tx: DmaSlice, rx: DmaSlice, ) -> Result<(), Error> { // Conservative compiler fence to prevent optimizations that do not // take in to account actions by DMA. The fence has been placed here, // before any DMA action has started compiler_fence(SeqCst); // Set up the DMA write self.0 .txd .ptr .write(|w| unsafe { w.ptr().bits(tx.ptr) }); self.0.txd.maxcnt.write(|w| // Note that that nrf52840 maxcnt is a wider // type than a u8, so we use a `_` cast rather than a `u8` cast. // The MAXCNT field is thus at least 8 bits wide and accepts the full // range of values that fit in a `u8`. unsafe { w.maxcnt().bits(tx.len as _ ) }); // Set up the DMA read self.0.rxd.ptr.write(|w| // This is safe for the same reasons that writing to TXD.PTR is // safe. Please refer to the explanation there. unsafe { w.ptr().bits(rx.ptr) }); self.0.rxd.maxcnt.write(|w| // This is safe for the same reasons that writing to TXD.MAXCNT is // safe. Please refer to the explanation there. unsafe { w.maxcnt().bits(rx.len as _) }); // Start SPI transaction self.0.tasks_start.write(|w| // `1` is a valid value to write to task registers. unsafe { w.bits(1) }); // Conservative compiler fence to prevent optimizations that do not // take in to account actions by DMA. The fence has been placed here, // after all possible DMA actions have completed compiler_fence(SeqCst); // Wait for END event // // This event is triggered once both transmitting and receiving are // done. while self.0.events_end.read().bits() == 0 {} // Reset the event, otherwise it will always read `1` from now on. self.0.events_end.write(|w| w); // Conservative compiler fence to prevent optimizations that do not // take in to account actions by DMA. The fence has been placed here, // after all possible DMA actions have completed compiler_fence(SeqCst); if self.0.txd.amount.read().bits() != tx.len { return Err(Error::Transmit); } if self.0.rxd.amount.read().bits() != rx.len { return Err(Error::Receive); } Ok(()) } /// Read from an SPI slave /// /// This method is deprecated. Consider using `transfer` or `transfer_split` #[inline(always)] pub fn read( &mut self, chip_select: &mut Pin<Output<PushPull>>, tx_buffer: &[u8], rx_buffer: &mut [u8], ) -> Result<(), Error> { self.transfer_split_uneven(chip_select, tx_buffer, rx_buffer) } /// Read and write from a SPI slave, using a single buffer /// /// This method implements a complete read transaction, which consists of /// the master transmitting what it wishes to read, and the slave responding /// with the requested data. /// /// Uses the provided chip select pin to initiate the transaction. Transmits /// all bytes in `buffer`, then receives an equal number of bytes. pub fn transfer( &mut self, chip_select: &mut Pin<Output<PushPull>>, buffer: &mut [u8], ) -> Result<(), Error> { ram_slice_check(buffer)?; chip_select.set_low().unwrap(); // Don't return early, as we must reset the CS pin let res = buffer.chunks(EASY_DMA_SIZE).try_for_each(|chunk| { self.do_spi_dma_transfer( DmaSlice::from_slice(chunk), DmaSlice::from_slice(chunk), ) }); chip_select.set_high().unwrap(); res } /// Read and write from a SPI slave, using separate read and write buffers /// /// This method implements a complete read transaction, which consists of /// the master transmitting what it wishes to read, and the slave responding /// with the requested data. /// /// Uses the provided chip select pin to initiate the transaction. Transmits /// all bytes in `tx_buffer`, then receives bytes until `rx_buffer` is full. /// /// If `tx_buffer.len() != rx_buffer.len()`, the transaction will stop at the /// smaller of either buffer. pub fn transfer_split_even( &mut self, chip_select: &mut Pin<Output<PushPull>>, tx_buffer: &[u8], rx_buffer: &mut [u8], ) -> Result<(), Error> { ram_slice_check(tx_buffer)?; ram_slice_check(rx_buffer)?; let txi = tx_buffer.chunks(EASY_DMA_SIZE); let rxi = rx_buffer.chunks_mut(EASY_DMA_SIZE); chip_select.set_low().unwrap(); // Don't return early, as we must reset the CS pin let res = txi.zip(rxi).try_for_each(|(t, r)| { self.do_spi_dma_transfer(DmaSlice::from_slice(t), DmaSlice::from_slice(r)) }); chip_select.set_high().unwrap(); res } /// Read and write from a SPI slave, using separate read and write buffers /// /// This method implements a complete read transaction, which consists of /// the master transmitting what it wishes to read, and the slave responding /// with the requested data. /// /// Uses the provided chip select pin to initiate the transaction. Transmits /// all bytes in `tx_buffer`, then receives bytes until `rx_buffer` is full. /// /// This method is more complicated than the other `transfer` methods because /// it is allowed to perform transactions where `tx_buffer.len() != rx_buffer.len()`. /// If this occurs, extra incoming bytes will be discarded, OR extra outgoing bytes /// will be filled with the `orc` value. pub fn transfer_split_uneven( &mut self, chip_select: &mut Pin<Output<PushPull>>, tx_buffer: &[u8], rx_buffer: &mut [u8], ) -> Result<(), Error> { ram_slice_check(tx_buffer)?; ram_slice_check(rx_buffer)?; // For the tx and rx, we want to return Some(chunk) // as long as there is data to send. We then chain a repeat to // the end so once all chunks have been exhausted, we will keep // getting Nones out of the iterators let txi = tx_buffer .chunks(EASY_DMA_SIZE) .map(|c| Some(c)) .chain(repeat_with(|| None)); let rxi = rx_buffer .chunks_mut(EASY_DMA_SIZE) .map(|c| Some(c)) .chain(repeat_with(|| None)); chip_select.set_low().unwrap(); // We then chain the iterators together, and once BOTH are feeding // back Nones, then we are done sending and receiving // // Don't return early, as we must reset the CS pin let res = txi.zip(rxi) .take_while(|(t, r)| t.is_some() && r.is_some()) // We also turn the slices into either a DmaSlice (if there was data), or a null // DmaSlice (if there is no data) .map(|(t, r)| { ( t.map(|t| DmaSlice::from_slice(t)) .unwrap_or_else(|| DmaSlice::null()), r.map(|r| DmaSlice::from_slice(r)) .unwrap_or_else(|| DmaSlice::null()), ) }) .try_for_each(|(t, r)| { self.do_spi_dma_transfer(t, r) }); chip_select.set_high().unwrap(); res } /// Write to an SPI slave /// /// This method uses the provided chip select pin to initiate the /// transaction, then transmits all bytes in `tx_buffer`. All incoming /// bytes are discarded. pub fn write( &mut self, chip_select: &mut Pin<Output<PushPull>>, tx_buffer: &[u8], ) -> Result<(), Error> { ram_slice_check(tx_buffer)?; self.transfer_split_uneven(chip_select, tx_buffer, &mut [0u8; 0]) } /// Return the raw interface to the underlying SPIM peripheral pub fn free(self) -> T { self.0 } } /// GPIO pins for SPIM interface pub struct Pins { /// SPI clock pub sck: Pin<Output<PushPull>>, /// MOSI Master out, slave in /// None if unused pub mosi: Option<Pin<Output<PushPull>>>, /// MISO Master in, slave out /// None if unused pub miso: Option<Pin<Input<Floating>>>, } #[derive(Debug)] pub enum Error { TxBufferTooLong, RxBufferTooLong, /// EasyDMA can only read from data memory, read only buffers in flash will fail DMABufferNotInDataMemory, Transmit, Receive, } fn ram_slice_check(slice: &[u8]) -> Result<(), Error> { if slice_in_ram(slice) { Ok(()) } else { Err(Error::DMABufferNotInDataMemory) } } /// Implemented by all SPIM instances pub trait Instance: Deref<Target = spim0::RegisterBlock> {} impl Instance for SPIM0 {} #[cfg(any(feature = "52832", feature = "52840"))] impl Instance for SPIM1 {} #[cfg(any(feature = "52832", feature = "52840"))] impl Instance for SPIM2 {}
33.565421
116
0.580468
4b3bfb2571286f1c525a1ee01fe7583cca5aaf73
3,767
use crate::V; #[derive(Debug, Default, PartialEq)] #[repr(C)] pub struct Vector3(pub [f64; 3]); impl Vector3 { /// Build a new `Vector3` struct from given `x`, `y` and `z` coordinates pub const fn new(x: f64, y: f64, z: f64) -> Self { Self([x, y, z]) } /// Returns the `x` coordinate of the vector #[inline(always)] pub const fn x(&self) -> f64 { self.0[0] } /// Returns the `y` coordinate of the vector #[inline(always)] pub const fn y(&self) -> f64 { self.0[1] } /// Returns the `z` coordinate of the vector #[inline(always)] pub const fn z(&self) -> f64 { self.0[2] } /// Computes the dot product with `other` pub fn dot(&self, other: &Vector3) -> f64 { self.x() * other.x() + self.y() * other.y() + self.z() * other.z() } /// Computes cross product with `other` pub fn cross(&self, other: &Vector3) -> Vector3 { let [a1, a2, a3] = self.0; let [b1, b2, b3] = other.0; Self::new( a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1 ) } /// Computes the length of the vector #[inline(always)] pub fn length(&self) -> f64 { (self.x() * self.x() + self.y() * self.y() + self.z() * self.z()).sqrt() } /// Computes the unit vector in the direction of this vector #[inline(always)] pub fn unit(&self) -> Self { self / self.length() } } /// Implement negation operator for `Vector3` impl std::ops::Neg for Vector3 { type Output = Self; fn neg(self) -> Self::Output { V!(-self.x(), -self.y(), -self.z()) } } /// Implement addition operator for `Vector3` impl std::ops::Add for Vector3 { type Output = Self; fn add(self, other: Self) -> Self::Output { V!(self.x() + other.x(), self.y() + other.y(), self.z() + other.z()) } } /// Implement subtraction operator for `Vector3` impl std::ops::Sub for Vector3 { type Output = Self; fn sub(self, other: Self) -> Self::Output { V!(self.x() - other.x(), self.y() - other.y(), self.z() - other.z()) } } /// Implement addition operator for `Vector3` impl std::ops::Add<&Vector3> for Vector3 { type Output = Self; fn add(self, other: &Self) -> Self::Output { V!(self.x() + other.x(), self.y() + other.y(), self.z() + other.z()) } } /// Implement subtraction operator for `Vector3` impl std::ops::Sub<&Vector3> for Vector3 { type Output = Self; fn sub(self, other: &Self) -> Self::Output { V!(self.x() - other.x(), self.y() - other.y(), self.z() - other.z()) } } /// Implement subtraction operator for `Vector3` impl std::ops::Sub<Vector3> for &Vector3 { type Output = Vector3; fn sub(self, other: Vector3) -> Self::Output { V!(self.x() - other.x(), self.y() - other.y(), self.z() - other.z()) } } /// Scalar multiplication for `Vector3` impl std::ops::Mul<f64> for Vector3 { type Output = Vector3; fn mul(self, rhs: f64) -> Self::Output { V!(self.x()*rhs, self.y()*rhs, self.z()*rhs) } } /// Scalar multiplication for `&Vector3` impl std::ops::Mul<f64> for &Vector3 { type Output = Vector3; fn mul(self, rhs: f64) -> Self::Output { V!(self.x()*rhs, self.y()*rhs, self.z()*rhs) } } /// Scalar division for `Vector3` impl std::ops::Div<f64> for Vector3 { type Output = Vector3; fn div(self, rhs: f64) -> Self::Output { V!(self.x()/rhs, self.y()/rhs, self.z()/rhs) } } /// Scalar division for `&Vector3` impl std::ops::Div<f64> for &Vector3 { type Output = Vector3; fn div(self, rhs: f64) -> Self::Output { V!(self.x()/rhs, self.y()/rhs, self.z()/rhs) } }
28.11194
80
0.5442
29c6bde8c7df1daf11cf124feed182db2dae4acd
1,500
pub mod cmd; pub mod rsp; use message::{MessageClass, MessageHeader, MessagePayload, MessageType}; use std::io::{Error, ErrorKind}; pub fn parse(header: &MessageHeader, buffer: &[u8]) -> Result<MessagePayload, Error> { match header { MessageHeader { message_type: MessageType::command_response, payload_length: 0x02, message_class: MessageClass::flash, message_id: 0x04, } => Ok(MessagePayload::rsp_flash_ps_erase(rsp::ps_erase::from( buffer, ))), MessageHeader { message_type: MessageType::command_response, payload_length: 0x02, message_class: MessageClass::flash, message_id: 0x01, } => Ok(MessagePayload::rsp_flash_ps_erase_all( rsp::ps_erase_all::from(buffer), )), MessageHeader { message_type: MessageType::command_response, payload_length: _, message_class: MessageClass::flash, message_id: 0x03, } => Ok(MessagePayload::rsp_flash_ps_load(rsp::ps_load::from( buffer, ))), MessageHeader { message_type: MessageType::command_response, payload_length: 0x02, message_class: MessageClass::flash, message_id: 0x02, } => Ok(MessagePayload::rsp_flash_ps_save(rsp::ps_save::from( buffer, ))), _ => Err(Error::from(ErrorKind::InvalidData)), } }
31.25
86
0.588667
bfd883be84876252e9671819c0980948d79dc78a
7,946
// 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. use borrowck::BorrowckCtxt; use rustc::middle::mem_categorization as mc; use rustc::middle::mem_categorization::Categorization; use rustc::middle::mem_categorization::NoteClosureEnv; use rustc::middle::mem_categorization::InteriorOffsetKind as Kind; use rustc::ty; use syntax::ast; use syntax_pos; use errors::DiagnosticBuilder; use borrowck::gather_loans::gather_moves::PatternSource; pub struct MoveErrorCollector<'tcx> { errors: Vec<MoveError<'tcx>> } impl<'tcx> MoveErrorCollector<'tcx> { pub fn new() -> MoveErrorCollector<'tcx> { MoveErrorCollector { errors: Vec::new() } } pub fn add_error(&mut self, error: MoveError<'tcx>) { self.errors.push(error); } pub fn report_potential_errors<'a>(&self, bccx: &BorrowckCtxt<'a, 'tcx>) { report_move_errors(bccx, &self.errors) } } pub struct MoveError<'tcx> { move_from: mc::cmt<'tcx>, move_to: Option<MovePlace<'tcx>> } impl<'tcx> MoveError<'tcx> { pub fn with_move_info(move_from: mc::cmt<'tcx>, move_to: Option<MovePlace<'tcx>>) -> MoveError<'tcx> { MoveError { move_from: move_from, move_to: move_to, } } } #[derive(Clone)] pub struct MovePlace<'tcx> { pub span: syntax_pos::Span, pub name: ast::Name, pub pat_source: PatternSource<'tcx>, } pub struct GroupedMoveErrors<'tcx> { move_from: mc::cmt<'tcx>, move_to_places: Vec<MovePlace<'tcx>> } fn report_move_errors<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, errors: &Vec<MoveError<'tcx>>) { let grouped_errors = group_errors_with_same_origin(errors); for error in &grouped_errors { let mut err = report_cannot_move_out_of(bccx, error.move_from.clone()); let mut is_first_note = true; match error.move_to_places.get(0) { Some(&MovePlace { pat_source: PatternSource::LetDecl(ref e), .. }) => { // ignore patterns that are found at the top-level of a `let`; // see `get_pattern_source()` for details let initializer = e.init.as_ref().expect("should have an initializer to get an error"); if let Ok(snippet) = bccx.tcx.sess.codemap().span_to_snippet(initializer.span) { err.span_suggestion(initializer.span, "consider using a reference instead", format!("&{}", snippet)); } } _ => { for move_to in &error.move_to_places { err = note_move_destination(err, move_to.span, move_to.name, is_first_note); is_first_note = false; } } } if let NoteClosureEnv(upvar_id) = error.move_from.note { let var_node_id = bccx.tcx.hir.def_index_to_node_id(upvar_id.var_id); err.span_label(bccx.tcx.hir.span(var_node_id), "captured outer variable"); } err.emit(); } } fn group_errors_with_same_origin<'tcx>(errors: &Vec<MoveError<'tcx>>) -> Vec<GroupedMoveErrors<'tcx>> { let mut grouped_errors = Vec::new(); for error in errors { append_to_grouped_errors(&mut grouped_errors, error) } return grouped_errors; fn append_to_grouped_errors<'tcx>(grouped_errors: &mut Vec<GroupedMoveErrors<'tcx>>, error: &MoveError<'tcx>) { let move_from_id = error.move_from.id; debug!("append_to_grouped_errors(move_from_id={})", move_from_id); let move_to = if error.move_to.is_some() { vec![error.move_to.clone().unwrap()] } else { Vec::new() }; for ge in &mut *grouped_errors { if move_from_id == ge.move_from.id && error.move_to.is_some() { debug!("appending move_to to list"); ge.move_to_places.extend(move_to); return } } debug!("found a new move from location"); grouped_errors.push(GroupedMoveErrors { move_from: error.move_from.clone(), move_to_places: move_to }) } } // (keep in sync with gather_moves::check_and_get_illegal_move_origin ) fn report_cannot_move_out_of<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, move_from: mc::cmt<'tcx>) -> DiagnosticBuilder<'a> { match move_from.cat { Categorization::Deref(_, mc::BorrowedPtr(..)) | Categorization::Deref(_, mc::Implicit(..)) | Categorization::Deref(_, mc::UnsafePtr(..)) | Categorization::StaticItem => { let mut err = struct_span_err!(bccx, move_from.span, E0507, "cannot move out of {}", move_from.descriptive_string(bccx.tcx)); err.span_label( move_from.span, format!("cannot move out of {}", move_from.descriptive_string(bccx.tcx)) ); err } Categorization::Interior(ref b, mc::InteriorElement(ik)) => { match (&b.ty.sty, ik) { (&ty::TySlice(..), _) | (_, Kind::Index) => { let mut err = struct_span_err!(bccx, move_from.span, E0508, "cannot move out of type `{}`, \ a non-copy array", b.ty); err.span_label(move_from.span, "cannot move out of here"); err } (_, Kind::Pattern) => { span_bug!(move_from.span, "this path should not cause illegal move"); } } } Categorization::Downcast(ref b, _) | Categorization::Interior(ref b, mc::InteriorField(_)) => { match b.ty.sty { ty::TyAdt(def, _) if def.has_dtor(bccx.tcx) => { let mut err = struct_span_err!(bccx, move_from.span, E0509, "cannot move out of type `{}`, \ which implements the `Drop` trait", b.ty); err.span_label(move_from.span, "cannot move out of here"); err }, _ => { span_bug!(move_from.span, "this path should not cause illegal move"); } } } _ => { span_bug!(move_from.span, "this path should not cause illegal move"); } } } fn note_move_destination(mut err: DiagnosticBuilder, move_to_span: syntax_pos::Span, pat_name: ast::Name, is_first_note: bool) -> DiagnosticBuilder { if is_first_note { err.span_label( move_to_span, format!("hint: to prevent move, use `ref {0}` or `ref mut {0}`", pat_name)); err } else { err.span_label(move_to_span, format!("...and here (use `ref {0}` or `ref mut {0}`)", pat_name)); err } }
37.658768
96
0.530204
9174f8e8456f33908d4ccc2d906f7045b480af9a
52,516
// Copyright 2012-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. // // ignore-lexer-test FIXME #15677 //! Simple getopt alternative. //! //! Construct a vector of options, either by using `reqopt`, `optopt`, and `optflag` //! or by building them from components yourself, and pass them to `getopts`, //! along with a vector of actual arguments (not including `argv[0]`). You'll //! either get a failure code back, or a match. You'll have to verify whether //! the amount of 'free' arguments in the match is what you expect. Use `opt_*` //! accessors to get argument values out of the matches object. //! //! Single-character options are expected to appear on the command line with a //! single preceding dash; multiple-character options are expected to be //! proceeded by two dashes. Options that expect an argument accept their //! argument following either a space or an equals sign. Single-character //! options don't require the space. //! //! # Example //! //! The following example shows simple command line parsing for an application //! that requires an input file to be specified, accepts an optional output //! file name following `-o`, and accepts both `-h` and `--help` as optional flags. //! //! ```{.rust} //! extern crate getopts; //! use getopts::{optopt,optflag,getopts,OptGroup}; //! use std::os; //! //! fn do_work(inp: &str, out: Option<String>) { //! println!("{}", inp); //! match out { //! Some(x) => println!("{}", x), //! None => println!("No Output"), //! } //! } //! //! fn print_usage(program: &str, _opts: &[OptGroup]) { //! println!("Usage: {} [options]", program); //! println!("-o\t\tOutput"); //! println!("-h --help\tUsage"); //! } //! //! fn main() { //! let args: Vec<String> = os::args(); //! //! let program = args[0].clone(); //! //! let opts = &[ //! optopt("o", "", "set output file name", "NAME"), //! optflag("h", "help", "print this help menu") //! ]; //! let matches = match getopts(args.tail(), opts) { //! Ok(m) => { m } //! Err(f) => { panic!(f.to_string()) } //! }; //! if matches.opt_present("h") { //! print_usage(program.as_slice(), opts); //! return; //! } //! let output = matches.opt_str("o"); //! let input = if !matches.free.is_empty() { //! matches.free[0].clone() //! } else { //! print_usage(program.as_slice(), opts); //! return; //! }; //! do_work(input.as_slice(), output); //! } //! ``` #![crate_name = "getopts"] #![experimental] #![crate_type = "rlib"] #![crate_type = "dylib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![feature(globs, phase)] #![feature(import_shadowing)] #![deny(missing_docs)] #[cfg(test)] #[phase(plugin, link)] extern crate log; use self::Name::*; use self::HasArg::*; use self::Occur::*; use self::Fail::*; use self::Optval::*; use self::SplitWithinState::*; use self::Whitespace::*; use self::LengthLimit::*; use std::fmt; use std::result::Result::{Err, Ok}; use std::result; use std::string::String; /// Name of an option. Either a string or a single char. #[deriving(Clone, PartialEq, Eq)] pub enum Name { /// A string representing the long name of an option. /// For example: "help" Long(String), /// A char representing the short name of an option. /// For example: 'h' Short(char), } /// Describes whether an option has an argument. #[deriving(Clone, PartialEq, Eq)] pub enum HasArg { /// The option requires an argument. Yes, /// The option takes no argument. No, /// The option argument is optional. Maybe, } impl Copy for HasArg {} /// Describes how often an option may occur. #[deriving(Clone, PartialEq, Eq)] pub enum Occur { /// The option occurs once. Req, /// The option occurs at most once. Optional, /// The option occurs zero or more times. Multi, } impl Copy for Occur {} /// A description of a possible option. #[deriving(Clone, PartialEq, Eq)] pub struct Opt { /// Name of the option pub name: Name, /// Whether it has an argument pub hasarg: HasArg, /// How often it can occur pub occur: Occur, /// Which options it aliases pub aliases: Vec<Opt>, } /// One group of options, e.g., both `-h` and `--help`, along with /// their shared description and properties. #[deriving(Clone, PartialEq, Eq)] pub struct OptGroup { /// Short name of the option, e.g. `h` for a `-h` option pub short_name: String, /// Long name of the option, e.g. `help` for a `--help` option pub long_name: String, /// Hint for argument, e.g. `FILE` for a `-o FILE` option pub hint: String, /// Description for usage help text pub desc: String, /// Whether option has an argument pub hasarg: HasArg, /// How often it can occur pub occur: Occur } /// Describes whether an option is given at all or has a value. #[deriving(Clone, PartialEq, Eq)] enum Optval { Val(String), Given, } /// The result of checking command line arguments. Contains a vector /// of matches and a vector of free strings. #[deriving(Clone, PartialEq, Eq)] pub struct Matches { /// Options that matched opts: Vec<Opt>, /// Values of the Options that matched vals: Vec<Vec<Optval>>, /// Free string fragments pub free: Vec<String>, } /// The type returned when the command line does not conform to the /// expected format. Use the `Show` implementation to output detailed /// information. #[deriving(Clone, PartialEq, Eq)] pub enum Fail { /// The option requires an argument but none was passed. ArgumentMissing(String), /// The passed option is not declared among the possible options. UnrecognizedOption(String), /// A required option is not present. OptionMissing(String), /// A single occurrence option is being used multiple times. OptionDuplicated(String), /// There's an argument being passed to a non-argument option. UnexpectedArgument(String), } /// The type of failure that occurred. #[deriving(PartialEq, Eq)] #[allow(missing_docs)] pub enum FailType { ArgumentMissing_, UnrecognizedOption_, OptionMissing_, OptionDuplicated_, UnexpectedArgument_, } impl Copy for FailType {} /// The result of parsing a command line with a set of options. pub type Result = result::Result<Matches, Fail>; impl Name { fn from_str(nm: &str) -> Name { if nm.len() == 1u { Short(nm.char_at(0u)) } else { Long(nm.to_string()) } } fn to_string(&self) -> String { match *self { Short(ch) => ch.to_string(), Long(ref s) => s.to_string() } } } impl OptGroup { /// Translate OptGroup into Opt. /// (Both short and long names correspond to different Opts). pub fn long_to_short(&self) -> Opt { let OptGroup { short_name, long_name, hasarg, occur, .. } = (*self).clone(); match (short_name.len(), long_name.len()) { (0,0) => panic!("this long-format option was given no name"), (0,_) => Opt { name: Long((long_name)), hasarg: hasarg, occur: occur, aliases: Vec::new() }, (1,0) => Opt { name: Short(short_name.char_at(0)), hasarg: hasarg, occur: occur, aliases: Vec::new() }, (1,_) => Opt { name: Long((long_name)), hasarg: hasarg, occur: occur, aliases: vec!( Opt { name: Short(short_name.char_at(0)), hasarg: hasarg, occur: occur, aliases: Vec::new() } ) }, (_,_) => panic!("something is wrong with the long-form opt") } } } impl Matches { fn opt_vals(&self, nm: &str) -> Vec<Optval> { match find_opt(self.opts.as_slice(), Name::from_str(nm)) { Some(id) => self.vals[id].clone(), None => panic!("No option '{}' defined", nm) } } fn opt_val(&self, nm: &str) -> Option<Optval> { let vals = self.opt_vals(nm); if vals.is_empty() { None } else { Some(vals[0].clone()) } } /// Returns true if an option was matched. pub fn opt_present(&self, nm: &str) -> bool { !self.opt_vals(nm).is_empty() } /// Returns the number of times an option was matched. pub fn opt_count(&self, nm: &str) -> uint { self.opt_vals(nm).len() } /// Returns true if any of several options were matched. pub fn opts_present(&self, names: &[String]) -> bool { for nm in names.iter() { match find_opt(self.opts.as_slice(), Name::from_str(nm.as_slice())) { Some(id) if !self.vals[id].is_empty() => return true, _ => (), }; } false } /// Returns the string argument supplied to one of several matching options or `None`. pub fn opts_str(&self, names: &[String]) -> Option<String> { for nm in names.iter() { match self.opt_val(nm.as_slice()) { Some(Val(ref s)) => return Some(s.clone()), _ => () } } None } /// Returns a vector of the arguments provided to all matches of the given /// option. /// /// Used when an option accepts multiple values. pub fn opt_strs(&self, nm: &str) -> Vec<String> { let mut acc: Vec<String> = Vec::new(); let r = self.opt_vals(nm); for v in r.iter() { match *v { Val(ref s) => acc.push((*s).clone()), _ => () } } acc } /// Returns the string argument supplied to a matching option or `None`. pub fn opt_str(&self, nm: &str) -> Option<String> { let vals = self.opt_vals(nm); if vals.is_empty() { return None::<String>; } match vals[0] { Val(ref s) => Some((*s).clone()), _ => None } } /// Returns the matching string, a default, or none. /// /// Returns none if the option was not present, `def` if the option was /// present but no argument was provided, and the argument if the option was /// present and an argument was provided. pub fn opt_default(&self, nm: &str, def: &str) -> Option<String> { let vals = self.opt_vals(nm); if vals.is_empty() { None } else { match vals[0] { Val(ref s) => Some((*s).clone()), _ => Some(def.to_string()) } } } } fn is_arg(arg: &str) -> bool { arg.len() > 1 && arg.as_bytes()[0] == b'-' } fn find_opt(opts: &[Opt], nm: Name) -> Option<uint> { // Search main options. let pos = opts.iter().position(|opt| opt.name == nm); if pos.is_some() { return pos } // Search in aliases. for candidate in opts.iter() { if candidate.aliases.iter().position(|opt| opt.name == nm).is_some() { return opts.iter().position(|opt| opt.name == candidate.name); } } None } /// Create a long option that is required and takes an argument. /// /// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none /// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none /// * `desc` - Description for usage help /// * `hint` - Hint that is used in place of the argument in the usage help, /// e.g. `"FILE"` for a `-o FILE` option pub fn reqopt(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptGroup { let len = short_name.len(); assert!(len == 1 || len == 0); OptGroup { short_name: short_name.to_string(), long_name: long_name.to_string(), hint: hint.to_string(), desc: desc.to_string(), hasarg: Yes, occur: Req } } /// Create a long option that is optional and takes an argument. /// /// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none /// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none /// * `desc` - Description for usage help /// * `hint` - Hint that is used in place of the argument in the usage help, /// e.g. `"FILE"` for a `-o FILE` option pub fn optopt(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptGroup { let len = short_name.len(); assert!(len == 1 || len == 0); OptGroup { short_name: short_name.to_string(), long_name: long_name.to_string(), hint: hint.to_string(), desc: desc.to_string(), hasarg: Yes, occur: Optional } } /// Create a long option that is optional and does not take an argument. /// /// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none /// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none /// * `desc` - Description for usage help pub fn optflag(short_name: &str, long_name: &str, desc: &str) -> OptGroup { let len = short_name.len(); assert!(len == 1 || len == 0); OptGroup { short_name: short_name.to_string(), long_name: long_name.to_string(), hint: "".to_string(), desc: desc.to_string(), hasarg: No, occur: Optional } } /// Create a long option that can occur more than once and does not /// take an argument. /// /// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none /// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none /// * `desc` - Description for usage help pub fn optflagmulti(short_name: &str, long_name: &str, desc: &str) -> OptGroup { let len = short_name.len(); assert!(len == 1 || len == 0); OptGroup { short_name: short_name.to_string(), long_name: long_name.to_string(), hint: "".to_string(), desc: desc.to_string(), hasarg: No, occur: Multi } } /// Create a long option that is optional and takes an optional argument. /// /// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none /// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none /// * `desc` - Description for usage help /// * `hint` - Hint that is used in place of the argument in the usage help, /// e.g. `"FILE"` for a `-o FILE` option pub fn optflagopt(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptGroup { let len = short_name.len(); assert!(len == 1 || len == 0); OptGroup { short_name: short_name.to_string(), long_name: long_name.to_string(), hint: hint.to_string(), desc: desc.to_string(), hasarg: Maybe, occur: Optional } } /// Create a long option that is optional, takes an argument, and may occur /// multiple times. /// /// * `short_name` - e.g. `"h"` for a `-h` option, or `""` for none /// * `long_name` - e.g. `"help"` for a `--help` option, or `""` for none /// * `desc` - Description for usage help /// * `hint` - Hint that is used in place of the argument in the usage help, /// e.g. `"FILE"` for a `-o FILE` option pub fn optmulti(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptGroup { let len = short_name.len(); assert!(len == 1 || len == 0); OptGroup { short_name: short_name.to_string(), long_name: long_name.to_string(), hint: hint.to_string(), desc: desc.to_string(), hasarg: Yes, occur: Multi } } /// Create a generic option group, stating all parameters explicitly pub fn opt(short_name: &str, long_name: &str, desc: &str, hint: &str, hasarg: HasArg, occur: Occur) -> OptGroup { let len = short_name.len(); assert!(len == 1 || len == 0); OptGroup { short_name: short_name.to_string(), long_name: long_name.to_string(), hint: hint.to_string(), desc: desc.to_string(), hasarg: hasarg, occur: occur } } impl Fail { /// Convert a `Fail` enum into an error string. #[deprecated="use `Show` (`{}` format specifier)"] pub fn to_err_msg(self) -> String { self.to_string() } } impl fmt::Show for Fail { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ArgumentMissing(ref nm) => { write!(f, "Argument to option '{}' missing.", *nm) } UnrecognizedOption(ref nm) => { write!(f, "Unrecognized option: '{}'.", *nm) } OptionMissing(ref nm) => { write!(f, "Required option '{}' missing.", *nm) } OptionDuplicated(ref nm) => { write!(f, "Option '{}' given more than once.", *nm) } UnexpectedArgument(ref nm) => { write!(f, "Option '{}' does not take an argument.", *nm) } } } } /// Parse command line arguments according to the provided options. /// /// On success returns `Ok(Matches)`. Use methods such as `opt_present` /// `opt_str`, etc. to interrogate results. /// # Panics /// /// Returns `Err(Fail)` on failure: use the `Show` implementation of `Fail` to display /// information about it. pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { let opts: Vec<Opt> = optgrps.iter().map(|x| x.long_to_short()).collect(); let n_opts = opts.len(); fn f(_x: uint) -> Vec<Optval> { return Vec::new(); } let mut vals = Vec::from_fn(n_opts, f); let mut free: Vec<String> = Vec::new(); let l = args.len(); let mut i = 0; while i < l { let cur = args[i].clone(); let curlen = cur.len(); if !is_arg(cur.as_slice()) { free.push(cur); } else if cur == "--" { let mut j = i + 1; while j < l { free.push(args[j].clone()); j += 1; } break; } else { let mut names; let mut i_arg = None; if cur.as_bytes()[1] == b'-' { let tail = cur.slice(2, curlen); let tail_eq: Vec<&str> = tail.split('=').collect(); if tail_eq.len() <= 1 { names = vec!(Long(tail.to_string())); } else { names = vec!(Long(tail_eq[0].to_string())); i_arg = Some(tail_eq[1].to_string()); } } else { let mut j = 1; names = Vec::new(); while j < curlen { let range = cur.char_range_at(j); let opt = Short(range.ch); /* In a series of potential options (eg. -aheJ), if we see one which takes an argument, we assume all subsequent characters make up the argument. This allows options such as -L/usr/local/lib/foo to be interpreted correctly */ let opt_id = match find_opt(opts.as_slice(), opt.clone()) { Some(id) => id, None => return Err(UnrecognizedOption(opt.to_string())) }; names.push(opt); let arg_follows = match opts[opt_id].hasarg { Yes | Maybe => true, No => false }; if arg_follows && range.next < curlen { i_arg = Some(cur.slice(range.next, curlen).to_string()); break; } j = range.next; } } let mut name_pos = 0; for nm in names.iter() { name_pos += 1; let optid = match find_opt(opts.as_slice(), (*nm).clone()) { Some(id) => id, None => return Err(UnrecognizedOption(nm.to_string())) }; match opts[optid].hasarg { No => { if name_pos == names.len() && !i_arg.is_none() { return Err(UnexpectedArgument(nm.to_string())); } vals[optid].push(Given); } Maybe => { if !i_arg.is_none() { vals[optid] .push(Val((i_arg.clone()) .unwrap())); } else if name_pos < names.len() || i + 1 == l || is_arg(args[i + 1].as_slice()) { vals[optid].push(Given); } else { i += 1; vals[optid].push(Val(args[i].clone())); } } Yes => { if !i_arg.is_none() { vals[optid].push(Val(i_arg.clone().unwrap())); } else if i + 1 == l { return Err(ArgumentMissing(nm.to_string())); } else { i += 1; vals[optid].push(Val(args[i].clone())); } } } } } i += 1; } for i in range(0u, n_opts) { let n = vals[i].len(); let occ = opts[i].occur; if occ == Req && n == 0 { return Err(OptionMissing(opts[i].name.to_string())); } if occ != Multi && n > 1 { return Err(OptionDuplicated(opts[i].name.to_string())); } } Ok(Matches { opts: opts, vals: vals, free: free }) } /// Derive a usage message from a set of long options. pub fn usage(brief: &str, opts: &[OptGroup]) -> String { let desc_sep = format!("\n{}", " ".repeat(24)); let rows = opts.iter().map(|optref| { let OptGroup{short_name, long_name, hint, desc, hasarg, ..} = (*optref).clone(); let mut row = " ".repeat(4); // short option match short_name.len() { 0 => {} 1 => { row.push('-'); row.push_str(short_name.as_slice()); row.push(' '); } _ => panic!("the short name should only be 1 ascii char long"), } // long option match long_name.len() { 0 => {} _ => { row.push_str("--"); row.push_str(long_name.as_slice()); row.push(' '); } } // arg match hasarg { No => {} Yes => row.push_str(hint.as_slice()), Maybe => { row.push('['); row.push_str(hint.as_slice()); row.push(']'); } } // FIXME: #5516 should be graphemes not codepoints // here we just need to indent the start of the description let rowlen = row.char_len(); if rowlen < 24 { for _ in range(0, 24 - rowlen) { row.push(' '); } } else { row.push_str(desc_sep.as_slice()) } // Normalize desc to contain words separated by one space character let mut desc_normalized_whitespace = String::new(); for word in desc.words() { desc_normalized_whitespace.push_str(word); desc_normalized_whitespace.push(' '); } // FIXME: #5516 should be graphemes not codepoints let mut desc_rows = Vec::new(); each_split_within(desc_normalized_whitespace.as_slice(), 54, |substr| { desc_rows.push(substr.to_string()); true }); // FIXME: #5516 should be graphemes not codepoints // wrapped description row.push_str(desc_rows.connect(desc_sep.as_slice()).as_slice()); row }); format!("{}\n\nOptions:\n{}\n", brief, rows.collect::<Vec<String>>().connect("\n")) } fn format_option(opt: &OptGroup) -> String { let mut line = String::new(); if opt.occur != Req { line.push('['); } // Use short_name is possible, but fallback to long_name. if opt.short_name.len() > 0 { line.push('-'); line.push_str(opt.short_name.as_slice()); } else { line.push_str("--"); line.push_str(opt.long_name.as_slice()); } if opt.hasarg != No { line.push(' '); if opt.hasarg == Maybe { line.push('['); } line.push_str(opt.hint.as_slice()); if opt.hasarg == Maybe { line.push(']'); } } if opt.occur != Req { line.push(']'); } if opt.occur == Multi { line.push_str(".."); } line } /// Derive a short one-line usage summary from a set of long options. pub fn short_usage(program_name: &str, opts: &[OptGroup]) -> String { let mut line = format!("Usage: {} ", program_name); line.push_str(opts.iter() .map(format_option) .collect::<Vec<String>>() .connect(" ") .as_slice()); line } enum SplitWithinState { A, // leading whitespace, initial state B, // words C, // internal and trailing whitespace } impl Copy for SplitWithinState {} enum Whitespace { Ws, // current char is whitespace Cr // current char is not whitespace } impl Copy for Whitespace {} enum LengthLimit { UnderLim, // current char makes current substring still fit in limit OverLim // current char makes current substring no longer fit in limit } impl Copy for LengthLimit {} /// Splits a string into substrings with possibly internal whitespace, /// each of them at most `lim` bytes long. The substrings have leading and trailing /// whitespace removed, and are only cut at whitespace boundaries. /// /// Note: Function was moved here from `std::str` because this module is the only place that /// uses it, and because it was too specific for a general string function. /// /// # Panics /// /// Panics during iteration if the string contains a non-whitespace /// sequence longer than the limit. fn each_split_within<'a>(ss: &'a str, lim: uint, it: |&'a str| -> bool) -> bool { // Just for fun, let's write this as a state machine: let mut slice_start = 0; let mut last_start = 0; let mut last_end = 0; let mut state = A; let mut fake_i = ss.len(); let mut lim = lim; let mut cont = true; // if the limit is larger than the string, lower it to save cycles if lim >= fake_i { lim = fake_i; } let machine: |&mut bool, (uint, char)| -> bool = |cont, (i, c)| { let whitespace = if c.is_whitespace() { Ws } else { Cr }; let limit = if (i - slice_start + 1) <= lim { UnderLim } else { OverLim }; state = match (state, whitespace, limit) { (A, Ws, _) => { A } (A, Cr, _) => { slice_start = i; last_start = i; B } (B, Cr, UnderLim) => { B } (B, Cr, OverLim) if (i - last_start + 1) > lim => panic!("word starting with {} longer than limit!", ss.slice(last_start, i + 1)), (B, Cr, OverLim) => { *cont = it(ss.slice(slice_start, last_end)); slice_start = last_start; B } (B, Ws, UnderLim) => { last_end = i; C } (B, Ws, OverLim) => { last_end = i; *cont = it(ss.slice(slice_start, last_end)); A } (C, Cr, UnderLim) => { last_start = i; B } (C, Cr, OverLim) => { *cont = it(ss.slice(slice_start, last_end)); slice_start = i; last_start = i; last_end = i; B } (C, Ws, OverLim) => { *cont = it(ss.slice(slice_start, last_end)); A } (C, Ws, UnderLim) => { C } }; *cont }; ss.char_indices().all(|x| machine(&mut cont, x)); // Let the automaton 'run out' by supplying trailing whitespace while cont && match state { B | C => true, A => false } { machine(&mut cont, (fake_i, ' ')); fake_i += 1; } return cont; } #[test] fn test_split_within() { fn t(s: &str, i: uint, u: &[String]) { let mut v = Vec::new(); each_split_within(s, i, |s| { v.push(s.to_string()); true }); assert!(v.iter().zip(u.iter()).all(|(a,b)| a == b)); } t("", 0, &[]); t("", 15, &[]); t("hello", 15, &["hello".to_string()]); t("\nMary had a little lamb\nLittle lamb\n", 15, &[ "Mary had a".to_string(), "little lamb".to_string(), "Little lamb".to_string() ]); t("\nMary had a little lamb\nLittle lamb\n", ::std::uint::MAX, &["Mary had a little lamb\nLittle lamb".to_string()]); } #[cfg(test)] mod tests { use super::*; use super::Fail::*; use std::result::Result::{Err, Ok}; use std::result; // Tests for reqopt #[test] fn test_reqopt() { let long_args = vec!("--test=20".to_string()); let opts = vec!(reqopt("t", "test", "testing", "TEST")); let rs = getopts(long_args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert!(m.opt_present("test")); assert_eq!(m.opt_str("test").unwrap(), "20"); assert!(m.opt_present("t")); assert_eq!(m.opt_str("t").unwrap(), "20"); } _ => { panic!("test_reqopt failed (long arg)"); } } let short_args = vec!("-t".to_string(), "20".to_string()); match getopts(short_args.as_slice(), opts.as_slice()) { Ok(ref m) => { assert!((m.opt_present("test"))); assert_eq!(m.opt_str("test").unwrap(), "20"); assert!((m.opt_present("t"))); assert_eq!(m.opt_str("t").unwrap(), "20"); } _ => { panic!("test_reqopt failed (short arg)"); } } } #[test] fn test_reqopt_missing() { let args = vec!("blah".to_string()); let opts = vec!(reqopt("t", "test", "testing", "TEST")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Err(OptionMissing(_)) => {}, _ => panic!() } } #[test] fn test_reqopt_no_arg() { let long_args = vec!("--test".to_string()); let opts = vec!(reqopt("t", "test", "testing", "TEST")); let rs = getopts(long_args.as_slice(), opts.as_slice()); match rs { Err(ArgumentMissing(_)) => {}, _ => panic!() } let short_args = vec!("-t".to_string()); match getopts(short_args.as_slice(), opts.as_slice()) { Err(ArgumentMissing(_)) => {}, _ => panic!() } } #[test] fn test_reqopt_multi() { let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string()); let opts = vec!(reqopt("t", "test", "testing", "TEST")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Err(OptionDuplicated(_)) => {}, _ => panic!() } } // Tests for optopt #[test] fn test_optopt() { let long_args = vec!("--test=20".to_string()); let opts = vec!(optopt("t", "test", "testing", "TEST")); let rs = getopts(long_args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert!(m.opt_present("test")); assert_eq!(m.opt_str("test").unwrap(), "20"); assert!((m.opt_present("t"))); assert_eq!(m.opt_str("t").unwrap(), "20"); } _ => panic!() } let short_args = vec!("-t".to_string(), "20".to_string()); match getopts(short_args.as_slice(), opts.as_slice()) { Ok(ref m) => { assert!((m.opt_present("test"))); assert_eq!(m.opt_str("test").unwrap(), "20"); assert!((m.opt_present("t"))); assert_eq!(m.opt_str("t").unwrap(), "20"); } _ => panic!() } } #[test] fn test_optopt_missing() { let args = vec!("blah".to_string()); let opts = vec!(optopt("t", "test", "testing", "TEST")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert!(!m.opt_present("test")); assert!(!m.opt_present("t")); } _ => panic!() } } #[test] fn test_optopt_no_arg() { let long_args = vec!("--test".to_string()); let opts = vec!(optopt("t", "test", "testing", "TEST")); let rs = getopts(long_args.as_slice(), opts.as_slice()); match rs { Err(ArgumentMissing(_)) => {}, _ => panic!() } let short_args = vec!("-t".to_string()); match getopts(short_args.as_slice(), opts.as_slice()) { Err(ArgumentMissing(_)) => {}, _ => panic!() } } #[test] fn test_optopt_multi() { let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string()); let opts = vec!(optopt("t", "test", "testing", "TEST")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Err(OptionDuplicated(_)) => {}, _ => panic!() } } // Tests for optflag #[test] fn test_optflag() { let long_args = vec!("--test".to_string()); let opts = vec!(optflag("t", "test", "testing")); let rs = getopts(long_args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert!(m.opt_present("test")); assert!(m.opt_present("t")); } _ => panic!() } let short_args = vec!("-t".to_string()); match getopts(short_args.as_slice(), opts.as_slice()) { Ok(ref m) => { assert!(m.opt_present("test")); assert!(m.opt_present("t")); } _ => panic!() } } #[test] fn test_optflag_missing() { let args = vec!("blah".to_string()); let opts = vec!(optflag("t", "test", "testing")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert!(!m.opt_present("test")); assert!(!m.opt_present("t")); } _ => panic!() } } #[test] fn test_optflag_long_arg() { let args = vec!("--test=20".to_string()); let opts = vec!(optflag("t", "test", "testing")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Err(UnexpectedArgument(_)) => {}, _ => panic!() } } #[test] fn test_optflag_multi() { let args = vec!("--test".to_string(), "-t".to_string()); let opts = vec!(optflag("t", "test", "testing")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Err(OptionDuplicated(_)) => {}, _ => panic!() } } #[test] fn test_optflag_short_arg() { let args = vec!("-t".to_string(), "20".to_string()); let opts = vec!(optflag("t", "test", "testing")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { // The next variable after the flag is just a free argument assert!(m.free[0] == "20"); } _ => panic!() } } // Tests for optflagmulti #[test] fn test_optflagmulti_short1() { let args = vec!("-v".to_string()); let opts = vec!(optflagmulti("v", "verbose", "verbosity")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert_eq!(m.opt_count("v"), 1); } _ => panic!() } } #[test] fn test_optflagmulti_short2a() { let args = vec!("-v".to_string(), "-v".to_string()); let opts = vec!(optflagmulti("v", "verbose", "verbosity")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert_eq!(m.opt_count("v"), 2); } _ => panic!() } } #[test] fn test_optflagmulti_short2b() { let args = vec!("-vv".to_string()); let opts = vec!(optflagmulti("v", "verbose", "verbosity")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert_eq!(m.opt_count("v"), 2); } _ => panic!() } } #[test] fn test_optflagmulti_long1() { let args = vec!("--verbose".to_string()); let opts = vec!(optflagmulti("v", "verbose", "verbosity")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert_eq!(m.opt_count("verbose"), 1); } _ => panic!() } } #[test] fn test_optflagmulti_long2() { let args = vec!("--verbose".to_string(), "--verbose".to_string()); let opts = vec!(optflagmulti("v", "verbose", "verbosity")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert_eq!(m.opt_count("verbose"), 2); } _ => panic!() } } #[test] fn test_optflagmulti_mix() { let args = vec!("--verbose".to_string(), "-v".to_string(), "-vv".to_string(), "verbose".to_string()); let opts = vec!(optflagmulti("v", "verbose", "verbosity")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert_eq!(m.opt_count("verbose"), 4); assert_eq!(m.opt_count("v"), 4); } _ => panic!() } } // Tests for optmulti #[test] fn test_optmulti() { let long_args = vec!("--test=20".to_string()); let opts = vec!(optmulti("t", "test", "testing", "TEST")); let rs = getopts(long_args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert!((m.opt_present("test"))); assert_eq!(m.opt_str("test").unwrap(), "20"); assert!((m.opt_present("t"))); assert_eq!(m.opt_str("t").unwrap(), "20"); } _ => panic!() } let short_args = vec!("-t".to_string(), "20".to_string()); match getopts(short_args.as_slice(), opts.as_slice()) { Ok(ref m) => { assert!((m.opt_present("test"))); assert_eq!(m.opt_str("test").unwrap(), "20"); assert!((m.opt_present("t"))); assert_eq!(m.opt_str("t").unwrap(), "20"); } _ => panic!() } } #[test] fn test_optmulti_missing() { let args = vec!("blah".to_string()); let opts = vec!(optmulti("t", "test", "testing", "TEST")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert!(!m.opt_present("test")); assert!(!m.opt_present("t")); } _ => panic!() } } #[test] fn test_optmulti_no_arg() { let long_args = vec!("--test".to_string()); let opts = vec!(optmulti("t", "test", "testing", "TEST")); let rs = getopts(long_args.as_slice(), opts.as_slice()); match rs { Err(ArgumentMissing(_)) => {}, _ => panic!() } let short_args = vec!("-t".to_string()); match getopts(short_args.as_slice(), opts.as_slice()) { Err(ArgumentMissing(_)) => {}, _ => panic!() } } #[test] fn test_optmulti_multi() { let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string()); let opts = vec!(optmulti("t", "test", "testing", "TEST")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert!(m.opt_present("test")); assert_eq!(m.opt_str("test").unwrap(), "20"); assert!(m.opt_present("t")); assert_eq!(m.opt_str("t").unwrap(), "20"); let pair = m.opt_strs("test"); assert!(pair[0] == "20"); assert!(pair[1] == "30"); } _ => panic!() } } #[test] fn test_unrecognized_option() { let long_args = vec!("--untest".to_string()); let opts = vec!(optmulti("t", "test", "testing", "TEST")); let rs = getopts(long_args.as_slice(), opts.as_slice()); match rs { Err(UnrecognizedOption(_)) => {}, _ => panic!() } let short_args = vec!("-u".to_string()); match getopts(short_args.as_slice(), opts.as_slice()) { Err(UnrecognizedOption(_)) => {}, _ => panic!() } } #[test] fn test_combined() { let args = vec!("prog".to_string(), "free1".to_string(), "-s".to_string(), "20".to_string(), "free2".to_string(), "--flag".to_string(), "--long=30".to_string(), "-f".to_string(), "-m".to_string(), "40".to_string(), "-m".to_string(), "50".to_string(), "-n".to_string(), "-A B".to_string(), "-n".to_string(), "-60 70".to_string()); let opts = vec!(optopt("s", "something", "something", "SOMETHING"), optflag("", "flag", "a flag"), reqopt("", "long", "hi", "LONG"), optflag("f", "", "another flag"), optmulti("m", "", "mmmmmm", "YUM"), optmulti("n", "", "nothing", "NOTHING"), optopt("", "notpresent", "nothing to see here", "NOPE")); let rs = getopts(args.as_slice(), opts.as_slice()); match rs { Ok(ref m) => { assert!(m.free[0] == "prog"); assert!(m.free[1] == "free1"); assert_eq!(m.opt_str("s").unwrap(), "20"); assert!(m.free[2] == "free2"); assert!((m.opt_present("flag"))); assert_eq!(m.opt_str("long").unwrap(), "30"); assert!((m.opt_present("f"))); let pair = m.opt_strs("m"); assert!(pair[0] == "40"); assert!(pair[1] == "50"); let pair = m.opt_strs("n"); assert!(pair[0] == "-A B"); assert!(pair[1] == "-60 70"); assert!((!m.opt_present("notpresent"))); } _ => panic!() } } #[test] fn test_multi() { let opts = vec!(optopt("e", "", "encrypt", "ENCRYPT"), optopt("", "encrypt", "encrypt", "ENCRYPT"), optopt("f", "", "flag", "FLAG")); let args_single = vec!("-e".to_string(), "foo".to_string()); let matches_single = &match getopts(args_single.as_slice(), opts.as_slice()) { result::Result::Ok(m) => m, result::Result::Err(_) => panic!() }; assert!(matches_single.opts_present(&["e".to_string()])); assert!(matches_single.opts_present(&["encrypt".to_string(), "e".to_string()])); assert!(matches_single.opts_present(&["e".to_string(), "encrypt".to_string()])); assert!(!matches_single.opts_present(&["encrypt".to_string()])); assert!(!matches_single.opts_present(&["thing".to_string()])); assert!(!matches_single.opts_present(&[])); assert_eq!(matches_single.opts_str(&["e".to_string()]).unwrap(), "foo"); assert_eq!(matches_single.opts_str(&["e".to_string(), "encrypt".to_string()]).unwrap(), "foo"); assert_eq!(matches_single.opts_str(&["encrypt".to_string(), "e".to_string()]).unwrap(), "foo"); let args_both = vec!("-e".to_string(), "foo".to_string(), "--encrypt".to_string(), "foo".to_string()); let matches_both = &match getopts(args_both.as_slice(), opts.as_slice()) { result::Result::Ok(m) => m, result::Result::Err(_) => panic!() }; assert!(matches_both.opts_present(&["e".to_string()])); assert!(matches_both.opts_present(&["encrypt".to_string()])); assert!(matches_both.opts_present(&["encrypt".to_string(), "e".to_string()])); assert!(matches_both.opts_present(&["e".to_string(), "encrypt".to_string()])); assert!(!matches_both.opts_present(&["f".to_string()])); assert!(!matches_both.opts_present(&["thing".to_string()])); assert!(!matches_both.opts_present(&[])); assert_eq!(matches_both.opts_str(&["e".to_string()]).unwrap(), "foo"); assert_eq!(matches_both.opts_str(&["encrypt".to_string()]).unwrap(), "foo"); assert_eq!(matches_both.opts_str(&["e".to_string(), "encrypt".to_string()]).unwrap(), "foo"); assert_eq!(matches_both.opts_str(&["encrypt".to_string(), "e".to_string()]).unwrap(), "foo"); } #[test] fn test_nospace() { let args = vec!("-Lfoo".to_string(), "-M.".to_string()); let opts = vec!(optmulti("L", "", "library directory", "LIB"), optmulti("M", "", "something", "MMMM")); let matches = &match getopts(args.as_slice(), opts.as_slice()) { result::Result::Ok(m) => m, result::Result::Err(_) => panic!() }; assert!(matches.opts_present(&["L".to_string()])); assert_eq!(matches.opts_str(&["L".to_string()]).unwrap(), "foo"); assert!(matches.opts_present(&["M".to_string()])); assert_eq!(matches.opts_str(&["M".to_string()]).unwrap(), "."); } #[test] fn test_nospace_conflict() { let args = vec!("-vvLverbose".to_string(), "-v".to_string() ); let opts = vec!(optmulti("L", "", "library directory", "LIB"), optflagmulti("v", "verbose", "Verbose")); let matches = &match getopts(args.as_slice(), opts.as_slice()) { result::Result::Ok(m) => m, result::Result::Err(e) => panic!( "{}", e ) }; assert!(matches.opts_present(&["L".to_string()])); assert_eq!(matches.opts_str(&["L".to_string()]).unwrap(), "verbose"); assert!(matches.opts_present(&["v".to_string()])); assert_eq!(3, matches.opt_count("v")); } #[test] fn test_long_to_short() { let mut short = Opt { name: Name::Long("banana".to_string()), hasarg: HasArg::Yes, occur: Occur::Req, aliases: Vec::new(), }; short.aliases = vec!(Opt { name: Name::Short('b'), hasarg: HasArg::Yes, occur: Occur::Req, aliases: Vec::new() }); let verbose = reqopt("b", "banana", "some bananas", "VAL"); assert!(verbose.long_to_short() == short); } #[test] fn test_aliases_long_and_short() { let opts = vec!( optflagmulti("a", "apple", "Desc")); let args = vec!("-a".to_string(), "--apple".to_string(), "-a".to_string()); let matches = getopts(args.as_slice(), opts.as_slice()).unwrap(); assert_eq!(3, matches.opt_count("a")); assert_eq!(3, matches.opt_count("apple")); } #[test] fn test_usage() { let optgroups = vec!( reqopt("b", "banana", "Desc", "VAL"), optopt("a", "012345678901234567890123456789", "Desc", "VAL"), optflag("k", "kiwi", "Desc"), optflagopt("p", "", "Desc", "VAL"), optmulti("l", "", "Desc", "VAL")); let expected = "Usage: fruits Options: -b --banana VAL Desc -a --012345678901234567890123456789 VAL Desc -k --kiwi Desc -p [VAL] Desc -l VAL Desc "; let generated_usage = usage("Usage: fruits", optgroups.as_slice()); debug!("expected: <<{}>>", expected); debug!("generated: <<{}>>", generated_usage); assert_eq!(generated_usage, expected); } #[test] fn test_usage_description_wrapping() { // indentation should be 24 spaces // lines wrap after 78: or rather descriptions wrap after 54 let optgroups = vec!( optflag("k", "kiwi", "This is a long description which won't be wrapped..+.."), // 54 optflag("a", "apple", "This is a long description which _will_ be wrapped..+..")); let expected = "Usage: fruits Options: -k --kiwi This is a long description which won't be wrapped..+.. -a --apple This is a long description which _will_ be wrapped..+.. "; let usage = usage("Usage: fruits", optgroups.as_slice()); debug!("expected: <<{}>>", expected); debug!("generated: <<{}>>", usage); assert!(usage == expected) } #[test] fn test_usage_description_multibyte_handling() { let optgroups = vec!( optflag("k", "k\u2013w\u2013", "The word kiwi is normally spelled with two i's"), optflag("a", "apple", "This \u201Cdescription\u201D has some characters that could \ confuse the line wrapping; an apple costs 0.51€ in some parts of Europe.")); let expected = "Usage: fruits Options: -k --k–w– The word kiwi is normally spelled with two i's -a --apple This “description” has some characters that could confuse the line wrapping; an apple costs 0.51€ in some parts of Europe. "; let usage = usage("Usage: fruits", optgroups.as_slice()); debug!("expected: <<{}>>", expected); debug!("generated: <<{}>>", usage); assert!(usage == expected) } #[test] fn test_short_usage() { let optgroups = vec!( reqopt("b", "banana", "Desc", "VAL"), optopt("a", "012345678901234567890123456789", "Desc", "VAL"), optflag("k", "kiwi", "Desc"), optflagopt("p", "", "Desc", "VAL"), optmulti("l", "", "Desc", "VAL")); let expected = "Usage: fruits -b VAL [-a VAL] [-k] [-p [VAL]] [-l VAL]..".to_string(); let generated_usage = short_usage("fruits", optgroups.as_slice()); debug!("expected: <<{}>>", expected); debug!("generated: <<{}>>", generated_usage); assert_eq!(generated_usage, expected); } }
32.557967
95
0.503047
719921663c91a1db49147e48714790cfa46fcf0f
4,921
/// Return the basic type name, stripped of any crates. pub(crate) fn basic_type_name<T>() -> &'static str { let tn = std::any::type_name::<T>(); match tn.rsplit_once("::") { Some((_, basic)) => basic, None => tn, } } /// Implement Display for a given class by formatting it as pretty-printed JSON. macro_rules! display_json { ($cls:ident) => { impl Display for $cls { fn fmt(&self, f: &mut Formatter) -> FmtResult { let buf = Vec::new(); let serde_formatter = ::serde_json::ser::PrettyFormatter::with_indent(b" "); let mut ser = ::serde_json::Serializer::with_formatter(buf, serde_formatter); match self.serialize(&mut ser) { Ok(()) => (), Err(e) => { error!("Failed to serialize {}: {:?}", crate::macros::basic_type_name::<Self>(), e); return Err(FmtError); } }; match from_utf8(&ser.into_inner()) { Ok(s) => write!(f, "{}", s), Err(e) => { error!("JSON serialization of {} contained non-UTF-8 characters: {:?}", crate::macros::basic_type_name::<Self>(), e); Err(FmtError) } } } } } } /// Implement FromStr for a given class by parsing it as JSON. macro_rules! from_str_json { ($cls:ident) => { impl FromStr for $cls { type Err = ::serde_json::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { match ::serde_json::from_str::<Self>(s) { Ok(result) => Ok(result), Err(e) => { debug!("Failed to parse policy: {}: {:?}", s, e); Err(e) } } } } }; } // macro_rules! create_list_enum { // ($list:ident, $visitor:ident, $final:ident) => { // #[derive(Debug, PartialEq)] // pub enum $list { // Single($final), // List(std::vec::Vec<$final>), // } // struct $visitor {} // impl<'de> ::serde::de::Visitor<'de> for $visitor { // type Value = $list; // fn expecting(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { // write!(f, "{} or list of {}", crate::macros::basic_type_name::<$final>(), crate::macros::basic_type_name::<$final>()) // } // fn visit_map<A>(self, access: A) -> Result<Self::Value, A::Error> // where // A: ::serde::de::MapAccess<'de> // { // let deserializer = ::serde::de::value::MapAccessDeserializer::new(access); // let value = match $final::deserialize(deserializer) { // Ok(value) => value, // Err(e) => { // ::log::debug!("Failed to deserialize {}: {:?}", crate::macros::basic_type_name::<$final>(), e); // return Err(<A::Error as ::serde::de::Error>::invalid_value(::serde::de::Unexpected::Map, &self)); // } // }; // Ok($list::Single(value)) // } // fn visit_seq<A>(self, access: A) -> Result<Self::Value, A::Error> // where // A: ::serde::de::SeqAccess<'de> // { // let deserializer = ::serde::de::value::SeqAccessDeserializer::new(access); // let value = match ::std::vec::Vec::<$final>::deserialize(deserializer) { // Ok(l) => l, // Err(e) => { // ::log::debug!("Failed to deserialize {} list: {:?}", crate::macros::basic_type_name::<$final>(), e); // return Err(<A::Error as ::serde::de::Error>::invalid_value(::serde::de::Unexpected::Seq, &self)); // } // }; // Ok($list::List(value)) // } // } // impl<'de> ::serde::de::Deserialize<'de> for $list { // fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> // where // D: ::serde::de::Deserializer<'de> // { // deserializer.deserialize_any($visitor {}) // } // } // impl ::serde::ser::Serialize for $list { // fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> // where // S: ::serde::ser::Serializer // { // match self { // Self::Single(v) => v.serialize(serializer), // Self::List(v) => v.serialize(serializer), // } // } // } // } // }
39.368
141
0.4304
fb971526ba8e884b4c057a41d6cda492da3f95f3
1,224
use std::borrow::Cow; use reqwest::Method; use crate::api::req::HttpReq; use crate::api::resp::RespType; use crate::api::TGReq; use crate::errors::TGBotResult; use crate::types::ReplyMarkup; use crate::vision::PossibilityMessage; /// Use this method to edit captions of messages sent by the bot. #[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)] #[must_use = "requests do nothing unless sent"] pub struct EditMessageCaption<'s> { chat_id: i64, message_id: i64, caption: Cow<'s, str>, #[serde(skip_serializing_if = "Option::is_none")] reply_markup: Option<ReplyMarkup>, } impl<'s> TGReq for EditMessageCaption<'s> { type Resp = RespType<PossibilityMessage>; fn request(&self) -> TGBotResult<HttpReq> { HttpReq::json_req(Method::POST, "editMessageCaption", self) } } impl<'s> EditMessageCaption<'s> { pub fn new<T>(chat: i64, message_id: i64, caption: T) -> Self where T: Into<Cow<'s, str>> { EditMessageCaption { chat_id: chat, message_id, caption: caption.into(), reply_markup: None, } } pub fn reply_markup<R>(&mut self, reply_markup: R) -> &mut Self where R: Into<ReplyMarkup> { self.reply_markup = Some(reply_markup.into()); self } }
26.042553
94
0.683007
916c26e9f287b2cb81f421bf6f9fc500e7dd22e5
3,604
use crate::{ for_each2, for_each3, Array2ForEach, Array3ForEach, ArrayForEach, ArrayStrideIter, Local, Local2i, Local3i, LockStepArrayForEach, LockStepArrayForEach2, LockStepArrayForEach3, Stride, }; use building_blocks_core::prelude::*; pub trait ArrayIndexer<N> { fn stride_from_local_point(shape: PointN<N>, point: Local<N>) -> Stride; fn make_stride_iter( array_shape: PointN<N>, origin: Local<N>, step: PointN<N>, ) -> ArrayStrideIter; fn for_each(for_each: ArrayForEach<N>, f: impl FnMut(PointN<N>, Stride)); fn for_each_lockstep_unchecked( for_each: LockStepArrayForEach<N>, f: impl FnMut(PointN<N>, (Stride, Stride)), ); #[inline] fn strides_from_local_points(shape: PointN<N>, points: &[Local<N>], strides: &mut [Stride]) where PointN<N>: Copy, { for (i, p) in points.iter().enumerate() { strides[i] = Self::stride_from_local_point(shape, *p); } } } impl ArrayIndexer<[i32; 2]> for [i32; 2] { #[inline] fn stride_from_local_point(s: Point2i, p: Local2i) -> Stride { Stride((p.y() * s.x() + p.x()) as usize) } #[inline] fn make_stride_iter(array_shape: Point2i, origin: Local2i, step: Point2i) -> ArrayStrideIter { ArrayStrideIter::new_2d(array_shape, origin, step) } #[inline] fn for_each(for_each: Array2ForEach, f: impl FnMut(Point2i, Stride)) { let Array2ForEach { iter_extent, iter } = for_each; for_each2(iter, &iter_extent, f); } #[inline] fn for_each_lockstep_unchecked( for_each: LockStepArrayForEach2, f: impl FnMut(Point2i, (Stride, Stride)), ) { let LockStepArrayForEach2 { iter_extent, iter1, iter2, } = for_each; for_each2((iter1, iter2), &iter_extent, f); } } impl ArrayIndexer<[i32; 3]> for [i32; 3] { #[inline] fn stride_from_local_point(s: Point3i, p: Local3i) -> Stride { Stride((p.z() * s.y() * s.x() + p.y() * s.x() + p.x()) as usize) } #[inline] fn make_stride_iter(array_shape: Point3i, origin: Local3i, step: Point3i) -> ArrayStrideIter { ArrayStrideIter::new_3d(array_shape, origin, step) } #[inline] fn for_each(for_each: Array3ForEach, f: impl FnMut(Point3i, Stride)) { let Array3ForEach { iter_extent, iter } = for_each; for_each3(iter, &iter_extent, f); } #[inline] fn for_each_lockstep_unchecked( for_each: LockStepArrayForEach3, f: impl FnMut(Point3i, (Stride, Stride)), ) { let LockStepArrayForEach3 { iter_extent, iter1, iter2, } = for_each; for_each3((iter1, iter2), &iter_extent, f) } } /// When a lattice map implements `IndexedArray`, that means there is some underlying array with the location and shape dictated /// by the extent. /// /// For the sake of generic impls, if the same map also implements `Get*<Stride>`, it must use the same data layout as `Array`. pub trait IndexedArray<N> { type Indexer: ArrayIndexer<N>; fn extent(&self) -> &ExtentN<N>; #[inline] fn stride_from_local_point(&self, p: Local<N>) -> Stride where PointN<N>: Copy, { Self::Indexer::stride_from_local_point(self.extent().shape, p) } #[inline] fn strides_from_local_points(&self, points: &[Local<N>], strides: &mut [Stride]) where PointN<N>: Copy, { Self::Indexer::strides_from_local_points(self.extent().shape, points, strides) } }
29.540984
128
0.617092
26be8e93357e94cc54bd37a3ae06a002bbfe554f
18,675
//! TCP connection stream for local server with remote (proxy server or remote target) use std::{ fmt::{self, Display, Formatter}, io::{self, Error}, net::SocketAddr, pin::Pin, task::{self, Poll}, time::Duration, }; use bytes::{Buf, BufMut, BytesMut}; use futures::ready; use log::{debug, error, trace}; use pin_project::pin_project; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf, ReadHalf, WriteHalf}; use crate::{ config::{ConfigType, ServerAddr, ServerConfig}, context::{Context, SharedContext}, relay::{socks5::Address, sys::tcp_stream_connect, utils::try_timeout}, }; use super::{connection::Connection, CryptoStream, STcpStream}; enum ProxiedConnectState { Connected(Address), Handshaking { buf: BytesMut }, Established, } #[pin_project] struct ProxiedConnection { #[pin] stream: CryptoStream<STcpStream>, state: ProxiedConnectState, } impl ProxiedConnection { fn connected(stream: CryptoStream<STcpStream>, addr: Address) -> ProxiedConnection { ProxiedConnection { stream, state: ProxiedConnectState::Connected(addr), } } fn local_addr(&self) -> io::Result<SocketAddr> { self.stream.get_ref().get_ref().local_addr() } } impl AsyncRead for ProxiedConnection { fn poll_read(self: Pin<&mut Self>, cx: &mut task::Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> { self.project().stream.poll_read(cx, buf) } } impl AsyncWrite for ProxiedConnection { fn poll_write(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, data: &[u8]) -> Poll<io::Result<usize>> { loop { let this = self.as_mut().project(); match this.state { ProxiedConnectState::Connected(ref addr) => { assert_ne!(data.len(), 0); // Send relay address to remote // // NOTE: `Address` handshake packets are very small in most cases, // so // 1. it will be sent with the IV/Nonce data (implemented inside `CryptoStream`). // 2. concatenating target's Address with the first data buffer (#232) // // For lower latency, first packet should be sent back quickly, // so TCP_NODELAY should be kept enabled until the first data packet is received. // A new buffer must be allocated // CryptoStream will encrypt all data into one packet // // Vectored IO is not applicable here. let addr_len = addr.serialized_len(); let mut buf = BytesMut::with_capacity(addr_len + data.len()); addr.write_to_buf(&mut buf); buf.put_slice(data); trace!( "sending handshake address {} ({} bytes) with data {} bytes, totally {} bytes", addr, addr_len, data.len(), buf.remaining() ); // Fast path // // For CryptoStream (Stream and AEAD), poll_write will return Ready(..) until all data have been sent out match this.stream.poll_write(cx, buf.bytes()) { Poll::Ready(Err(err)) => return Poll::Ready(Err(err)), Poll::Ready(Ok(n)) => { buf.advance(n); if buf.remaining() < data.len() { // Ok, written some data with Address let written_len = data.len() - buf.remaining(); trace!( "sent handshake address {} ({} bytes) with {} bytes of data, data len {} bytes, totally {} bytes", addr, addr_len, written_len, data.len(), n, ); self.state = ProxiedConnectState::Established; return Poll::Ready(Ok(written_len)); } else { trace!( "sending handshake address {} ({} bytes) partially {} bytes, data len {} bytes", addr, addr_len, n, data.len() ); } // FALLTHROUGH // Handshaking branch will try to poll_write again self.state = ProxiedConnectState::Handshaking { buf }; } Poll::Pending => { // poll_write is not ready, let Handshaking branch try again later self.state = ProxiedConnectState::Handshaking { buf }; return Poll::Pending; } } } ProxiedConnectState::Handshaking { ref mut buf } => { // Try to write at least addr_len size let n = ready!(this.stream.poll_write(cx, buf.bytes()))?; buf.advance(n); if buf.remaining() < data.len() { // Ok, written some data with Address let written_len = data.len() - buf.remaining(); trace!( "sent handshake address with {} bytes of data, data len {} bytes, totally {} bytes", written_len, data.len(), n, ); self.state = ProxiedConnectState::Established; return Poll::Ready(Ok(written_len)); } } ProxiedConnectState::Established => { break; } } } self.project().stream.poll_write(cx, data) } fn poll_flush(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> { self.project().stream.poll_flush(cx) } fn poll_shutdown(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> { self.project().stream.poll_shutdown(cx) } } #[pin_project(project = ProxyConnectionProj)] enum ProxyConnection { Direct(#[pin] STcpStream), Proxied(#[pin] ProxiedConnection), } impl ProxyConnection { /// Check if the underlying connection is proxied fn is_proxied(&self) -> bool { matches!(*self, ProxyConnection::Proxied { .. }) } fn local_addr(&self) -> io::Result<SocketAddr> { match *self { ProxyConnection::Direct(ref stream) => stream.get_ref().local_addr(), ProxyConnection::Proxied(ref stream) => stream.local_addr(), } } } macro_rules! forward_call { ($self:expr, $method:ident $(, $param:expr)*) => { match $self.as_mut().project() { ProxyConnectionProj::Direct(stream) => stream.$method($($param),*), ProxyConnectionProj::Proxied(stream) => stream.$method($($param),*), } }; } impl AsyncRead for ProxyConnection { fn poll_read(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> { forward_call!(self, poll_read, cx, buf) } } impl AsyncWrite for ProxyConnection { fn poll_write(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> { // let p = forward_call!(self, poll_write, cx, buf); forward_call!(self, poll_write, cx, buf) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> { forward_call!(self, poll_flush, cx) } fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> { forward_call!(self, poll_shutdown, cx) } } #[derive(Debug)] pub struct ProxyStreamError { inner: Error, bypassed: bool, } impl ProxyStreamError { fn new(inner: Error, bypassed: bool) -> ProxyStreamError { ProxyStreamError { inner, bypassed } } /// Check if it is proxied pub fn is_proxied(&self) -> bool { self.bypassed } /// Into internal `std::io::Error` pub fn into_inner(self) -> Error { self.inner } } impl From<ProxyStreamError> for Error { fn from(err: ProxyStreamError) -> Error { err.inner } } impl Display for ProxyStreamError { fn fmt(&self, f: &mut Formatter) -> fmt::Result { Display::fmt(&self.inner, f) } } /// Stream wrapper for both direct connections and proxied connections #[pin_project] pub struct ProxyStream { #[pin] connection: ProxyConnection, context: SharedContext, } impl ProxyStream { /// Connect to remote by ACL rules pub async fn connect( context: SharedContext, svr_cfg: &ServerConfig, addr: &Address, ) -> Result<ProxyStream, ProxyStreamError> { if context.check_target_bypassed(addr).await { ProxyStream::connect_direct_wrapped(context, addr).await } else { ProxyStream::connect_proxied_wrapped(context, svr_cfg, addr).await } } /// Connect to remote directly (without proxy) /// /// This is used for hosts that matches ACL bypassed rules pub async fn connect_direct(context: SharedContext, addr: &Address) -> io::Result<ProxyStream> { debug!("connect to {} directly (bypassed)", addr); // FIXME: No timeout for direct connections let stream = match *addr { Address::SocketAddress(ref saddr) => tcp_stream_connect(&saddr, context.config()).await?, Address::DomainNameAddress(ref domain, port) => { lookup_then!(context, domain, port, |saddr| { tcp_stream_connect(&saddr, context.config()).await })? .1 } }; Ok(ProxyStream { context, connection: ProxyConnection::Direct(Connection::new(stream, None)), }) } async fn connect_direct_wrapped(context: SharedContext, addr: &Address) -> Result<ProxyStream, ProxyStreamError> { match ProxyStream::connect_direct(context, addr).await { Ok(s) => Ok(s), Err(err) => Err(ProxyStreamError::new(err, true)), } } /// Connect to remote via proxy server /// /// This is used for hosts that matches ACL proxied rules pub async fn connect_proxied( context: SharedContext, svr_cfg: &ServerConfig, addr: &Address, ) -> io::Result<ProxyStream> { debug!( "connect to {} via {} ({}) (proxied)", addr, svr_cfg.addr(), svr_cfg.external_addr() ); let server_stream = connect_proxy_server(&context, svr_cfg).await?; let proxy_stream = CryptoStream::new(context.clone(), server_stream, svr_cfg); Ok(ProxyStream { context, connection: ProxyConnection::Proxied(ProxiedConnection::connected(proxy_stream, addr.clone())), }) } async fn connect_proxied_wrapped( context: SharedContext, svr_cfg: &ServerConfig, addr: &Address, ) -> Result<ProxyStream, ProxyStreamError> { match ProxyStream::connect_proxied(context, svr_cfg, addr).await { Ok(s) => Ok(s), Err(err) => Err(ProxyStreamError::new(err, false)), } } /// Split into reader and writer pub fn split(self) -> (ReadHalf<ProxyStream>, WriteHalf<ProxyStream>) { use tokio::io::split; split(self) } /// Returns the local socket address of this stream socket pub fn local_addr(&self) -> io::Result<SocketAddr> { self.connection.local_addr() } /// Check if the underlying connection is proxied pub fn is_proxied(&self) -> bool { self.connection.is_proxied() } /// Get reference to context pub fn context(&self) -> &Context { &self.context } } impl AsyncRead for ProxyStream { fn poll_read(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> { #[allow(unused_variables)] let before_remain = buf.remaining(); let p = self.as_mut().project().connection.poll_read(cx, buf); // Flow statistic for Android client #[cfg(feature = "local-flow-stat")] { if self.is_proxied() { if let Poll::Ready(Ok(..)) = p { self.context() .local_flow_statistic() .tcp() .incr_rx(before_remain - buf.remaining()); } } } p } } impl AsyncWrite for ProxyStream { fn poll_write(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> { let p = self.as_mut().project().connection.poll_write(cx, buf); // Flow statistic for Android client #[cfg(feature = "local-flow-stat")] { if self.is_proxied() { if let Poll::Ready(Ok(n)) = p { self.context().local_flow_statistic().tcp().incr_tx(n); } } } p } fn poll_flush(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> { self.project().connection.poll_flush(cx) } fn poll_shutdown(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<io::Result<()>> { self.project().connection.poll_shutdown(cx) } } async fn connect_proxy_server_internal( context: &Context, orig_svr_addr: &ServerAddr, svr_addr: &ServerAddr, timeout: Option<Duration>, ) -> io::Result<STcpStream> { match svr_addr { ServerAddr::SocketAddr(ref addr) => { let stream = try_timeout(tcp_stream_connect(&addr, context.config()), timeout).await?; trace!("connected proxy {} ({})", orig_svr_addr, addr); Ok(STcpStream::new(stream, timeout)) } ServerAddr::DomainName(ref domain, port) => { let result = lookup_then!(context, domain.as_str(), *port, |addr| { match try_timeout(tcp_stream_connect(&addr, context.config()), timeout).await { Ok(s) => Ok(STcpStream::new(s, timeout)), Err(e) => { trace!( "failed to connect proxy {} ({}:{} ({})) try another (err: {})", orig_svr_addr, domain, port, addr, e ); Err(e) } } }); match result { Ok((addr, s)) => { trace!("connected proxy {} ({}:{} ({}))", orig_svr_addr, domain, port, addr); Ok(s) } Err(err) => { debug!( "failed to connect proxy {} ({}:{}), {}", orig_svr_addr, domain, port, err ); Err(err) } } } } } /// Connect to proxy server with `ServerConfig` async fn connect_proxy_server(context: &Context, svr_cfg: &ServerConfig) -> io::Result<STcpStream> { let timeout = svr_cfg.timeout(); let svr_addr = match context.config().config_type { ConfigType::Server => svr_cfg.addr(), ConfigType::Socks5Local => svr_cfg.external_addr(), #[cfg(feature = "local-socks4")] ConfigType::Socks4Local => svr_cfg.external_addr(), #[cfg(feature = "local-tunnel")] ConfigType::TunnelLocal => svr_cfg.external_addr(), #[cfg(feature = "local-dns")] ConfigType::DnsLocal => svr_cfg.external_addr(), #[cfg(feature = "local-http")] ConfigType::HttpLocal => svr_cfg.external_addr(), #[cfg(all( feature = "local-http", any(feature = "local-http-native-tls", feature = "local-http-rustls") ))] ConfigType::HttpsLocal => svr_cfg.external_addr(), #[cfg(feature = "local-redir")] ConfigType::RedirLocal => svr_cfg.external_addr(), ConfigType::Manager => unreachable!("ConfigType::Manager shouldn't need to connect to proxy server"), }; // Retry if connect failed // // FIXME: This won't work if server is actually down. // Probably we should retry with another server. // // Also works if plugin is starting const RETRY_TIMES: i32 = 3; let orig_svr_addr = svr_cfg.addr(); trace!( "connecting to proxy {} ({}), timeout: {:?}", orig_svr_addr, svr_addr, timeout ); let mut last_err = None; for retry_time in 0..RETRY_TIMES { match connect_proxy_server_internal(context, orig_svr_addr, svr_addr, timeout).await { Ok(mut s) => { // IMPOSSIBLE, won't fail, but just a guard if let Err(err) = s.set_nodelay(context.config().no_delay) { error!("failed to set TCP_NODELAY on remote socket, error: {:?}", err); } return Ok(s); } Err(err) => { // Connection failure, retry trace!( "failed to connect {}, retried {} times (last err: {})", svr_addr, retry_time, err ); last_err = Some(err); // Yield and let the others' run // // It may take some time for scheduler to resume this coroutine. tokio::task::yield_now().await; } } } let last_err = last_err.unwrap(); debug!( "failed to connect {}, retried {} times, last_err: {}", svr_addr, RETRY_TIMES, last_err ); Err(last_err) }
34.203297
134
0.51427
5668420574b0e2ed13c75e1da08785b97da1eadc
5,870
// Copyright 2015-2021 Swim 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, // 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 super::*; #[test] #[should_panic] fn too_large_read1() { let mut mask = FrameMask::new(); mask.read(64); } #[test] #[should_panic] fn too_large_write1() { let mut mask = FrameMask::new(); mask.write(64); } #[test] #[should_panic] fn too_large_read2() { let mut mask = FrameMask::new(); mask.read(200); } #[test] #[should_panic] fn too_large_write2() { let mut mask = FrameMask::new(); mask.write(200); } #[test] fn read_and_get() { let mut mask = FrameMask::new(); for i in 0..MAX_SIZE { assert!(mask.get(i).is_none()); mask.read(i); assert_eq!(mask.get(i), Some(ReadWrite::Read)); mask.read(i); assert_eq!(mask.get(i), Some(ReadWrite::Read)); } } #[test] fn write_and_get() { let mut mask = FrameMask::new(); for i in 0..MAX_SIZE { assert!(mask.get(i).is_none()); mask.write(i); assert_eq!(mask.get(i), Some(ReadWrite::Write)); mask.write(i); assert_eq!(mask.get(i), Some(ReadWrite::Write)); } } #[test] fn read_after_write_noop() { let mut mask = FrameMask::new(); for i in 0..MAX_SIZE { assert!(mask.get(i).is_none()); mask.write(i); assert_eq!(mask.get(i), Some(ReadWrite::Write)); mask.read(i); assert_eq!(mask.get(i), Some(ReadWrite::Write)); } } #[test] fn write_after_read_stacks() { let mut mask = FrameMask::new(); for i in 0..MAX_SIZE { assert!(mask.get(i).is_none()); mask.read(i); assert_eq!(mask.get(i), Some(ReadWrite::Read)); mask.write(i); assert_eq!(mask.get(i), Some(ReadWrite::ReadWrite)); } } #[test] fn iterate_empty() { let mask = FrameMask::new(); assert!(mask.iter().next().is_none()); } fn single_item_iter(i: usize) { let mut mask = FrameMask::new(); mask.read(i); let contents = mask.iter().collect::<Vec<_>>(); assert_eq!(contents, vec![(i, ReadWrite::Read)]); let mut mask = FrameMask::new(); mask.write(i); let contents = mask.iter().collect::<Vec<_>>(); assert_eq!(contents, vec![(i, ReadWrite::Write)]); let mut mask = FrameMask::new(); mask.read(i); mask.write(i); let contents = mask.iter().collect::<Vec<_>>(); assert_eq!(contents, vec![(i, ReadWrite::ReadWrite)]); } #[test] fn only_first_iter() { single_item_iter(0); } #[test] fn only_last_iter() { single_item_iter(MAX_SIZE - 1); } #[test] fn only_internal_iter() { single_item_iter(34); } #[test] fn initial_block_iter() { let mut mask = FrameMask::new(); mask.read(0); mask.read(1); mask.write(1); mask.write(2); let contents = mask.iter().collect::<Vec<_>>(); assert_eq!( contents, vec![ (0, ReadWrite::Read), (1, ReadWrite::ReadWrite), (2, ReadWrite::Write) ] ); } #[test] fn end_block_iter() { let mut mask = FrameMask::new(); mask.write(MAX_SIZE - 3); mask.read(MAX_SIZE - 2); mask.write(MAX_SIZE - 2); mask.read(MAX_SIZE - 1); let contents = mask.iter().collect::<Vec<_>>(); assert_eq!( contents, vec![ (MAX_SIZE - 3, ReadWrite::Write), (MAX_SIZE - 2, ReadWrite::ReadWrite), (MAX_SIZE - 1, ReadWrite::Read) ] ); } #[test] fn internal_block_iter() { let mut mask = FrameMask::new(); mask.write(12); mask.write(13); mask.write(14); let contents = mask.iter().collect::<Vec<_>>(); assert_eq!( contents, vec![ (12, ReadWrite::Write), (13, ReadWrite::Write), (14, ReadWrite::Write) ] ); } #[test] fn two_blocks_iter() { let mut mask = FrameMask::new(); mask.read(12); mask.write(13); mask.read(14); mask.write(14); mask.write(16); mask.read(17); let contents = mask.iter().collect::<Vec<_>>(); assert_eq!( contents, vec![ (12, ReadWrite::Read), (13, ReadWrite::Write), (14, ReadWrite::ReadWrite), (16, ReadWrite::Write), (17, ReadWrite::Read) ] ); } #[test] fn all_iter() { let mut mask = FrameMask::new(); for i in 0..MAX_SIZE { let m = (i % 7) % 3; match m { 0 => { mask.read(i); } 1 => { mask.write(i); } _ => { mask.read(i); mask.write(i); } } } let contents = mask.iter().collect::<Vec<_>>(); assert_eq!(contents.len(), MAX_SIZE); let mut prev: Option<usize> = None; for (i, rw) in contents.into_iter() { match &mut prev { Some(p) => { assert_eq!(i, *p + 1); *p += 1; } _ => { assert_eq!(i, 0); prev = Some(0); } } let m = (i % 7) % 3; match m { 0 => { assert_eq!(rw, ReadWrite::Read); } 1 => { assert_eq!(rw, ReadWrite::Write); } _ => { assert_eq!(rw, ReadWrite::ReadWrite); } } } }
23.110236
75
0.528279
1cded509c3ef5c09787049e1539faaf960ee5411
6,432
// Copyright (c) 2017-present PyO3 Project and Contributors use crate::defs; use crate::func::impl_method_proto; use crate::method::FnSpec; use crate::pymethod; use proc_macro2::{Span, TokenStream}; use quote::quote; use quote::ToTokens; use std::collections::HashSet; pub fn build_py_proto(ast: &mut syn::ItemImpl) -> syn::Result<TokenStream> { if let Some((_, ref mut path, _)) = ast.trait_ { let proto = if let Some(ref mut segment) = path.segments.last() { match segment.ident.to_string().as_str() { "PyObjectProtocol" => &defs::OBJECT, "PyAsyncProtocol" => &defs::ASYNC, "PyMappingProtocol" => &defs::MAPPING, "PyIterProtocol" => &defs::ITER, "PyContextProtocol" => &defs::CONTEXT, "PySequenceProtocol" => &defs::SEQ, "PyNumberProtocol" => &defs::NUM, "PyDescrProtocol" => &defs::DESCR, "PyBufferProtocol" => &defs::BUFFER, "PyGCProtocol" => &defs::GC, _ => { return Err(syn::Error::new_spanned( path, "#[pyproto] can not be used with this block", )); } } } else { return Err(syn::Error::new_spanned( path, "#[pyproto] can only be used with protocol trait implementations", )); }; let tokens = impl_proto_impl(&ast.self_ty, &mut ast.items, proto)?; // attach lifetime let mut seg = path.segments.pop().unwrap().into_value(); seg.arguments = syn::PathArguments::AngleBracketed(syn::parse_quote! {<'p>}); path.segments.push(seg); ast.generics.params = syn::parse_quote! {'p}; Ok(tokens) } else { Err(syn::Error::new_spanned( ast, "#[pyproto] can only be used with protocol trait implementations", )) } } fn impl_proto_impl( ty: &syn::Type, impls: &mut Vec<syn::ImplItem>, proto: &defs::Proto, ) -> syn::Result<TokenStream> { let mut trait_impls = TokenStream::new(); let mut py_methods = Vec::new(); let mut method_names = HashSet::new(); for iimpl in impls.iter_mut() { if let syn::ImplItem::Method(ref mut met) = iimpl { // impl Py~Protocol<'p> { type = ... } if let Some(m) = proto.get_proto(&met.sig.ident) { impl_method_proto(ty, &mut met.sig, m).to_tokens(&mut trait_impls); // Insert the method to the HashSet method_names.insert(met.sig.ident.to_string()); } // Add non-slot methods to inventory like `#[pymethods]` if let Some(m) = proto.get_method(&met.sig.ident) { let name = &met.sig.ident; let fn_spec = FnSpec::parse(&met.sig, &mut met.attrs, false)?; let method = pymethod::impl_proto_wrap(ty, &fn_spec); let coexist = if m.can_coexist { // We need METH_COEXIST here to prevent __add__ from overriding __radd__ quote!(pyo3::ffi::METH_COEXIST) } else { quote!(0) }; // TODO(kngwyu): Set ml_doc py_methods.push(quote! { pyo3::class::PyMethodDefType::Method({ #method pyo3::class::PyMethodDef { ml_name: stringify!(#name), ml_meth: pyo3::class::PyMethodType::PyCFunctionWithKeywords(__wrap), ml_flags: pyo3::ffi::METH_VARARGS | pyo3::ffi::METH_KEYWORDS | #coexist, ml_doc: "" } }) }); } } } let inventory_submission = inventory_submission(py_methods, ty); let slot_initialization = slot_initialization(method_names, ty, proto)?; Ok(quote! { #trait_impls #inventory_submission #slot_initialization }) } fn inventory_submission(py_methods: Vec<TokenStream>, ty: &syn::Type) -> TokenStream { if py_methods.is_empty() { return quote! {}; } quote! { pyo3::inventory::submit! { #![crate = pyo3] { type Inventory = <#ty as pyo3::class::methods::HasMethodsInventory>::Methods; <Inventory as pyo3::class::methods::PyMethodsInventory>::new(&[#(#py_methods),*]) } } } } fn slot_initialization( method_names: HashSet<String>, ty: &syn::Type, proto: &defs::Proto, ) -> syn::Result<TokenStream> { // Some setters cannot coexist. // E.g., if we have `__add__`, we need to skip `set_radd`. let mut skipped_setters = Vec::new(); // Collect initializers let mut initializers: Vec<TokenStream> = vec![]; 'outer_loop: for m in proto.slot_setters { if skipped_setters.contains(&m.set_function) { continue; } for name in m.proto_names { // If this `#[pyproto]` block doesn't provide all required methods, // let's skip implementing this method. if !method_names.contains(*name) { continue 'outer_loop; } } skipped_setters.extend_from_slice(m.skipped_setters); // Add slot methods to PyProtoRegistry let set = syn::Ident::new(m.set_function, Span::call_site()); initializers.push(quote! { table.#set::<#ty>(); }); } if initializers.is_empty() { return Ok(quote! {}); } let table: syn::Path = syn::parse_str(proto.slot_table)?; let set = syn::Ident::new(proto.set_slot_table, Span::call_site()); let ty_hash = typename_hash(ty); let init = syn::Ident::new( &format!("__init_{}_{}", proto.name, ty_hash), Span::call_site(), ); Ok(quote! { #[pyo3::ctor::ctor] fn #init() { let mut table = #table::default(); #(#initializers)* <#ty as pyo3::class::proto_methods::HasProtoRegistry>::registry().#set(table); } }) } fn typename_hash(ty: &syn::Type) -> u64 { use std::hash::{Hash, Hasher}; let mut hasher = std::collections::hash_map::DefaultHasher::new(); ty.hash(&mut hasher); hasher.finish() }
36.754286
100
0.539335
893a020bbcba4685eca12eb2e2c1e43c0265ac69
2,757
// Copyright (c) 2019 Parity Technologies (UK) Ltd. // // 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. // Example to be used with the autobahn test suite, a fully automated test // suite to verify client and server implementations of websocket // implementation. // // Once started, the tests can be executed with: wstest -m fuzzingclient // // See https://github.com/crossbario/autobahn-testsuite for details. use futures::io::{BufReader, BufWriter}; use soketto::{connection, handshake, BoxedError}; use tokio::net::{TcpListener, TcpStream}; use tokio_stream::{wrappers::TcpListenerStream, StreamExt}; use tokio_util::compat::{Compat, TokioAsyncReadCompatExt}; #[tokio::main] async fn main() -> Result<(), BoxedError> { let listener = TcpListener::bind("127.0.0.1:9001").await?; let mut incoming = TcpListenerStream::new(listener); while let Some(socket) = incoming.next().await { let mut server = new_server(socket?); let key = { let req = server.receive_request().await?; req.key() }; let accept = handshake::server::Response::Accept { key, protocol: None }; server.send_response(&accept).await?; let (mut sender, mut receiver) = server.into_builder().finish(); let mut message = Vec::new(); loop { message.clear(); match receiver.receive_data(&mut message).await { Ok(soketto::Data::Binary(n)) => { assert_eq!(n, message.len()); sender.send_binary_mut(&mut message).await?; sender.flush().await? } Ok(soketto::Data::Text(n)) => { assert_eq!(n, message.len()); if let Ok(txt) = std::str::from_utf8(&message) { sender.send_text(txt).await?; sender.flush().await? } else { break; } } Err(connection::Error::Closed) => break, Err(e) => { log::error!("connection error: {}", e); break; } } } } Ok(()) } #[cfg(not(feature = "deflate"))] fn new_server<'a>(socket: TcpStream) -> handshake::Server<'a, BufReader<BufWriter<Compat<TcpStream>>>> { handshake::Server::new(BufReader::new(BufWriter::new(socket.compat()))) } #[cfg(feature = "deflate")] fn new_server<'a>(socket: TcpStream) -> handshake::Server<'a, BufReader<BufWriter<Compat<TcpStream>>>> { let socket = BufReader::with_capacity(8 * 1024, BufWriter::with_capacity(16 * 1024, socket.compat())); let mut server = handshake::Server::new(socket); let deflate = soketto::extension::deflate::Deflate::new(soketto::Mode::Server); server.add_extension(Box::new(deflate)); server }
35.805195
104
0.682989
9c857f91953de6639901258f050c072136b32138
8,478
// Copyright 2020 Tran Tuan Linh // // 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 libc::{c_int, c_void}; use crate::{ffi, ffi_util::from_cstr, Cache, Error, DB}; #[derive(Debug, Copy, Clone, PartialEq)] #[repr(i32)] pub enum PerfStatsLevel { /// Unknown settings Uninitialized = 0, /// Disable perf stats Disable, /// Enables only count stats EnableCount, /// Count stats and enable time stats except for mutexes EnableTimeExceptForMutex, /// Other than time, also measure CPU time counters. Still don't measure /// time (neither wall time nor CPU time) for mutexes EnableTimeAndCPUTimeExceptForMutex, /// Enables count and time stats EnableTime, /// N.B must always be the last value! OutOfBound, } #[derive(Debug, Copy, Clone, PartialEq)] #[non_exhaustive] #[repr(i32)] pub enum PerfMetric { UserKeyComparisonCount = 0, BlockCacheHitCount = 1, BlockReadCount = 2, BlockReadByte = 3, BlockReadTime = 4, BlockChecksumTime = 5, BlockDecompressTime = 6, GetReadBytes = 7, MultigetReadBytes = 8, IterReadBytes = 9, InternalKeySkippedCount = 10, InternalDeleteSkippedCount = 11, InternalRecentSkippedCount = 12, InternalMergeCount = 13, GetSnapshotTime = 14, GetFromMemtableTime = 15, GetFromMemtableCount = 16, GetPostProcessTime = 17, GetFromOutputFilesTime = 18, SeekOnMemtableTime = 19, SeekOnMemtableCount = 20, NextOnMemtableCount = 21, PrevOnMemtableCount = 22, SeekChildSeekTime = 23, SeekChildSeekCount = 24, SeekMinHeapTime = 25, SeekMaxHeapTime = 26, SeekInternalSeekTime = 27, FindNextUserEntryTime = 28, WriteWalTime = 29, WriteMemtableTime = 30, WriteDelayTime = 31, WritePreAndPostProcessTime = 32, DbMutexLockNanos = 33, DbConditionWaitNanos = 34, MergeOperatorTimeNanos = 35, ReadIndexBlockNanos = 36, ReadFilterBlockNanos = 37, NewTableBlockIterNanos = 38, NewTableIteratorNanos = 39, BlockSeekNanos = 40, FindTableNanos = 41, BloomMemtableHitCount = 42, BloomMemtableMissCount = 43, BloomSstHitCount = 44, BloomSstMissCount = 45, KeyLockWaitTime = 46, KeyLockWaitCount = 47, EnvNewSequentialFileNanos = 48, EnvNewRandomAccessFileNanos = 49, EnvNewWritableFileNanos = 50, EnvReuseWritableFileNanos = 51, EnvNewRandomRwFileNanos = 52, EnvNewDirectoryNanos = 53, EnvFileExistsNanos = 54, EnvGetChildrenNanos = 55, EnvGetChildrenFileAttributesNanos = 56, EnvDeleteFileNanos = 57, EnvCreateDirNanos = 58, EnvCreateDirIfMissingNanos = 59, EnvDeleteDirNanos = 60, EnvGetFileSizeNanos = 61, EnvGetFileModificationTimeNanos = 62, EnvRenameFileNanos = 63, EnvLinkFileNanos = 64, EnvLockFileNanos = 65, EnvUnlockFileNanos = 66, EnvNewLoggerNanos = 67, TotalMetricCount = 68, } /// Sets the perf stats level for current thread. pub fn set_perf_stats(lvl: PerfStatsLevel) { unsafe { ffi::rocksdb_set_perf_level(lvl as c_int); } } /// Thread local context for gathering performance counter efficiently /// and transparently. pub struct PerfContext { pub(crate) inner: *mut ffi::rocksdb_perfcontext_t, } impl Default for PerfContext { fn default() -> Self { let ctx = unsafe { ffi::rocksdb_perfcontext_create() }; assert!(!ctx.is_null(), "Could not create Perf Context"); Self { inner: ctx } } } impl Drop for PerfContext { fn drop(&mut self) { unsafe { ffi::rocksdb_perfcontext_destroy(self.inner); } } } impl PerfContext { /// Reset context pub fn reset(&mut self) { unsafe { ffi::rocksdb_perfcontext_reset(self.inner); } } /// Get the report on perf pub fn report(&self, exclude_zero_counters: bool) -> String { unsafe { let ptr = ffi::rocksdb_perfcontext_report(self.inner, u8::from(exclude_zero_counters)); let report = from_cstr(ptr); libc::free(ptr as *mut c_void); report } } /// Returns value of a metric pub fn metric(&self, id: PerfMetric) -> u64 { unsafe { ffi::rocksdb_perfcontext_metric(self.inner, id as c_int) } } } /// Memory usage stats pub struct MemoryUsageStats { /// Approximate memory usage of all the mem-tables pub mem_table_total: u64, /// Approximate memory usage of un-flushed mem-tables pub mem_table_unflushed: u64, /// Approximate memory usage of all the table readers pub mem_table_readers_total: u64, /// Approximate memory usage by cache pub cache_total: u64, } /// Wrap over memory_usage_t. Hold current memory usage of the specified DB instances and caches struct MemoryUsage { inner: *mut ffi::rocksdb_memory_usage_t, } impl Drop for MemoryUsage { fn drop(&mut self) { unsafe { ffi::rocksdb_approximate_memory_usage_destroy(self.inner); } } } impl MemoryUsage { /// Approximate memory usage of all the mem-tables fn approximate_mem_table_total(&self) -> u64 { unsafe { ffi::rocksdb_approximate_memory_usage_get_mem_table_total(self.inner) } } /// Approximate memory usage of un-flushed mem-tables fn approximate_mem_table_unflushed(&self) -> u64 { unsafe { ffi::rocksdb_approximate_memory_usage_get_mem_table_unflushed(self.inner) } } /// Approximate memory usage of all the table readers fn approximate_mem_table_readers_total(&self) -> u64 { unsafe { ffi::rocksdb_approximate_memory_usage_get_mem_table_readers_total(self.inner) } } /// Approximate memory usage by cache fn approximate_cache_total(&self) -> u64 { unsafe { ffi::rocksdb_approximate_memory_usage_get_cache_total(self.inner) } } } /// Builder for MemoryUsage struct MemoryUsageBuilder { inner: *mut ffi::rocksdb_memory_consumers_t, } impl Drop for MemoryUsageBuilder { fn drop(&mut self) { unsafe { ffi::rocksdb_memory_consumers_destroy(self.inner); } } } impl MemoryUsageBuilder { /// Create new instance fn new() -> Result<Self, Error> { let mc = unsafe { ffi::rocksdb_memory_consumers_create() }; if mc.is_null() { Err(Error::new( "Could not create MemoryUsage builder".to_owned(), )) } else { Ok(Self { inner: mc }) } } /// Add a DB instance to collect memory usage from it and add up in total stats fn add_db(&mut self, db: &DB) { unsafe { ffi::rocksdb_memory_consumers_add_db(self.inner, db.inner); } } /// Add a cache to collect memory usage from it and add up in total stats fn add_cache(&mut self, cache: &Cache) { unsafe { ffi::rocksdb_memory_consumers_add_cache(self.inner, cache.0.inner); } } /// Build up MemoryUsage fn build(&self) -> Result<MemoryUsage, Error> { unsafe { let mu = ffi_try!(ffi::rocksdb_approximate_memory_usage_create(self.inner)); Ok(MemoryUsage { inner: mu }) } } } /// Get memory usage stats from DB instances and Cache instances pub fn get_memory_usage_stats( dbs: Option<&[&DB]>, caches: Option<&[&Cache]>, ) -> Result<MemoryUsageStats, Error> { let mut builder = MemoryUsageBuilder::new()?; if let Some(dbs_) = dbs { dbs_.iter().for_each(|db| builder.add_db(db)); } if let Some(caches_) = caches { caches_.iter().for_each(|cache| builder.add_cache(cache)); } let mu = builder.build()?; Ok(MemoryUsageStats { mem_table_total: mu.approximate_mem_table_total(), mem_table_unflushed: mu.approximate_mem_table_unflushed(), mem_table_readers_total: mu.approximate_mem_table_readers_total(), cache_total: mu.approximate_cache_total(), }) }
29.747368
99
0.667138
dee70b6f576116c3e45c9f0f54b969b3e9b2e6b8
366
extern crate proc_macro; #[proc_macro_derive(Serialize, attributes(serde))] pub fn serialize(_items: proc_macro::TokenStream) -> proc_macro::TokenStream { proc_macro::TokenStream::new() } #[proc_macro_derive(Deserialize, attributes(serde))] pub fn deserialize(_items: proc_macro::TokenStream) -> proc_macro::TokenStream { proc_macro::TokenStream::new() }
28.153846
80
0.762295
753fc815c474be6120ba250fef891c659ba7f79f
855
use crate::objc::NSObject; objc_subclass! { /// A singleton object used to represent null values in collection objects that /// don’t allow `nil` values. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnull). pub class NSNull: NSObject<'static>; } impl Default for &NSNull { #[inline] fn default() -> Self { NSNull::null() } } impl NSNull { /// Returns the singleton instance. /// /// See [documentation](https://developer.apple.com/documentation/foundation/nsnull). #[inline] #[doc(alias = "kCFNull")] pub fn null() -> &'static Self { extern "C" { // `NSNull` is toll-free bridged with `CFNullRef` whose only // instance is this. static kCFNull: &'static NSNull; } unsafe { kCFNull } } }
25.909091
89
0.592982
67a4c27b27e176f92e66b17a98d029355cb3f81d
2,538
pub mod segment_cwd; pub mod segment_host; pub mod segment_jobs; pub mod segment_nix; pub mod segment_perms; pub mod segment_ps; pub mod segment_root; pub mod segment_ssh; pub mod segment_time; pub mod segment_user; pub mod segment_virtualenv; pub use self::segment_cwd::*; pub use self::segment_host::*; pub use self::segment_jobs::*; pub use self::segment_nix::*; pub use self::segment_perms::*; pub use self::segment_ps::*; pub use self::segment_root::*; pub use self::segment_ssh::*; pub use self::segment_time::*; pub use self::segment_user::*; pub use self::segment_virtualenv::*; #[cfg(feature = "git2")] pub mod segment_git; #[cfg(feature = "git2")] pub use self::segment_git::*; use Shell; use format::*; use std::borrow::Cow; use theme::Theme; pub struct Segment { bg: u8, fg: u8, before: &'static str, after: &'static str, conditional: bool, escaped: bool, text: Cow<'static, str> } impl Segment { pub fn new<S>(bg: u8, fg: u8, text: S) -> Self where S: Into<Cow<'static, str>> { Segment { bg, fg, before: "", after: "", conditional: false, escaped: false, text: text.into() } } pub fn dont_escape(mut self) -> Self { self.escaped = true; self } pub fn with_before(mut self, before: &'static str) -> Self { self.before = before; self } pub fn with_after(mut self, after: &'static str) -> Self { self.after = after; self } pub fn into_conditional(mut self) -> Self { self.conditional = true; self } pub fn is_conditional(&self) -> bool { self.conditional } pub fn escape(&mut self, shell: Shell) { if self.escaped { return; } escape(shell, self.text.to_mut()); self.escaped = true; } pub fn print(&self, next: Option<&Segment>, shell: Shell, theme: &Theme) { print!("{}{}{} {} ", self.before, Fg(shell, self.fg), Bg(shell, self.bg), self.text); match next { Some(next) if next.is_conditional() => {}, Some(next) if next.bg == self.bg => print!("{}", Fg(shell, theme.separator_fg)), Some(next) => print!("{}{}", Fg(shell, self.bg), Bg(shell, next.bg)), // Last tile resets colors None => print!("{}{}{}",Fg(shell, self.bg), Reset(shell, false), Reset(shell, true)) } print!("{}", self.after); } }
25.636364
103
0.564618
ab1948a41fc40ed7c2c3acc45c42dd672e033c31
9,922
/* * Copyright 2018-2021 TON Labs LTD. * * Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use * this file except in compliance with the License. * * 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 TON DEV software governing permissions and * limitations under the License. * */ use crate::client::{FetchResult, WebSocket}; use crate::error::ClientResult; use crate::ClientContext; use futures::SinkExt; use serde_json::Value; use std::collections::HashMap; #[derive(Debug, Clone)] pub(crate) struct FetchMock { pub id: usize, pub url: String, pub delay: Option<u64>, pub result: ClientResult<FetchResult>, } impl FetchMock { pub async fn get_result( self, env: &crate::client::ClientEnv, url: &str, ) -> ClientResult<FetchResult> { if let Some(delay) = self.delay { let _ = env.set_timer(delay).await; } let mut result = self.result; let id = if self.id != 0 { format!(" {}", self.id) } else { String::default() }; if let Ok(result) = &mut result { result.url = url.split("?").next().unwrap_or("").to_string(); } let (text, find, replace_with) = match &result { Ok(ok) => (format!("{:?}", ok), "FetchResult", "✅"), Err(err) => (format!("{:?}", err), "ClientError", "❌"), }; println!("{}", text.replace(find, &format!("{}{}", replace_with, id))); result } } #[derive(Debug, Clone)] pub(crate) struct MessageMock { pub url: String, pub delay: Option<u64>, pub message: String, } pub(crate) struct NetworkMock { pub fetches: Option<Vec<FetchMock>>, pub messages: Option<Vec<MessageMock>>, } fn same_endpoints(url1: &str, url2: &str) -> bool { fn reduce_url(url: &str) -> String { url.split("://").last().unwrap_or(url).to_lowercase() } let a = reduce_url(url1); let b = reduce_url(url2); return a.starts_with(&b) || b.starts_with(&a); } impl NetworkMock { pub(crate) fn build() -> NetworkMockBuilder { NetworkMockBuilder::new() } pub(crate) fn new() -> Self { Self { fetches: None, messages: None, } } fn extract_messages(&mut self, url: &str) -> Vec<MessageMock> { let mut result = Vec::new(); if let Some(messages) = &mut self.messages { let mut i = 0; while i < messages.len() { if same_endpoints(url, &messages[i].url) { result.push(messages.remove(i)); } else { i += 1; } } } result } pub async fn websocket_connect( &mut self, async_runtime_handle: &tokio::runtime::Handle, url: &str, ) -> Option<WebSocket> { let mut messages = self.extract_messages(url); if messages.len() > 0 { let (client_sender, server_receiver) = futures::channel::mpsc::channel::<String>(10); let (mut server_sender, client_receiver) = futures::channel::mpsc::channel::<ClientResult<String>>(10); async_runtime_handle.enter(move || { tokio::spawn(Box::pin(async move { let _ = server_receiver; while !messages.is_empty() { let message = messages.remove(0); println!("Send {}", message.message); if let Some(delay) = message.delay { tokio::time::delay_for(tokio::time::Duration::from_millis(delay)).await; } let _ = server_sender.send(Ok(message.message)).await; } })) }); Some(WebSocket { receiver: Box::pin(client_receiver), sender: Box::pin( client_sender .sink_map_err(|err| crate::client::Error::websocket_send_error(err)), ), }) } else { None } } pub(crate) fn dequeue_fetch(&mut self, url: &str, body: &Option<String>) -> Option<FetchMock> { if let Some(queue) = &mut self.fetches { let next_index = queue.iter().position(|x| same_endpoints(&x.url, url)); let fetch = match next_index { Some(index) => queue.remove(index), None => FetchMock { id: 0, delay: None, url: url.to_string(), result: Err(crate::client::Error::http_request_send_error( "Test fetch queue is empty", )), }, }; let mut log = "❔".to_string(); if fetch.id != 0 { log.push_str(&format!(" {}", fetch.id)); } if let Some(delay) = fetch.delay { log.push_str(&format!(" {} ms ", delay)); } log.push_str(" "); log.push_str(url); if let Some(body) = &body { log.push_str(&format!("\n ⤷ {}", body)); } println!("{}", log); Some(fetch) } else { None } } #[cfg(not(feature = "wasm"))] #[cfg(test)] pub async fn get_len(client: &ClientContext) -> usize { client .env .network_mock .read() .await .fetches .as_ref() .map(|x| x.len()) .unwrap_or(0) } } pub(crate) struct NetworkMockBuilder { last_id: usize, url: String, repeat: Option<usize>, delay: Option<u64>, fetches: Vec<FetchMock>, messages: Vec<MessageMock>, } impl NetworkMockBuilder { fn new() -> Self { Self { last_id: 0, url: String::default(), repeat: None, delay: None, fetches: Vec::new(), messages: Vec::new(), } } pub fn url(&mut self, url: &str) -> &mut Self { self.url = url.to_string(); self } pub fn delay(&mut self, delay: u64) -> &mut Self { self.delay = Some(delay); self } pub fn repeat(&mut self, repeat: usize) -> &mut Self { self.repeat = Some(repeat); self } fn push_fetch(&mut self, result: ClientResult<FetchResult>) -> &mut Self { let repeat = self.repeat.take().unwrap_or(1); let delay = self.delay.take(); for _ in 0..repeat { self.last_id += 1; self.fetches.push(FetchMock { id: self.last_id, url: self.url.clone(), delay, result: result.clone(), }); } self } pub fn ws(&mut self, message: &Value) -> &mut Self { let repeat = self.repeat.take().unwrap_or(1); let delay = self.delay.take(); for _ in 0..repeat { self.messages.push(MessageMock { url: self.url.clone(), delay, message: message.to_string(), }); } self } pub fn ws_ack(&mut self) -> &mut Self { self.ws(&json!({"type":"connection_ack"})) } pub fn ws_ka(&mut self) -> &mut Self { self.ws(&json!({"type":"ka"})) } pub fn ok(&mut self, body: &str) -> &mut Self { self.push_fetch(Ok(FetchResult { url: self.url.clone(), status: 200, body: body.to_string(), headers: HashMap::new(), remote_address: None, })) } pub fn status(&mut self, status: u16, body: &str) -> &mut Self { self.push_fetch(Ok(FetchResult { url: self.url.clone(), status, body: body.to_string(), headers: HashMap::new(), remote_address: None, })) } pub fn network_err(&mut self) -> &mut Self { self.push_fetch(Err(crate::client::Error::http_request_send_error( "Network error", ))) } #[cfg(not(feature = "wasm"))] #[cfg(test)] pub async fn reset_client(&self, client: &ClientContext) { client .get_server_link() .unwrap() .invalidate_querying_endpoint() .await; let mut network_mock = client.env.network_mock.write().await; network_mock.fetches = Some(self.fetches.clone()); network_mock.messages = Some(self.messages.clone()); } pub fn schema(&mut self, time: u64) -> &mut Self { self.ok(&json!({ "data": { "info": { "version": "0.39.0", "time": time, } } }) .to_string()) } pub fn metrics(&mut self, time: u64, latency: u64) -> &mut Self { self.ok(&json!({ "data": { "info": { "version": "0.39.0", "time": time, "latency": latency, } } }) .to_string()) } pub fn election(&mut self, time: u64, latency: u64) -> &mut Self { self.schema(time).metrics(time, latency) } pub fn election_loose(&mut self, time: u64) -> &mut Self { self.schema(time) } pub fn blocks(&mut self, id: &str) -> &mut Self { self.ok(&json!({ "data": { "blocks": [{"id": id.to_string()}], } }) .to_string()) } }
29.096774
100
0.489317
db43f7a425ce66558658b0889f31da6b82703bc3
9,309
// Not in interpret to make sure we do not use private implementation details use std::convert::TryFrom; use rustc_hir::Mutability; use rustc_middle::mir; use rustc_middle::mir::interpret::{EvalToValTreeResult, GlobalId}; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::{source_map::DUMMY_SP, symbol::Symbol}; use crate::interpret::{ intern_const_alloc_recursive, ConstValue, InternKind, InterpCx, InterpResult, MemPlaceMeta, Scalar, }; mod error; mod eval_queries; mod fn_queries; mod machine; mod valtrees; pub use error::*; pub use eval_queries::*; pub use fn_queries::*; pub use machine::*; pub(crate) use valtrees::{const_to_valtree_inner, valtree_to_const_value}; pub(crate) fn const_caller_location( tcx: TyCtxt<'_>, (file, line, col): (Symbol, u32, u32), ) -> ConstValue<'_> { trace!("const_caller_location: {}:{}:{}", file, line, col); let mut ecx = mk_eval_cx(tcx, DUMMY_SP, ty::ParamEnv::reveal_all(), false); let loc_place = ecx.alloc_caller_location(file, line, col); if intern_const_alloc_recursive(&mut ecx, InternKind::Constant, &loc_place).is_err() { bug!("intern_const_alloc_recursive should not error in this case") } ConstValue::Scalar(Scalar::from_maybe_pointer(loc_place.ptr, &tcx)) } // We forbid type-level constants that contain more than `VALTREE_MAX_NODES` nodes. const VALTREE_MAX_NODES: usize = 1000; pub(crate) enum ValTreeCreationError { NodesOverflow, NonSupportedType, Other, } pub(crate) type ValTreeCreationResult<'tcx> = Result<ty::ValTree<'tcx>, ValTreeCreationError>; /// Evaluates a constant and turns it into a type-level constant value. pub(crate) fn eval_to_valtree<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, cid: GlobalId<'tcx>, ) -> EvalToValTreeResult<'tcx> { let const_alloc = tcx.eval_to_allocation_raw(param_env.and(cid))?; let ecx = mk_eval_cx( tcx, DUMMY_SP, param_env, // It is absolutely crucial for soundness that // we do not read from static items or other mutable memory. false, ); let place = ecx.raw_const_to_mplace(const_alloc).unwrap(); debug!(?place); let mut num_nodes = 0; let valtree_result = const_to_valtree_inner(&ecx, &place, &mut num_nodes); match valtree_result { Ok(valtree) => Ok(Some(valtree)), Err(err) => { let did = cid.instance.def_id(); let s = cid.display(tcx); match err { ValTreeCreationError::NodesOverflow => { let msg = format!("maximum number of nodes exceeded in constant {}", &s); let mut diag = match tcx.hir().span_if_local(did) { Some(span) => tcx.sess.struct_span_err(span, &msg), None => tcx.sess.struct_err(&msg), }; diag.emit(); Ok(None) } ValTreeCreationError::NonSupportedType | ValTreeCreationError::Other => Ok(None), } } } } /// This function should never fail for validated constants. However, it is also invoked from the /// pretty printer which might attempt to format invalid constants and in that case it might fail. pub(crate) fn try_destructure_const<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, val: ty::Const<'tcx>, ) -> InterpResult<'tcx, mir::DestructuredConst<'tcx>> { trace!("destructure_const: {:?}", val); let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false); let op = ecx.const_to_op(val, None)?; // We go to `usize` as we cannot allocate anything bigger anyway. let (field_count, variant, down) = match val.ty().kind() { ty::Array(_, len) => (usize::try_from(len.eval_usize(tcx, param_env)).unwrap(), None, op), // Checks if we have any variants, to avoid downcasting to a non-existing variant (when // there are no variants `read_discriminant` successfully returns a non-existing variant // index). ty::Adt(def, _) if def.variants().is_empty() => throw_ub!(Unreachable), ty::Adt(def, _) => { let variant = ecx.read_discriminant(&op)?.1; let down = ecx.operand_downcast(&op, variant)?; (def.variant(variant).fields.len(), Some(variant), down) } ty::Tuple(substs) => (substs.len(), None, op), _ => bug!("cannot destructure constant {:?}", val), }; let fields = (0..field_count) .map(|i| { let field_op = ecx.operand_field(&down, i)?; let val = op_to_const(&ecx, &field_op); Ok(ty::Const::from_value(tcx, val, field_op.layout.ty)) }) .collect::<InterpResult<'tcx, Vec<_>>>()?; let fields = tcx.arena.alloc_from_iter(fields); Ok(mir::DestructuredConst { variant, fields }) } #[instrument(skip(tcx), level = "debug")] pub(crate) fn try_destructure_mir_constant<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, val: mir::ConstantKind<'tcx>, ) -> InterpResult<'tcx, mir::DestructuredMirConstant<'tcx>> { trace!("destructure_mir_constant: {:?}", val); let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false); let op = ecx.mir_const_to_op(&val, None)?; // We go to `usize` as we cannot allocate anything bigger anyway. let (field_count, variant, down) = match val.ty().kind() { ty::Array(_, len) => (len.eval_usize(tcx, param_env) as usize, None, op), ty::Adt(def, _) if def.variants().is_empty() => { throw_ub!(Unreachable) } ty::Adt(def, _) => { let variant = ecx.read_discriminant(&op).unwrap().1; let down = ecx.operand_downcast(&op, variant).unwrap(); (def.variants()[variant].fields.len(), Some(variant), down) } ty::Tuple(substs) => (substs.len(), None, op), _ => bug!("cannot destructure mir constant {:?}", val), }; let fields_iter = (0..field_count) .map(|i| { let field_op = ecx.operand_field(&down, i)?; let val = op_to_const(&ecx, &field_op); Ok(mir::ConstantKind::Val(val, field_op.layout.ty)) }) .collect::<InterpResult<'tcx, Vec<_>>>()?; let fields = tcx.arena.alloc_from_iter(fields_iter); Ok(mir::DestructuredMirConstant { variant, fields }) } #[instrument(skip(tcx), level = "debug")] pub(crate) fn deref_const<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, val: ty::Const<'tcx>, ) -> ty::Const<'tcx> { trace!("deref_const: {:?}", val); let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false); let op = ecx.const_to_op(val, None).unwrap(); let mplace = ecx.deref_operand(&op).unwrap(); if let Some(alloc_id) = mplace.ptr.provenance { assert_eq!( tcx.get_global_alloc(alloc_id).unwrap().unwrap_memory().inner().mutability, Mutability::Not, "deref_const cannot be used with mutable allocations as \ that could allow pattern matching to observe mutable statics", ); } let ty = match mplace.meta { MemPlaceMeta::None => mplace.layout.ty, MemPlaceMeta::Poison => bug!("poison metadata in `deref_const`: {:#?}", mplace), // In case of unsized types, figure out the real type behind. MemPlaceMeta::Meta(scalar) => match mplace.layout.ty.kind() { ty::Str => bug!("there's no sized equivalent of a `str`"), ty::Slice(elem_ty) => tcx.mk_array(*elem_ty, scalar.to_machine_usize(&tcx).unwrap()), _ => bug!( "type {} should not have metadata, but had {:?}", mplace.layout.ty, mplace.meta ), }, }; tcx.mk_const(ty::ConstS { val: ty::ConstKind::Value(op_to_const(&ecx, &mplace.into())), ty }) } #[instrument(skip(tcx), level = "debug")] pub(crate) fn deref_mir_constant<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, val: mir::ConstantKind<'tcx>, ) -> mir::ConstantKind<'tcx> { let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false); let op = ecx.mir_const_to_op(&val, None).unwrap(); let mplace = ecx.deref_operand(&op).unwrap(); if let Some(alloc_id) = mplace.ptr.provenance { assert_eq!( tcx.get_global_alloc(alloc_id).unwrap().unwrap_memory().0.0.mutability, Mutability::Not, "deref_const cannot be used with mutable allocations as \ that could allow pattern matching to observe mutable statics", ); } let ty = match mplace.meta { MemPlaceMeta::None => mplace.layout.ty, MemPlaceMeta::Poison => bug!("poison metadata in `deref_const`: {:#?}", mplace), // In case of unsized types, figure out the real type behind. MemPlaceMeta::Meta(scalar) => match mplace.layout.ty.kind() { ty::Str => bug!("there's no sized equivalent of a `str`"), ty::Slice(elem_ty) => tcx.mk_array(*elem_ty, scalar.to_machine_usize(&tcx).unwrap()), _ => bug!( "type {} should not have metadata, but had {:?}", mplace.layout.ty, mplace.meta ), }, }; mir::ConstantKind::Val(op_to_const(&ecx, &mplace.into()), ty) }
39.113445
98
0.61274
488b1ee9b203b7aa28b69bcbf396717dc35bb0ac
11,344
//! <div align="center"> //! <h1>🌗🚀 Dioxus</h1> //! <p> //! <strong>A concurrent, functional, virtual DOM for Rust</strong> //! </p> //! </div> //! //! # Resources //! //! This overview provides a brief introduction to Dioxus. For a more in-depth guide, make sure to check out: //! - [Getting Started](https://dioxuslabs.com/getting-started) //! - [Book](https://dioxuslabs.com/book) //! - [Reference](https://dioxuslabs.com/reference) //! - [Community Examples](https://github.com/DioxusLabs/community-examples) //! //! # Overview and Goals //! //! Dioxus makes it easy to quickly build complex user interfaces with Rust. Any Dioxus app can run in the web browser, //! as a desktop app, as a mobile app, or anywhere else provided you build the right renderer. //! //! Dioxus is heavily inspired by React, supporting many of the same concepts: //! //! - Hooks for state //! - VirtualDom & diffing //! - Concurrency, fibers, and asynchronous rendering //! - JSX-like templating syntax //! //! If you know React, then you know Dioxus. //! //! Dioxus is *substantially* more performant than many of the other Rust UI libraries (Yew/Percy) and is *significantly* more performant //! than React - roughly competitve with InfernoJS. //! //! Remember: Dioxus is a library for declaring interactive user interfaces - it is not a dedicated renderer. Most 1st party renderers for Dioxus currently only support web technologies. //! //! ## Brief Overview //! //! All Dioxus apps are built by composing functions that take in a `Scope` which is generic over some `Properties` and return an `Element`. //! A `Scope` holds relevant state data for the the currently-rendered component. //! //! To launch an app, we use the `launch` method for the specific renderer we want to use. In the launch function, we pass the app's `Component`. //! //! ```rust, ignore //! use dioxus::prelude::*; //! //! fn main() { //! dioxus::desktop::launch(app); //! } //! //! fn app(cx: Scope) -> Element { //! cx.render(rsx!("hello world!")) //! } //! ``` //! //! ## Elements & your first component //! //! To assemble UI trees with Dioxus, you need to use the `render` function on //! something called `LazyNodes`. To produce `LazyNodes`, you can use the `rsx!` //! macro or the NodeFactory API. For the most part, you want to use the `rsx!` //! macro. //! //! Any element in `rsx!` can have attributes, listeners, and children. For //! consistency, we force all attributes and listeners to be listed *before* //! children. //! //! ```rust, ignore //! let value = "123"; //! //! rsx!( //! div { //! class: "my-class {value}", // <--- attribute //! onclick: move |_| log::info!("clicked!"), // <--- listener //! h1 { "hello world" }, // <--- child //! } //! ) //! ``` //! //! The `rsx!` macro accepts attributes in "struct form" and will parse the rest //! of the body as child elements and rust expressions. Any rust expression that //! implements `IntoIterator<Item = impl IntoVNode>` will be parsed as a child. //! //! ```rust, ignore //! rsx!( //! div { //! (0..10).map(|_| rsx!(span { "hello world" })) //! } //! ) //! //! ``` //! //! Used within components, the `rsx!` macro must be rendered into an `Element` with //! the `render` function on Scope. //! //! If we want to omit the boilerplate of `cx.render`, we can simply pass in //! `cx` as the first argument of rsx. This is sometimes useful when we need to //! render nodes in match statements. //! //! ```rust, ignore //! fn example(cx: Scope) -> Element { //! //! // both of these are equivalent //! cx.render(rsx!("hello world")) //! //! rsx!(cx, "hello world!") //! } //! ``` //! //! Putting everything together, we can write a simple component that renders a list of //! elements: //! //! ```rust, ignore //! fn app(cx: Scope) -> Element { //! let name = "dave"; //! cx.render(rsx!( //! h1 { "Hello, {name}!" } //! div { //! class: "my-class", //! id: "my-id", //! //! (0..5).map(|i| rsx!( //! div { key: "{i}" //! "FizzBuzz: {i}" //! } //! )) //! //! } //! )) //! } //! ``` //! //! ## Components //! //! We can compose these function components to build a complex app. Each new //! component we design must take some Properties. For components with no explicit //! properties, we can use the `()` type or simply omit the type altogether. //! //! In Dioxus, all properties are memoized by default! //! //! ```rust, ignore //! fn App(cx: Scope) -> Element { //! cx.render(rsx!( //! Header { //! title: "My App", //! color: "red", //! } //! )) //! } //! ``` //! //! Our `Header` component takes a `title` and a `color` property, which we //! declare on an explicit `HeaderProps` struct. //! //! ```rust, ignore //! // The `Props` derive macro lets us add additional functionality to how props are interpreted. //! #[derive(Props, PartialEq)] //! struct HeaderProps { //! title: String, //! color: String, //! } //! //! fn Header(cx: Scope<HeaderProps>) -> Element { //! cx.render(rsx!( //! div { //! background_color: "{cx.props.color}" //! h1 { "{cx.props.title}" } //! } //! )) //! } //! ``` //! //! Components may use the `inline_props` macro to completely inline the props //! definition into the function arguments. //! //! ```rust, ignore //! #[inline_props] //! fn Header(cx: Scope, title: String, color: String) -> Element { //! cx.render(rsx!( //! div { //! background_color: "{color}" //! h1 { "{title}" } //! } //! )) //! } //! ``` //! //! Components may also borrow data from their parent component. We just need to //! attach some lifetimes to the props struct. //! > Note: we don't need to derive `PartialEq` for borrowed props since they cannot be memoized. //! //! ```rust, ignore //! #[derive(Props)] //! struct HeaderProps<'a> { //! title: &'a str, //! color: &'a str, //! } //! //! fn Header<'a>(cx: Scope<'a, HeaderProps<'a>>) -> Element { //! cx.render(rsx!( //! div { //! background_color: "{cx.props.color}" //! h1 { "{cx.props.title}" } //! } //! )) //! } //! ``` //! //! Components that begin with an uppercase letter may be called with //! the traditional (for React) curly-brace syntax like so: //! //! ```rust, ignore //! rsx!( //! Header { title: "My App" } //! ) //! ``` //! //! Alternatively, if your components begin with a lowercase letter, you can use //! the function call syntax: //! //! ```rust, ignore //! rsx!( //! header( title: "My App" ) //! ) //! ``` //! //! ## Hooks //! //! While components are reusable forms of UI elements, hooks are reusable forms //! of logic. Hooks provide us a way of retrieving state from the `Scope` and using //! it to render UI elements. //! //! By convention, all hooks are functions that should start with `use_`. We can //! use hooks to define state and modify it from within listeners. //! //! ```rust, ignore //! fn app(cx: Scope) -> Element { //! let name = use_state(&cx, || "world"); //! //! rsx!(cx, "hello {name}!") //! } //! ``` //! //! Hooks are sensitive to how they are used. To use hooks, you must abide by the //! ["rules of hooks" (borrowed from react)](https://reactjs.org/docs/hooks-rules.html): //! - Functions with "use_" should not be called in callbacks //! - Functions with "use_" should not be called out of order //! - Functions with "use_" should not be called in loops or conditionals //! //! In a sense, hooks let us add a field of state to our component without declaring //! an explicit state struct. However, this means we need to "load" the struct in the right //! order. If that order is wrong, then the hook will pick the wrong state and panic. //! //! Most hooks you'll write are simply composition of other hooks: //! //! ```rust, ignore //! fn use_username(cx: &ScopeState, id: Uuid) -> bool { //! let users = use_context::<Users>(cx); //! users.get(&id).map(|user| user.logged_in).ok_or(false) //! } //! ``` //! //! To create entirely new foundational hooks, we can use the `use_hook` method on `ScopeState`. //! //! ```rust, ignore //! fn use_mut_string(cx: &ScopeState) -> &mut String { //! cx.use_hook(|_| "Hello".to_string()) //! } //! ``` //! //! If you want to extend Dioxus with some new functionality, you'll probably want to implement a new hook from scratch. //! //! ## Putting it all together //! //! Using components, templates, and hooks, we can build a simple app. //! //! ```rust, ignore //! use dioxus::prelude::*; //! //! fn main() { //! dioxus::desktop::launch(App); //! } //! //! fn App(cx: Scope) -> Element { //! let mut count = use_state(&cx, || 0); //! //! cx.render(rsx!( //! div { "Count: {count}" } //! button { onclick: move |_| count += 1, "Increment" } //! button { onclick: move |_| count -= 1, "Decrement" } //! )) //! } //! ``` //! //! ## Features //! //! This overview doesn't cover everything. Make sure to check out the tutorial and reference guide on the official //! website for more details. //! //! Beyond this overview, Dioxus supports: //! - Server-side rendering //! - Concurrent rendering (with async support) //! - Web/Desktop/Mobile support //! - Pre-rendering and rehydration //! - Fragments, Portals, and Suspense //! - Inline-styles //! - Custom event handlers //! - Custom elements //! - Basic fine-grained reactivity (IE SolidJS/Svelte) //! - and more! //! //! Good luck! //! //! ## Inspiration, Resources, Alternatives and Credits //! //! Dioxus is inspired by: //! - React: for its hooks, concurrency, suspense //! - Dodrio: for its research in bump allocation, double buffering, and diffing architecture //! //! Alternatives to Dioxus include: //! - Yew: supports function components and web, but no SSR, borrowed data, or bump allocation. Rather slow at times. //! - Percy: supports function components, web, ssr, but lacks state management //! - Sycamore: supports function components, web, ssr, but closer to SolidJS than React //! - MoonZoom/Seed: opinionated frameworks based on the Elm model (message, update) - no hooks //! //! We've put a lot of work into making Dioxus ergonomic and *familiar*. //! Our target audience is TypeSrcipt developers looking to switch to Rust for the web - so we need to be comparabale to React. pub use dioxus_core as core; #[cfg(feature = "hooks")] pub use dioxus_hooks as hooks; #[cfg(feature = "router")] pub use dioxus_router as router; #[cfg(feature = "ssr")] pub use dioxus_ssr as ssr; #[cfg(feature = "web")] pub use dioxus_web as web; #[cfg(feature = "desktop")] pub use dioxus_desktop as desktop; #[cfg(feature = "fermi")] pub use fermi; // #[cfg(feature = "mobile")] // pub use dioxus_mobile as mobile; pub mod events { #[cfg(feature = "html")] pub use dioxus_html::{on::*, KeyCode}; } pub mod prelude { pub use dioxus_core::prelude::*; pub use dioxus_core_macro::{format_args_f, inline_props, rsx, Props}; pub use dioxus_elements::{GlobalAttributes, SvgAttributes}; pub use dioxus_hooks::*; pub use dioxus_html as dioxus_elements; }
31.423823
186
0.610279
1891956d7408b7578295c25544dad859253ce870
52,466
#![doc = "generated by AutoRust"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::models; #[derive(Clone)] pub struct Client { endpoint: String, credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>, scopes: Vec<String>, pipeline: azure_core::Pipeline, } #[derive(Clone)] pub struct ClientBuilder { credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>, endpoint: Option<String>, scopes: Option<Vec<String>>, } pub const DEFAULT_ENDPOINT: &str = "https://api.applicationinsights.io/v1"; impl ClientBuilder { pub fn new(credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>) -> Self { Self { credential, endpoint: None, scopes: None, } } pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self { self.endpoint = Some(endpoint.into()); self } pub fn scopes(mut self, scopes: &[&str]) -> Self { self.scopes = Some(scopes.iter().map(|scope| (*scope).to_owned()).collect()); self } pub fn build(self) -> Client { let endpoint = self.endpoint.unwrap_or_else(|| DEFAULT_ENDPOINT.to_owned()); let scopes = self.scopes.unwrap_or_else(|| vec![format!("{}/", endpoint)]); Client::new(endpoint, self.credential, scopes) } } impl Client { pub(crate) fn endpoint(&self) -> &str { self.endpoint.as_str() } pub(crate) fn token_credential(&self) -> &dyn azure_core::auth::TokenCredential { self.credential.as_ref() } pub(crate) fn scopes(&self) -> Vec<&str> { self.scopes.iter().map(String::as_str).collect() } pub(crate) async fn send(&self, request: impl Into<azure_core::Request>) -> azure_core::error::Result<azure_core::Response> { let mut context = azure_core::Context::default(); let mut request = request.into(); self.pipeline.send(&mut context, &mut request).await } pub fn new( endpoint: impl Into<String>, credential: std::sync::Arc<dyn azure_core::auth::TokenCredential>, scopes: Vec<String>, ) -> Self { let endpoint = endpoint.into(); let pipeline = azure_core::Pipeline::new( option_env!("CARGO_PKG_NAME"), option_env!("CARGO_PKG_VERSION"), azure_core::ClientOptions::default(), Vec::new(), Vec::new(), ); Self { endpoint, credential, scopes, pipeline, } } pub fn events(&self) -> events::Client { events::Client(self.clone()) } pub fn metadata(&self) -> metadata::Client { metadata::Client(self.clone()) } pub fn metrics(&self) -> metrics::Client { metrics::Client(self.clone()) } pub fn query(&self) -> query::Client { query::Client(self.clone()) } } #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] Metrics_Get(#[from] metrics::get::Error), #[error(transparent)] Metrics_GetMultiple(#[from] metrics::get_multiple::Error), #[error(transparent)] Metrics_GetMetadata(#[from] metrics::get_metadata::Error), #[error(transparent)] Events_GetByType(#[from] events::get_by_type::Error), #[error(transparent)] Events_Get(#[from] events::get::Error), #[error(transparent)] Events_GetOdataMetadata(#[from] events::get_odata_metadata::Error), #[error(transparent)] Query_Get(#[from] query::get::Error), #[error(transparent)] Query_Execute(#[from] query::execute::Error), #[error(transparent)] Metadata_Get(#[from] metadata::get::Error), #[error(transparent)] Metadata_Post(#[from] metadata::post::Error), } pub mod metrics { use super::models; pub struct Client(pub(crate) super::Client); impl Client { #[doc = "Retrieve metric data"] pub fn get(&self, app_id: impl Into<String>, metric_id: impl Into<String>) -> get::Builder { get::Builder { client: self.0.clone(), app_id: app_id.into(), metric_id: metric_id.into(), timespan: None, interval: None, aggregation: Vec::new(), segment: Vec::new(), top: None, orderby: None, filter: None, } } #[doc = "Retrieve metric data"] pub fn get_multiple(&self, app_id: impl Into<String>, body: impl Into<models::MetricsPostBody>) -> get_multiple::Builder { get_multiple::Builder { client: self.0.clone(), app_id: app_id.into(), body: body.into(), } } #[doc = "Retrieve metric metadata"] pub fn get_metadata(&self, app_id: impl Into<String>) -> get_metadata::Builder { get_metadata::Builder { client: self.0.clone(), app_id: app_id.into(), } } } pub mod get { use super::models; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) app_id: String, pub(crate) metric_id: String, pub(crate) timespan: Option<String>, pub(crate) interval: Option<String>, pub(crate) aggregation: Vec<String>, pub(crate) segment: Vec<String>, pub(crate) top: Option<i32>, pub(crate) orderby: Option<String>, pub(crate) filter: Option<String>, } impl Builder { pub fn timespan(mut self, timespan: impl Into<String>) -> Self { self.timespan = Some(timespan.into()); self } pub fn interval(mut self, interval: impl Into<String>) -> Self { self.interval = Some(interval.into()); self } pub fn aggregation(mut self, aggregation: Vec<String>) -> Self { self.aggregation = aggregation; self } pub fn segment(mut self, segment: Vec<String>) -> Self { self.segment = segment; self } pub fn top(mut self, top: i32) -> Self { self.top = Some(top); self } pub fn orderby(mut self, orderby: impl Into<String>) -> Self { self.orderby = Some(orderby.into()); self } pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::MetricsResult, Error>> { Box::pin(async move { let url_str = &format!("{}/apps/{}/metrics/{}", self.client.endpoint(), &self.app_id, &self.metric_id); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); if let Some(timespan) = &self.timespan { url.query_pairs_mut().append_pair("timespan", timespan); } if let Some(interval) = &self.interval { url.query_pairs_mut().append_pair("interval", interval); } if let Some(top) = &self.top { url.query_pairs_mut().append_pair("top", &top.to_string()); } if let Some(orderby) = &self.orderby { url.query_pairs_mut().append_pair("orderby", orderby); } if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("filter", filter); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::MetricsResult = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod get_multiple { use super::models; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) app_id: String, pub(crate) body: models::MetricsPostBody, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::MetricsResults, Error>> { Box::pin(async move { let url_str = &format!("{}/apps/{}/metrics", self.client.endpoint(), &self.app_id); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.body).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::MetricsResults = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod get_metadata { use super::models; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) app_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<serde_json::Value, Error>> { Box::pin(async move { let url_str = &format!("{}/apps/{}/metrics/metadata", self.client.endpoint(), &self.app_id); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: serde_json::Value = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod events { use super::models; pub struct Client(pub(crate) super::Client); impl Client { #[doc = "Execute OData query"] pub fn get_by_type(&self, app_id: impl Into<String>, event_type: impl Into<String>) -> get_by_type::Builder { get_by_type::Builder { client: self.0.clone(), app_id: app_id.into(), event_type: event_type.into(), timespan: None, filter: None, search: None, orderby: None, select: None, skip: None, top: None, format: None, count: None, apply: None, } } #[doc = "Get an event"] pub fn get(&self, app_id: impl Into<String>, event_type: impl Into<String>, event_id: impl Into<String>) -> get::Builder { get::Builder { client: self.0.clone(), app_id: app_id.into(), event_type: event_type.into(), event_id: event_id.into(), timespan: None, } } #[doc = "Get OData metadata"] pub fn get_odata_metadata(&self, app_id: impl Into<String>) -> get_odata_metadata::Builder { get_odata_metadata::Builder { client: self.0.clone(), app_id: app_id.into(), } } } pub mod get_by_type { use super::models; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) app_id: String, pub(crate) event_type: String, pub(crate) timespan: Option<String>, pub(crate) filter: Option<String>, pub(crate) search: Option<String>, pub(crate) orderby: Option<String>, pub(crate) select: Option<String>, pub(crate) skip: Option<i32>, pub(crate) top: Option<i32>, pub(crate) format: Option<String>, pub(crate) count: Option<bool>, pub(crate) apply: Option<String>, } impl Builder { pub fn timespan(mut self, timespan: impl Into<String>) -> Self { self.timespan = Some(timespan.into()); self } pub fn filter(mut self, filter: impl Into<String>) -> Self { self.filter = Some(filter.into()); self } pub fn search(mut self, search: impl Into<String>) -> Self { self.search = Some(search.into()); self } pub fn orderby(mut self, orderby: impl Into<String>) -> Self { self.orderby = Some(orderby.into()); self } pub fn select(mut self, select: impl Into<String>) -> Self { self.select = Some(select.into()); self } pub fn skip(mut self, skip: i32) -> Self { self.skip = Some(skip); self } pub fn top(mut self, top: i32) -> Self { self.top = Some(top); self } pub fn format(mut self, format: impl Into<String>) -> Self { self.format = Some(format.into()); self } pub fn count(mut self, count: bool) -> Self { self.count = Some(count); self } pub fn apply(mut self, apply: impl Into<String>) -> Self { self.apply = Some(apply.into()); self } pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::EventsResults, Error>> { Box::pin(async move { let url_str = &format!("{}/apps/{}/events/{}", self.client.endpoint(), &self.app_id, &self.event_type); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); if let Some(timespan) = &self.timespan { url.query_pairs_mut().append_pair("timespan", timespan); } if let Some(filter) = &self.filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(search) = &self.search { url.query_pairs_mut().append_pair("$search", search); } if let Some(orderby) = &self.orderby { url.query_pairs_mut().append_pair("$orderby", orderby); } if let Some(select) = &self.select { url.query_pairs_mut().append_pair("$select", select); } if let Some(skip) = &self.skip { url.query_pairs_mut().append_pair("$skip", &skip.to_string()); } if let Some(top) = &self.top { url.query_pairs_mut().append_pair("$top", &top.to_string()); } if let Some(format) = &self.format { url.query_pairs_mut().append_pair("$format", format); } if let Some(count) = &self.count { url.query_pairs_mut().append_pair("$count", &count.to_string()); } if let Some(apply) = &self.apply { url.query_pairs_mut().append_pair("$apply", apply); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::EventsResults = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod get { use super::models; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) app_id: String, pub(crate) event_type: String, pub(crate) event_id: String, pub(crate) timespan: Option<String>, } impl Builder { pub fn timespan(mut self, timespan: impl Into<String>) -> Self { self.timespan = Some(timespan.into()); self } pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::EventsResults, Error>> { Box::pin(async move { let url_str = &format!( "{}/apps/{}/events/{}/{}", self.client.endpoint(), &self.app_id, &self.event_type, &self.event_id ); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); if let Some(timespan) = &self.timespan { url.query_pairs_mut().append_pair("timespan", timespan); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::EventsResults = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod get_odata_metadata { use super::models; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) app_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<serde_json::Value, Error>> { Box::pin(async move { let url_str = &format!("{}/apps/{}/events/$metadata", self.client.endpoint(), &self.app_id); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: serde_json::Value = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod query { use super::models; pub struct Client(pub(crate) super::Client); impl Client { #[doc = "Execute an Analytics query"] pub fn get(&self, app_id: impl Into<String>, query: impl Into<String>) -> get::Builder { get::Builder { client: self.0.clone(), app_id: app_id.into(), query: query.into(), timespan: None, } } #[doc = "Execute an Analytics query"] pub fn execute(&self, app_id: impl Into<String>, body: impl Into<models::QueryBody>) -> execute::Builder { execute::Builder { client: self.0.clone(), app_id: app_id.into(), body: body.into(), } } } pub mod get { use super::models; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) app_id: String, pub(crate) query: String, pub(crate) timespan: Option<String>, } impl Builder { pub fn timespan(mut self, timespan: impl Into<String>) -> Self { self.timespan = Some(timespan.into()); self } pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::QueryResults, Error>> { Box::pin(async move { let url_str = &format!("{}/apps/{}/query", self.client.endpoint(), &self.app_id); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); let query = &self.query; url.query_pairs_mut().append_pair("query", query); if let Some(timespan) = &self.timespan { url.query_pairs_mut().append_pair("timespan", timespan); } let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::QueryResults = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod execute { use super::models; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) app_id: String, pub(crate) body: models::QueryBody, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::QueryResults, Error>> { Box::pin(async move { let url_str = &format!("{}/apps/{}/query", self.client.endpoint(), &self.app_id); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(&self.body).map_err(Error::Serialize)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::QueryResults = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } } pub mod metadata { use super::models; pub struct Client(pub(crate) super::Client); impl Client { #[doc = "Gets metadata information"] pub fn get(&self, app_id: impl Into<String>) -> get::Builder { get::Builder { client: self.0.clone(), app_id: app_id.into(), } } #[doc = "Gets metadata information"] pub fn post(&self, app_id: impl Into<String>) -> post::Builder { post::Builder { client: self.0.clone(), app_id: app_id.into(), } } } pub mod get { use super::models; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) app_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::MetadataResults, Error>> { Box::pin(async move { let url_str = &format!("{}/apps/{}/metadata", self.client.endpoint(), &self.app_id); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::MetadataResults = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } pub mod post { use super::models; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, #[error("Failed to parse request URL")] ParseUrl(#[source] url::ParseError), #[error("Failed to build request")] BuildRequest(#[source] http::Error), #[error("Failed to serialize request body")] Serialize(#[source] serde_json::Error), #[error("Failed to get access token")] GetToken(#[source] azure_core::Error), #[error("Failed to execute request")] SendRequest(#[source] azure_core::error::Error), #[error("Failed to get response bytes")] ResponseBytes(#[source] azure_core::error::Error), #[error("Failed to deserialize response, body: {1:?}")] Deserialize(#[source] serde_json::Error, bytes::Bytes), } #[derive(Clone)] pub struct Builder { pub(crate) client: super::super::Client, pub(crate) app_id: String, } impl Builder { pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::MetadataResults, Error>> { Box::pin(async move { let url_str = &format!("{}/apps/{}/metadata", self.client.endpoint(), &self.app_id); let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); let credential = self.client.token_credential(); let token_response = credential .get_token(&self.client.scopes().join(" ")) .await .map_err(Error::GetToken)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); let req_body = azure_core::EMPTY_BODY; req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(Error::BuildRequest)?; let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct(); match rsp_status { http::StatusCode::OK => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::MetadataResults = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?; let rsp_value: models::ErrorResponse = serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?; Err(Error::DefaultResponse { status_code, value: rsp_value, }) } } }) } } } }
48.624652
135
0.504384
71ad14c895d79bff09e7fbc8c77e1e3cc1e874a8
1,796
pub struct IconSettingsPhone { props: crate::Props, } impl yew::Component for IconSettingsPhone { type Properties = crate::Props; type Message = (); fn create(props: Self::Properties, _: yew::prelude::ComponentLink<Self>) -> Self { Self { props } } fn update(&mut self, _: Self::Message) -> yew::prelude::ShouldRender { true } fn change(&mut self, _: Self::Properties) -> yew::prelude::ShouldRender { false } fn view(&self) -> yew::prelude::Html { yew::prelude::html! { <svg class=self.props.class.unwrap_or("") width=self.props.size.unwrap_or(24).to_string() height=self.props.size.unwrap_or(24).to_string() viewBox="0 0 24 24" fill=self.props.fill.unwrap_or("none") stroke=self.props.color.unwrap_or("currentColor") stroke-width=self.props.stroke_width.unwrap_or(2).to_string() stroke-linecap=self.props.stroke_linecap.unwrap_or("round") stroke-linejoin=self.props.stroke_linejoin.unwrap_or("round") > <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M11 9h2v2h-2zm4 0h2v2h-2zm5 6.5c-1.25 0-2.45-.2-3.57-.57-.1-.03-.21-.05-.31-.05-.26 0-.51.1-.71.29l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM5.03 5h1.5c.07.88.22 1.75.46 2.59L5.79 8.8c-.41-1.21-.67-2.48-.76-3.8zM19 18.97c-1.32-.09-2.6-.35-3.8-.76l1.2-1.2c.85.24 1.72.39 2.6.45v1.51zM19 9h2v2h-2z"/></svg> </svg> } } }
39.043478
595
0.578508
fb2a2b9cb9c1de9e0fcbd1a445cd88d9cf41dd10
11,432
use std::{fs, io, path::Path}; /// The character length of the random string used for temporary file names. const TMP_NAME_LEN: usize = 7; /// Represents an action that should be run when this objects runs out of scope, /// unless it's explicitly deactivated. /// /// This helps with implementing functions that have transactional semantics: /// /// ```text /// do_x()?; /// let mut guard_x = OnScopeExit::new(|| undo_x()); /// /// // If this fails, undo_x() is called /// do_y()?; /// let mut guard_y = OnScopeExit::new(|| undo_y()); /// /// // If this fails, both undo_x and undo_y are called. /// let goods = get_goods()?; /// /// // The transaction is complete, deactivate the undo actions. /// guard_x.deactivate(); /// guard_y.deactivate(); /// /// return goods; /// ``` struct OnScopeExit<F> where F: FnOnce(), { action: Option<F>, } impl<F> OnScopeExit<F> where F: FnOnce(), { fn new(action: F) -> Self { Self { action: Some(action), } } fn deactivate(&mut self) { self.action = None } } impl<F> Drop for OnScopeExit<F> where F: FnOnce(), { fn drop(&mut self) { if let Some(action) = self.action.take() { action() } } } /// Atomically writes to `dst` file, using `tmp` as a buffer. /// /// Creates `tmp` if necessary and removes it if write fails with an error. /// /// # Pre-conditions /// * `dst` and `tmp` are not directories. /// * `dst` and `tmp` are on the same file system. /// /// # Panics /// /// Doesn't panic unless `action` panics. #[cfg(target_family = "unix")] pub fn write_atomically_using_tmp_file<PDst, PTmp, F>( dst: PDst, tmp: PTmp, action: F, ) -> io::Result<()> where F: FnOnce(&mut io::BufWriter<&fs::File>) -> io::Result<()>, PDst: AsRef<Path>, PTmp: AsRef<Path>, { use std::io::Write; let mut cleanup = OnScopeExit::new(|| { let _ = fs::remove_file(tmp.as_ref()); }); let f = fs::OpenOptions::new() .write(true) .create(true) .open(tmp.as_ref())?; { let mut w = io::BufWriter::new(&f); action(&mut w)?; w.flush()?; } f.sync_all()?; fs::rename(tmp.as_ref(), dst.as_ref())?; cleanup.deactivate(); Ok(()) } #[cfg(any(target_os = "linux"))] /// Copies only valid regions of file preserving the sparseness /// of the file. Also utilizes copy_file_range which performs /// in_kernel copy without the additional cost of transferring data /// from the kernel to user space and then back into the kernel. Also /// on certain file systems that support COW (btrfs/zfs), copy_file_range /// is a metadata operation and is extremely efficient pub fn copy_file_sparse(from: &Path, to: &Path) -> io::Result<u64> { use cvt::*; use fs::{File, OpenOptions}; use io::{Error, ErrorKind, Read, Write}; use libc::{ftruncate64, lseek64}; use std::os::unix::{ fs::{OpenOptionsExt, PermissionsExt}, io::AsRawFd, }; unsafe fn copy_file_range( fd_in: libc::c_int, off_in: *mut libc::loff_t, fd_out: libc::c_int, off_out: *mut libc::loff_t, len: libc::size_t, flags: libc::c_uint, ) -> libc::c_long { libc::syscall( libc::SYS_copy_file_range, fd_in, off_in, fd_out, off_out, len, flags, ) } let mut reader = File::open(from)?; let (mode, len) = { let metadata = reader.metadata()?; if !metadata.is_file() { return Err(Error::new( ErrorKind::InvalidInput, "the source path is not an existing regular file", )); } (metadata.permissions().mode(), metadata.len()) }; let bytes_to_copy: i64 = len as i64; let mut writer = OpenOptions::new() // prevent world readable/writeable file in case of empty umask .mode(0o000) .write(true) .create(true) .truncate(true) .open(to)?; let fd_in = reader.as_raw_fd(); let fd_out = writer.as_raw_fd(); cvt_r(|| unsafe { libc::fchmod(fd_out, mode) })?; match cvt_r(|| unsafe { ftruncate64(fd_out, bytes_to_copy) }) { Ok(_) => {} Err(err) => return Err(err), }; let mut srcpos: i64 = 0; let (mut can_handle_sparse, mut next_beg) = { let ret = unsafe { lseek64(fd_in, srcpos, libc::SEEK_DATA) }; if ret == -1 { (false, 0) } else { (true, ret) } }; let mut next_end: libc::loff_t = bytes_to_copy; if can_handle_sparse { let ret = unsafe { lseek64(fd_in, next_beg, libc::SEEK_HOLE) }; if ret == -1 { can_handle_sparse = false; } else { next_end = ret } } let mut next_len = next_end - next_beg; let mut use_copy_file_range = true; while srcpos < bytes_to_copy { if srcpos != 0 { if can_handle_sparse { next_beg = match cvt(unsafe { lseek64(fd_in, srcpos, libc::SEEK_DATA) }) { Ok(beg) => beg, Err(err) => match err.raw_os_error() { Some(libc::ENXIO) => { // Remaining portion is hole return Ok(srcpos as u64); } _ => { return Err(err); } }, }; next_end = cvt(unsafe { lseek64(fd_in, next_beg, libc::SEEK_HOLE) })?; next_len = next_end - next_beg; } else { next_beg = srcpos; next_end = bytes_to_copy - srcpos; } } if next_len <= 0 { srcpos = next_end; continue; } let num = if use_copy_file_range { match cvt(unsafe { copy_file_range( fd_in, &mut next_beg, fd_out, &mut next_beg, next_len as usize, 0, ) }) { Ok(n) => n as isize, Err(err) => match err.raw_os_error() { // Try fallback if either: // - Kernel version is < 4.5 (ENOSYS) // - Files are mounted on different fs (EXDEV) // - copy_file_range is disallowed, for example by seccomp (EPERM) Some(libc::ENOSYS) | Some(libc::EPERM) => { use_copy_file_range = false; continue; } Some(libc::EXDEV) | Some(libc::EINVAL) => { use_copy_file_range = false; continue; } _ => { return Err(err); } }, } } else { if can_handle_sparse { cvt(unsafe { lseek64(fd_in, next_beg, libc::SEEK_SET) })?; if next_beg != 0 { cvt(unsafe { lseek64(fd_out, next_beg, libc::SEEK_SET) })?; } } const DEFAULT_BUF_SIZE: usize = 16 * 1024; let mut buf = unsafe { let buf: [u8; DEFAULT_BUF_SIZE] = std::mem::zeroed(); buf }; let mut written = 0; while next_len > 0 { let slice_len = next_len.min(DEFAULT_BUF_SIZE as i64) as usize; let len = match reader.read(&mut buf[..slice_len]) { Ok(0) => { // break early out of copy loop, because nothing is to be read anymore srcpos += written; break; } Ok(len) => len, Err(ref err) if err.kind() == ErrorKind::Interrupted => continue, Err(err) => return Err(err), }; writer.write_all(&buf[..len])?; written += len as i64; next_len -= len as i64; } written as isize }; srcpos += num as i64; } Ok(srcpos as u64) } #[cfg(not(target_os = "linux"))] pub fn copy_file_sparse(from: &Path, to: &Path) -> io::Result<u64> { fs::copy(from, to) } /// Atomically write to `dst` file, using a random file in the parent directory /// of `dst` as the temporary file. /// /// # Pre-conditions /// * `dst` is not a directory. /// * The parent directory of `dst` must be writeable. /// /// # Panics /// /// Doesn't panic unless `action` panics. #[cfg(target_family = "unix")] pub fn write_atomically<PDst, F>(dst: PDst, action: F) -> io::Result<()> where F: FnOnce(&mut io::BufWriter<&fs::File>) -> io::Result<()>, PDst: AsRef<Path>, { // `.parent()` returns `None` for either `/` or a prefix (e.g. 'c:\\` on // windows). `write_atomically` is only available on UNIX, so we default to // `/` in case `.parent()` returns `None`. let tmp_path = dst .as_ref() .parent() .unwrap_or_else(|| Path::new("/")) .join(tmp_name()); write_atomically_using_tmp_file(dst, tmp_path.as_path(), action) } #[cfg(target_family = "unix")] fn tmp_name() -> String { use rand::{distributions::Alphanumeric, Rng}; let mut rng = rand::thread_rng(); std::iter::repeat(()) .map(|_| rng.sample(Alphanumeric)) .map(char::from) .take(TMP_NAME_LEN) .collect() } #[cfg(test)] mod tests { use super::write_atomically_using_tmp_file; #[test] fn test_write_success() { let tmp_dir = tempfile::TempDir::new().expect("failed to create a temporary directory"); let dst = tmp_dir.path().join("target.txt"); let tmp = tmp_dir.path().join("target_tmp.txt"); write_atomically_using_tmp_file(&dst, &tmp, |buf| { use std::io::Write; buf.write_all(b"test")?; Ok(()) }) .expect("failed to write atomically"); assert!(!tmp.exists()); assert_eq!( std::fs::read(&dst).expect("failed to read destination file"), b"test".to_vec() ); } #[test] fn test_write_failure() { let tmp_dir = tempfile::TempDir::new().expect("failed to create a temporary directory"); let dst = tmp_dir.path().join("target.txt"); let tmp = tmp_dir.path().join("target_tmp.txt"); std::fs::write(&dst, b"original contents") .expect("failed to write to the destination file"); let result = write_atomically_using_tmp_file(&dst, &tmp, |buf| { use std::io::Write; buf.write_all(b"new shiny contents")?; Err(std::io::Error::new( std::io::ErrorKind::Other, "something went wrong", )) }); assert!(!tmp.exists()); assert!( result.is_err(), "expected action result to be an error, got {:?}", result ); assert_eq!( std::fs::read(&dst).expect("failed to read destination file"), b"original contents".to_vec() ); } }
29.015228
96
0.50866
9c59e2a7413427992ef40b271fab82f804035256
88,878
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. #[macro_use] extern crate lazy_static; #[cfg(unix)] extern crate nix; #[cfg(unix)] extern crate pty; extern crate tempfile; use futures::prelude::*; use std::io::BufRead; use std::process::Command; use tempfile::TempDir; #[test] fn std_tests() { let dir = TempDir::new().expect("tempdir fail"); let std_path = util::root_path().join("std"); let status = util::deno_cmd() .env("DENO_DIR", dir.path()) .current_dir(std_path) // TODO(ry) change this to root_path .arg("test") .arg("--unstable") .arg("--seed=86") // Some tests rely on specific random numbers. .arg("-A") // .arg("-Ldebug") .spawn() .unwrap() .wait() .unwrap(); assert!(status.success()); } #[test] fn x_deno_warning() { let g = util::http_server(); let output = util::deno_cmd() .current_dir(util::root_path()) .arg("run") .arg("--reload") .arg("http://127.0.0.1:4545/cli/tests/x_deno_warning.js") .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .spawn() .unwrap() .wait_with_output() .unwrap(); assert!(output.status.success()); let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim(); let stderr_str = std::str::from_utf8(&output.stderr).unwrap().trim(); assert_eq!("testing x-deno-warning header", stdout_str); assert!(util::strip_ansi_codes(stderr_str).contains("Warning foobar")); drop(g); } #[test] fn eval_p() { let output = util::deno_cmd() .arg("eval") .arg("-p") .arg("1+2") .stdout(std::process::Stdio::piped()) .spawn() .unwrap() .wait_with_output() .unwrap(); assert!(output.status.success()); let stdout_str = util::strip_ansi_codes(std::str::from_utf8(&output.stdout).unwrap().trim()); assert_eq!("3", stdout_str); } #[test] fn no_color() { let output = util::deno_cmd() .current_dir(util::root_path()) .arg("run") .arg("cli/tests/no_color.js") .env("NO_COLOR", "1") .stdout(std::process::Stdio::piped()) .spawn() .unwrap() .wait_with_output() .unwrap(); assert!(output.status.success()); let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim(); assert_eq!("noColor true", stdout_str); let output = util::deno_cmd() .current_dir(util::root_path()) .arg("run") .arg("cli/tests/no_color.js") .stdout(std::process::Stdio::piped()) .spawn() .unwrap() .wait_with_output() .unwrap(); assert!(output.status.success()); let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim(); assert_eq!("noColor false", util::strip_ansi_codes(stdout_str)); } // TODO re-enable. This hangs on macOS // https://github.com/denoland/deno/issues/4262 #[cfg(unix)] #[test] #[ignore] pub fn test_raw_tty() { use pty::fork::*; use std::io::{Read, Write}; let fork = Fork::from_ptmx().unwrap(); if let Ok(mut master) = fork.is_parent() { let mut obytes: [u8; 100] = [0; 100]; let mut nread = master.read(&mut obytes).unwrap(); assert_eq!(String::from_utf8_lossy(&obytes[0..nread]), "S"); master.write_all(b"a").unwrap(); nread = master.read(&mut obytes).unwrap(); assert_eq!(String::from_utf8_lossy(&obytes[0..nread]), "A"); master.write_all(b"b").unwrap(); nread = master.read(&mut obytes).unwrap(); assert_eq!(String::from_utf8_lossy(&obytes[0..nread]), "B"); master.write_all(b"c").unwrap(); nread = master.read(&mut obytes).unwrap(); assert_eq!(String::from_utf8_lossy(&obytes[0..nread]), "C"); } else { use nix::sys::termios; use std::os::unix::io::AsRawFd; use std::process::*; // Turn off echo such that parent is reading works properly. let stdin_fd = std::io::stdin().as_raw_fd(); let mut t = termios::tcgetattr(stdin_fd).unwrap(); t.local_flags.remove(termios::LocalFlags::ECHO); termios::tcsetattr(stdin_fd, termios::SetArg::TCSANOW, &t).unwrap(); let deno_dir = TempDir::new().expect("tempdir fail"); let mut child = Command::new(util::deno_exe_path()) .env("DENO_DIR", deno_dir.path()) .current_dir(util::root_path()) .arg("run") .arg("cli/tests/raw_mode.ts") .stdin(Stdio::inherit()) .stdout(Stdio::inherit()) .stderr(Stdio::null()) .spawn() .expect("Failed to spawn script"); child.wait().unwrap(); } } #[test] fn test_pattern_match() { // foo, bar, baz, qux, quux, quuz, corge, grault, garply, waldo, fred, plugh, xyzzy let wildcard = "[BAR]"; assert!(util::pattern_match("foo[BAR]baz", "foobarbaz", wildcard)); assert!(!util::pattern_match("foo[BAR]baz", "foobazbar", wildcard)); let multiline_pattern = "[BAR] foo: [BAR]baz[BAR]"; fn multi_line_builder(input: &str, leading_text: Option<&str>) -> String { // If there is leading text add a newline so it's on it's own line let head = match leading_text { Some(v) => format!("{}\n", v), None => "".to_string(), }; format!( "{}foo: quuz {} corge grault", head, input ) } // Validate multi-line string builder assert_eq!( "QUUX=qux foo: quuz BAZ corge grault", multi_line_builder("BAZ", Some("QUUX=qux")) ); // Correct input & leading line assert!(util::pattern_match( multiline_pattern, &multi_line_builder("baz", Some("QUX=quux")), wildcard )); // Correct input & no leading line assert!(util::pattern_match( multiline_pattern, &multi_line_builder("baz", None), wildcard )); // Incorrect input & leading line assert!(!util::pattern_match( multiline_pattern, &multi_line_builder("garply", Some("QUX=quux")), wildcard )); // Incorrect input & no leading line assert!(!util::pattern_match( multiline_pattern, &multi_line_builder("garply", None), wildcard )); } #[test] fn benchmark_test() { util::run_python_script("tools/benchmark_test.py") } #[test] fn deno_dir_test() { use std::fs::remove_dir_all; let g = util::http_server(); let deno_dir = TempDir::new().expect("tempdir fail"); remove_dir_all(deno_dir.path()).unwrap(); // Run deno with no env flag let status = util::deno_cmd() .env_remove("DENO_DIR") .current_dir(util::root_path()) .arg("run") .arg("http://localhost:4545/cli/tests/subdir/print_hello.ts") .spawn() .expect("Failed to spawn script") .wait() .expect("Failed to wait for child process"); assert!(status.success()); assert!(!deno_dir.path().exists()); // Run deno with DENO_DIR env flag let status = util::deno_cmd() .env("DENO_DIR", deno_dir.path()) .current_dir(util::root_path()) .arg("run") .arg("http://localhost:4545/cli/tests/subdir/print_hello.ts") .spawn() .expect("Failed to spawn script") .wait() .expect("Failed to wait for child process"); assert!(status.success()); assert!(deno_dir.path().is_dir()); assert!(deno_dir.path().join("deps").is_dir()); assert!(deno_dir.path().join("gen").is_dir()); remove_dir_all(deno_dir.path()).unwrap(); drop(deno_dir); drop(g); } #[test] fn cache_test() { let g = util::http_server(); let deno_dir = TempDir::new().expect("tempdir fail"); let module_url = url::Url::parse("http://localhost:4545/cli/tests/006_url_imports.ts") .unwrap(); let output = Command::new(util::deno_exe_path()) .env("DENO_DIR", deno_dir.path()) .current_dir(util::root_path()) .arg("cache") .arg(module_url.to_string()) .output() .expect("Failed to spawn script"); assert!(output.status.success()); let out = std::str::from_utf8(&output.stdout).unwrap(); assert_eq!(out, ""); // TODO(ry) Is there some way to check that the file was actually cached in // DENO_DIR? drop(g); } #[test] fn fmt_test() { let t = TempDir::new().expect("tempdir fail"); let fixed = util::root_path().join("cli/tests/badly_formatted_fixed.js"); let badly_formatted_original = util::root_path().join("cli/tests/badly_formatted.js"); let badly_formatted = t.path().join("badly_formatted.js"); let badly_formatted_str = badly_formatted.to_str().unwrap(); std::fs::copy(&badly_formatted_original, &badly_formatted) .expect("Failed to copy file"); let status = util::deno_cmd() .current_dir(util::root_path()) .arg("fmt") .arg("--check") .arg(badly_formatted_str) .spawn() .expect("Failed to spawn script") .wait() .expect("Failed to wait for child process"); assert!(!status.success()); let status = util::deno_cmd() .current_dir(util::root_path()) .arg("fmt") .arg(badly_formatted_str) .spawn() .expect("Failed to spawn script") .wait() .expect("Failed to wait for child process"); assert!(status.success()); let expected = std::fs::read_to_string(fixed).unwrap(); let actual = std::fs::read_to_string(badly_formatted).unwrap(); assert_eq!(expected, actual); } #[test] fn fmt_stdin_error() { use std::io::Write; let mut deno = util::deno_cmd() .current_dir(util::root_path()) .arg("fmt") .arg("-") .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .spawn() .unwrap(); let stdin = deno.stdin.as_mut().unwrap(); let invalid_js = b"import { example }"; stdin.write_all(invalid_js).unwrap(); let output = deno.wait_with_output().unwrap(); // Error message might change. Just check stdout empty, stderr not. assert!(output.stdout.is_empty()); assert!(!output.stderr.is_empty()); assert!(!output.status.success()); } // Warning: this test requires internet access. #[test] fn upgrade_in_tmpdir() { let temp_dir = TempDir::new().unwrap(); let exe_path = if cfg!(windows) { temp_dir.path().join("deno") } else { temp_dir.path().join("deno.exe") }; let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); assert!(exe_path.exists()); let _mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); let status = Command::new(&exe_path) .arg("upgrade") .arg("--force") .spawn() .unwrap() .wait() .unwrap(); assert!(status.success()); let _mtime2 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); // TODO(ry) assert!(mtime1 < mtime2); } // Warning: this test requires internet access. #[test] fn upgrade_with_version_in_tmpdir() { let temp_dir = TempDir::new().unwrap(); let exe_path = if cfg!(windows) { temp_dir.path().join("deno") } else { temp_dir.path().join("deno.exe") }; let _ = std::fs::copy(util::deno_exe_path(), &exe_path).unwrap(); assert!(exe_path.exists()); let _mtime1 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); let status = Command::new(&exe_path) .arg("upgrade") .arg("--force") .arg("--version") .arg("0.42.0") .spawn() .unwrap() .wait() .unwrap(); assert!(status.success()); let upgraded_deno_version = String::from_utf8( Command::new(&exe_path).arg("-V").output().unwrap().stdout, ) .unwrap(); assert!(upgraded_deno_version.contains("0.42.0")); let _mtime2 = std::fs::metadata(&exe_path).unwrap().modified().unwrap(); // TODO(ry) assert!(mtime1 < mtime2); } #[test] fn installer_test_local_module_run() { let temp_dir = TempDir::new().expect("tempdir fail"); let bin_dir = temp_dir.path().join("bin"); std::fs::create_dir(&bin_dir).unwrap(); let status = util::deno_cmd() .current_dir(util::root_path()) .arg("install") .arg("--name") .arg("echo_test") .arg("--root") .arg(temp_dir.path()) .arg(util::tests_path().join("echo.ts")) .arg("hello") .spawn() .unwrap() .wait() .unwrap(); assert!(status.success()); let mut file_path = bin_dir.join("echo_test"); if cfg!(windows) { file_path = file_path.with_extension("cmd"); } assert!(file_path.exists()); // NOTE: using file_path here instead of exec_name, because tests // shouldn't mess with user's PATH env variable let output = Command::new(file_path) .current_dir(temp_dir.path()) .arg("foo") .env("PATH", util::target_dir()) .output() .expect("failed to spawn script"); let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim(); assert!(stdout_str.ends_with("hello, foo")); } #[test] fn installer_test_remote_module_run() { let g = util::http_server(); let temp_dir = TempDir::new().expect("tempdir fail"); let bin_dir = temp_dir.path().join("bin"); std::fs::create_dir(&bin_dir).unwrap(); let status = util::deno_cmd() .current_dir(util::root_path()) .arg("install") .arg("--name") .arg("echo_test") .arg("--root") .arg(temp_dir.path()) .arg("http://localhost:4545/cli/tests/echo.ts") .arg("hello") .spawn() .unwrap() .wait() .unwrap(); assert!(status.success()); let mut file_path = bin_dir.join("echo_test"); if cfg!(windows) { file_path = file_path.with_extension("cmd"); } assert!(file_path.exists()); let output = Command::new(file_path) .current_dir(temp_dir.path()) .arg("foo") .env("PATH", util::target_dir()) .output() .expect("failed to spawn script"); assert!(std::str::from_utf8(&output.stdout) .unwrap() .trim() .ends_with("hello, foo")); drop(g) } #[test] fn js_unit_tests() { let g = util::http_server(); let mut deno = util::deno_cmd() .current_dir(util::root_path()) .arg("run") .arg("--unstable") .arg("--reload") .arg("-A") .arg("cli/tests/unit/unit_test_runner.ts") .arg("--master") .arg("--verbose") .env("NO_COLOR", "1") .spawn() .expect("failed to spawn script"); let status = deno.wait().expect("failed to wait for the child process"); drop(g); assert_eq!(Some(0), status.code()); assert!(status.success()); } #[test] fn ts_dependency_recompilation() { let t = TempDir::new().expect("tempdir fail"); let ats = t.path().join("a.ts"); std::fs::write( &ats, " import { foo } from \"./b.ts\"; function print(str: string): void { console.log(str); } print(foo);", ) .unwrap(); let bts = t.path().join("b.ts"); std::fs::write( &bts, " export const foo = \"foo\";", ) .unwrap(); let output = util::deno_cmd() .current_dir(util::root_path()) .env("NO_COLOR", "1") .arg("run") .arg(&ats) .output() .expect("failed to spawn script"); let stdout_output = std::str::from_utf8(&output.stdout).unwrap().trim(); let stderr_output = std::str::from_utf8(&output.stderr).unwrap().trim(); assert!(stdout_output.ends_with("foo")); assert!(stderr_output.starts_with("Compile")); // Overwrite contents of b.ts and run again std::fs::write( &bts, " export const foo = 5;", ) .expect("error writing file"); let output = util::deno_cmd() .current_dir(util::root_path()) .env("NO_COLOR", "1") .arg("run") .arg(&ats) .output() .expect("failed to spawn script"); let stdout_output = std::str::from_utf8(&output.stdout).unwrap().trim(); let stderr_output = std::str::from_utf8(&output.stderr).unwrap().trim(); // error: TS2345 [ERROR]: Argument of type '5' is not assignable to parameter of type 'string'. assert!(stderr_output.contains("TS2345")); assert!(!output.status.success()); assert!(stdout_output.is_empty()); } #[test] fn bundle_exports() { // First we have to generate a bundle of some module that has exports. let mod1 = util::root_path().join("cli/tests/subdir/mod1.ts"); assert!(mod1.is_file()); let t = TempDir::new().expect("tempdir fail"); let bundle = t.path().join("mod1.bundle.js"); let mut deno = util::deno_cmd() .current_dir(util::root_path()) .arg("bundle") .arg(mod1) .arg(&bundle) .spawn() .expect("failed to spawn script"); let status = deno.wait().expect("failed to wait for the child process"); assert!(status.success()); assert!(bundle.is_file()); // Now we try to use that bundle from another module. let test = t.path().join("test.js"); std::fs::write( &test, " import { printHello3 } from \"./mod1.bundle.js\"; printHello3(); ", ) .expect("error writing file"); let output = util::deno_cmd() .current_dir(util::root_path()) .arg("run") .arg(&test) .output() .expect("failed to spawn script"); // check the output of the test.ts program. assert!(std::str::from_utf8(&output.stdout) .unwrap() .trim() .ends_with("Hello")); assert_eq!(output.stderr, b""); } #[test] fn bundle_circular() { // First we have to generate a bundle of some module that has exports. let circular1 = util::root_path().join("cli/tests/subdir/circular1.ts"); assert!(circular1.is_file()); let t = TempDir::new().expect("tempdir fail"); let bundle = t.path().join("circular1.bundle.js"); let mut deno = util::deno_cmd() .current_dir(util::root_path()) .arg("bundle") .arg(circular1) .arg(&bundle) .spawn() .expect("failed to spawn script"); let status = deno.wait().expect("failed to wait for the child process"); assert!(status.success()); assert!(bundle.is_file()); let output = util::deno_cmd() .current_dir(util::root_path()) .arg("run") .arg(&bundle) .output() .expect("failed to spawn script"); // check the output of the the bundle program. assert!(std::str::from_utf8(&output.stdout) .unwrap() .trim() .ends_with("f1\nf2")); assert_eq!(output.stderr, b""); } #[test] fn bundle_single_module() { // First we have to generate a bundle of some module that has exports. let single_module = util::root_path().join("cli/tests/subdir/single_module.ts"); assert!(single_module.is_file()); let t = TempDir::new().expect("tempdir fail"); let bundle = t.path().join("single_module.bundle.js"); let mut deno = util::deno_cmd() .current_dir(util::root_path()) .arg("bundle") .arg(single_module) .arg(&bundle) .spawn() .expect("failed to spawn script"); let status = deno.wait().expect("failed to wait for the child process"); assert!(status.success()); assert!(bundle.is_file()); let output = util::deno_cmd() .current_dir(util::root_path()) .arg("run") .arg("--reload") .arg(&bundle) .output() .expect("failed to spawn script"); // check the output of the the bundle program. assert!(std::str::from_utf8(&output.stdout) .unwrap() .trim() .ends_with("Hello world!")); assert_eq!(output.stderr, b""); } #[test] fn bundle_tla() { // First we have to generate a bundle of some module that has exports. let tla_import = util::root_path().join("cli/tests/subdir/tla.ts"); assert!(tla_import.is_file()); let t = tempfile::TempDir::new().expect("tempdir fail"); let bundle = t.path().join("tla.bundle.js"); let mut deno = util::deno_cmd() .current_dir(util::root_path()) .arg("bundle") .arg(tla_import) .arg(&bundle) .spawn() .expect("failed to spawn script"); let status = deno.wait().expect("failed to wait for the child process"); assert!(status.success()); assert!(bundle.is_file()); // Now we try to use that bundle from another module. let test = t.path().join("test.js"); std::fs::write( &test, " import { foo } from \"./tla.bundle.js\"; console.log(foo); ", ) .expect("error writing file"); let output = util::deno_cmd() .current_dir(util::root_path()) .arg("run") .arg(&test) .output() .expect("failed to spawn script"); // check the output of the test.ts program. assert!(std::str::from_utf8(&output.stdout) .unwrap() .trim() .ends_with("Hello")); assert_eq!(output.stderr, b""); } #[test] fn bundle_js() { // First we have to generate a bundle of some module that has exports. let mod6 = util::root_path().join("cli/tests/subdir/mod6.js"); assert!(mod6.is_file()); let t = TempDir::new().expect("tempdir fail"); let bundle = t.path().join("mod6.bundle.js"); let mut deno = util::deno_cmd() .current_dir(util::root_path()) .arg("bundle") .arg(mod6) .arg(&bundle) .spawn() .expect("failed to spawn script"); let status = deno.wait().expect("failed to wait for the child process"); assert!(status.success()); assert!(bundle.is_file()); let output = util::deno_cmd() .current_dir(util::root_path()) .arg("run") .arg(&bundle) .output() .expect("failed to spawn script"); // check that nothing went to stderr assert_eq!(output.stderr, b""); } #[test] fn bundle_dynamic_import() { let dynamic_import = util::root_path().join("cli/tests/subdir/subdir2/dynamic_import.ts"); assert!(dynamic_import.is_file()); let t = TempDir::new().expect("tempdir fail"); let bundle = t.path().join("dynamic_import.bundle.js"); let mut deno = util::deno_cmd() .current_dir(util::root_path()) .arg("bundle") .arg(dynamic_import) .arg(&bundle) .spawn() .expect("failed to spawn script"); let status = deno.wait().expect("failed to wait for the child process"); assert!(status.success()); assert!(bundle.is_file()); let output = util::deno_cmd() .current_dir(util::root_path()) .arg("run") .arg(&bundle) .output() .expect("failed to spawn script"); // check the output of the test.ts program. assert!(std::str::from_utf8(&output.stdout) .unwrap() .trim() .ends_with("Hello")); assert_eq!(output.stderr, b""); } #[test] fn bundle_import_map() { let import = util::root_path().join("cli/tests/bundle_im.ts"); let import_map_path = util::root_path().join("cli/tests/bundle_im.json"); assert!(import.is_file()); let t = TempDir::new().expect("tempdir fail"); let bundle = t.path().join("import_map.bundle.js"); let mut deno = util::deno_cmd() .current_dir(util::root_path()) .arg("bundle") .arg("--importmap") .arg(import_map_path) .arg("--unstable") .arg(import) .arg(&bundle) .spawn() .expect("failed to spawn script"); let status = deno.wait().expect("failed to wait for the child process"); assert!(status.success()); assert!(bundle.is_file()); // Now we try to use that bundle from another module. let test = t.path().join("test.js"); std::fs::write( &test, " import { printHello3 } from \"./import_map.bundle.js\"; printHello3(); ", ) .expect("error writing file"); let output = util::deno_cmd() .current_dir(util::root_path()) .arg("run") .arg(&test) .output() .expect("failed to spawn script"); // check the output of the test.ts program. assert!(std::str::from_utf8(&output.stdout) .unwrap() .trim() .ends_with("Hello")); assert_eq!(output.stderr, b""); } #[test] fn repl_test_console_log() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["console.log('hello')", "'world'"]), Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), false, ); assert!(out.ends_with("hello\nundefined\nworld\n")); assert!(err.is_empty()); } #[test] fn repl_cwd() { let (_out, err) = util::run_and_collect_output( true, "repl", Some(vec!["Deno.cwd()"]), Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), false, ); assert!(err.is_empty()); } #[test] fn repl_test_eof() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["1 + 2"]), Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), false, ); assert!(out.ends_with("3\n")); assert!(err.is_empty()); } #[test] fn repl_test_strict() { let (_, err) = util::run_and_collect_output( true, "repl", Some(vec![ "let a = {};", "Object.preventExtensions(a);", "a.c = 1;", ]), None, false, ); assert!(err.contains( "Uncaught TypeError: Cannot add property c, object is not extensible" )); } const REPL_MSG: &str = "exit using ctrl+d or close()\n"; #[test] fn repl_test_close_command() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["close()", "'ignored'"]), None, false, ); assert!(!out.contains("ignored")); assert!(err.is_empty()); } #[test] fn repl_test_function() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["Deno.writeFileSync"]), Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), false, ); assert!(out.ends_with("[Function: writeFileSync]\n")); assert!(err.is_empty()); } #[test] fn repl_test_multiline() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["(\n1 + 2\n)"]), Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), false, ); assert!(out.ends_with("3\n")); assert!(err.is_empty()); } #[test] fn repl_test_eval_unterminated() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["eval('{')"]), None, false, ); assert!(out.ends_with(REPL_MSG)); assert!(err.contains("Unexpected end of input")); } #[test] fn repl_test_reference_error() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["not_a_variable"]), None, false, ); assert!(out.ends_with(REPL_MSG)); assert!(err.contains("not_a_variable is not defined")); } #[test] fn repl_test_syntax_error() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["syntax error"]), None, false, ); assert!(out.ends_with(REPL_MSG)); assert!(err.contains("Unexpected identifier")); } #[test] fn repl_test_type_error() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["console()"]), None, false, ); assert!(out.ends_with(REPL_MSG)); assert!(err.contains("console is not a function")); } #[test] fn repl_test_variable() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["var a = 123;", "a"]), Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), false, ); assert!(out.ends_with("undefined\n123\n")); assert!(err.is_empty()); } #[test] fn repl_test_lexical_scoped_variable() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["let a = 123;", "a"]), Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), false, ); assert!(out.ends_with("undefined\n123\n")); assert!(err.is_empty()); } #[test] fn repl_test_missing_deno_dir() { use std::fs::{read_dir, remove_dir_all}; const DENO_DIR: &str = "nonexistent"; let test_deno_dir = util::root_path().join("cli").join("tests").join(DENO_DIR); let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["1"]), Some(vec![ ("DENO_DIR".to_owned(), DENO_DIR.to_owned()), ("NO_COLOR".to_owned(), "1".to_owned()), ]), false, ); assert!(read_dir(&test_deno_dir).is_ok()); remove_dir_all(&test_deno_dir).unwrap(); assert!(out.ends_with("1\n")); assert!(err.is_empty()); } #[test] fn repl_test_save_last_eval() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["1", "_"]), Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), false, ); assert!(out.ends_with("1\n1\n")); assert!(err.is_empty()); } #[test] fn repl_test_save_last_thrown() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["throw 1", "_error"]), Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), false, ); assert!(out.ends_with("1\n")); assert_eq!(err, "Thrown: 1\n"); } #[test] fn repl_test_assign_underscore() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["_ = 1", "2", "_"]), Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), false, ); assert!( out.ends_with("Last evaluation result is no longer saved to _.\n1\n2\n1\n") ); assert!(err.is_empty()); } #[test] fn repl_test_assign_underscore_error() { let (out, err) = util::run_and_collect_output( true, "repl", Some(vec!["_error = 1", "throw 2", "_error"]), Some(vec![("NO_COLOR".to_owned(), "1".to_owned())]), false, ); assert!( out.ends_with("Last thrown error is no longer saved to _error.\n1\n1\n") ); assert_eq!(err, "Thrown: 2\n"); } #[test] fn util_test() { util::run_python_script("tools/util_test.py") } macro_rules! itest( ($name:ident {$( $key:ident: $value:expr,)*}) => { #[test] fn $name() { (util::CheckOutputIntegrationTest { $( $key: $value, )* .. Default::default() }).run() } } ); // Unfortunately #[ignore] doesn't work with itest! macro_rules! itest_ignore( ($name:ident {$( $key:ident: $value:expr,)*}) => { #[ignore] #[test] fn $name() { (util::CheckOutputIntegrationTest { $( $key: $value, )* .. Default::default() }).run() } } ); itest!(_001_hello { args: "run --reload 001_hello.js", output: "001_hello.js.out", }); itest!(_002_hello { args: "run --quiet --reload 002_hello.ts", output: "002_hello.ts.out", }); itest!(_003_relative_import { args: "run --quiet --reload 003_relative_import.ts", output: "003_relative_import.ts.out", }); itest!(_004_set_timeout { args: "run --quiet --reload 004_set_timeout.ts", output: "004_set_timeout.ts.out", }); itest!(_005_more_imports { args: "run --quiet --reload 005_more_imports.ts", output: "005_more_imports.ts.out", }); itest!(_006_url_imports { args: "run --quiet --reload 006_url_imports.ts", output: "006_url_imports.ts.out", http_server: true, }); itest!(_012_async { args: "run --quiet --reload 012_async.ts", output: "012_async.ts.out", }); itest!(_013_dynamic_import { args: "run --quiet --reload --allow-read 013_dynamic_import.ts", output: "013_dynamic_import.ts.out", }); itest!(_014_duplicate_import { args: "run --quiet --reload --allow-read 014_duplicate_import.ts ", output: "014_duplicate_import.ts.out", }); itest!(_015_duplicate_parallel_import { args: "run --quiet --reload --allow-read 015_duplicate_parallel_import.js", output: "015_duplicate_parallel_import.js.out", }); itest!(_016_double_await { args: "run --quiet --allow-read --reload 016_double_await.ts", output: "016_double_await.ts.out", }); itest!(_017_import_redirect { args: "run --quiet --reload 017_import_redirect.ts", output: "017_import_redirect.ts.out", }); itest!(_018_async_catch { args: "run --quiet --reload 018_async_catch.ts", output: "018_async_catch.ts.out", }); // TODO(ry) Re-enable flaky test https://github.com/denoland/deno/issues/4049 itest_ignore!(_019_media_types { args: "run --reload 019_media_types.ts", output: "019_media_types.ts.out", http_server: true, }); itest!(_020_json_modules { args: "run --reload 020_json_modules.ts", output: "020_json_modules.ts.out", exit_code: 1, }); itest!(_021_mjs_modules { args: "run --quiet --reload 021_mjs_modules.ts", output: "021_mjs_modules.ts.out", }); // TODO(ry) Re-enable flaky test https://github.com/denoland/deno/issues/4049 itest_ignore!(_022_info_flag_script { args: "info http://127.0.0.1:4545/cli/tests/019_media_types.ts", output: "022_info_flag_script.out", http_server: true, }); itest!(_023_no_ext_with_headers { args: "run --reload 023_no_ext_with_headers", output: "023_no_ext_with_headers.out", }); // FIXME(bartlomieju): this test should use remote file itest_ignore!(_024_import_no_ext_with_headers { args: "run --reload 024_import_no_ext_with_headers.ts", output: "024_import_no_ext_with_headers.ts.out", }); // TODO(lucacasonato): remove --unstable when permissions goes stable itest!(_025_hrtime { args: "run --quiet --allow-hrtime --unstable --reload 025_hrtime.ts", output: "025_hrtime.ts.out", }); itest!(_025_reload_js_type_error { args: "run --quiet --reload 025_reload_js_type_error.js", output: "025_reload_js_type_error.js.out", }); itest!(_026_redirect_javascript { args: "run --quiet --reload 026_redirect_javascript.js", output: "026_redirect_javascript.js.out", http_server: true, }); itest!(deno_test_fail_fast { args: "test --failfast test_runner_test.ts", exit_code: 1, output: "deno_test_fail_fast.out", }); itest!(deno_test { args: "test test_runner_test.ts", exit_code: 1, output: "deno_test.out", }); #[test] fn workers() { let g = util::http_server(); let status = util::deno_cmd() .current_dir(util::tests_path()) .arg("test") .arg("--reload") .arg("--allow-net") .arg("--allow-read") .arg("--unstable") .arg("workers_test.ts") .spawn() .unwrap() .wait() .unwrap(); assert!(status.success()); drop(g); } #[test] fn compiler_api() { let status = util::deno_cmd() .current_dir(util::tests_path()) .arg("test") .arg("--unstable") .arg("--reload") .arg("--allow-read") .arg("compiler_api_test.ts") .spawn() .unwrap() .wait() .unwrap(); assert!(status.success()); } itest!(_027_redirect_typescript { args: "run --quiet --reload 027_redirect_typescript.ts", output: "027_redirect_typescript.ts.out", http_server: true, }); itest!(_028_args { args: "run --quiet --reload 028_args.ts --arg1 val1 --arg2=val2 -- arg3 arg4", output: "028_args.ts.out", }); itest!(_029_eval { args: "eval console.log(\"hello\")", output: "029_eval.out", }); // Ugly parentheses due to whitespace delimiting problem. itest!(_030_eval_ts { args: "eval --quiet -T console.log((123)as(number))", // 'as' is a TS keyword only output: "030_eval_ts.out", }); itest!(_033_import_map { args: "run --quiet --reload --importmap=importmaps/import_map.json --unstable importmaps/test.ts", output: "033_import_map.out", }); itest!(import_map_no_unstable { args: "run --quiet --reload --importmap=importmaps/import_map.json importmaps/test.ts", output: "import_map_no_unstable.out", exit_code: 70, }); itest!(_034_onload { args: "run --quiet --reload 034_onload/main.ts", output: "034_onload.out", }); // TODO(ry) Re-enable flaky test https://github.com/denoland/deno/issues/4049 itest_ignore!(_035_cached_only_flag { args: "--reload --cached-only http://127.0.0.1:4545/cli/tests/019_media_types.ts", output: "035_cached_only_flag.out", exit_code: 1, http_server: true, }); itest!(_036_import_map_fetch { args: "cache --quiet --reload --importmap=importmaps/import_map.json --unstable importmaps/test.ts", output: "036_import_map_fetch.out", }); itest!(_037_fetch_multiple { args: "cache --reload fetch/test.ts fetch/other.ts", http_server: true, output: "037_fetch_multiple.out", }); itest!(_038_checkjs { // checking if JS file is run through TS compiler args: "run --reload --config 038_checkjs.tsconfig.json 038_checkjs.js", exit_code: 1, output: "038_checkjs.js.out", }); itest!(_041_dyn_import_eval { args: "eval import('./subdir/mod4.js').then(console.log)", output: "041_dyn_import_eval.out", }); itest!(_041_info_flag { args: "info", output: "041_info_flag.out", }); itest!(_042_dyn_import_evalcontext { args: "run --quiet --allow-read --reload 042_dyn_import_evalcontext.ts", output: "042_dyn_import_evalcontext.ts.out", }); itest!(_044_bad_resource { args: "run --quiet --reload --allow-read 044_bad_resource.ts", output: "044_bad_resource.ts.out", exit_code: 1, }); itest_ignore!(_045_proxy { args: "run --allow-net --allow-env --allow-run --reload 045_proxy_test.ts", output: "045_proxy_test.ts.out", http_server: true, }); itest!(_046_tsx { args: "run --quiet --reload 046_jsx_test.tsx", output: "046_jsx_test.tsx.out", }); itest!(_047_jsx { args: "run --quiet --reload 047_jsx_test.jsx", output: "047_jsx_test.jsx.out", }); // TODO(ry) Re-enable flaky test https://github.com/denoland/deno/issues/4049 itest_ignore!(_048_media_types_jsx { args: "run --reload 048_media_types_jsx.ts", output: "048_media_types_jsx.ts.out", http_server: true, }); // TODO(ry) Re-enable flaky test https://github.com/denoland/deno/issues/4049 itest_ignore!(_049_info_flag_script_jsx { args: "info http://127.0.0.1:4545/cli/tests/048_media_types_jsx.ts", output: "049_info_flag_script_jsx.out", http_server: true, }); // TODO(ry) Re-enable flaky test https://github.com/denoland/deno/issues/4049 itest_ignore!(_052_no_remote_flag { args: "--reload --no-remote http://127.0.0.1:4545/cli/tests/019_media_types.ts", output: "052_no_remote_flag.out", exit_code: 1, http_server: true, }); itest!(_054_info_local_imports { args: "info --quiet 005_more_imports.ts", output: "054_info_local_imports.out", exit_code: 0, }); itest!(_056_make_temp_file_write_perm { args: "run --quiet --allow-read --allow-write=./subdir/ 056_make_temp_file_write_perm.ts", output: "056_make_temp_file_write_perm.out", }); // TODO(lucacasonato): remove --unstable when permissions goes stable itest!(_057_revoke_permissions { args: "test -A --unstable 057_revoke_permissions.ts", output: "057_revoke_permissions.out", }); itest!(_058_tasks_microtasks_close { args: "run --quiet 058_tasks_microtasks_close.ts", output: "058_tasks_microtasks_close.ts.out", }); itest!(_059_fs_relative_path_perm { args: "run 059_fs_relative_path_perm.ts", output: "059_fs_relative_path_perm.ts.out", exit_code: 1, }); itest!(_060_deno_doc_displays_all_overloads_in_details_view { args: "doc 060_deno_doc_displays_all_overloads_in_details_view.ts NS.test", output: "060_deno_doc_displays_all_overloads_in_details_view.ts.out", }); itest!(js_import_detect { args: "run --quiet --reload js_import_detect.ts", output: "js_import_detect.ts.out", exit_code: 0, }); itest!(lock_write_fetch { args: "run --quiet --allow-read --allow-write --allow-env --allow-run lock_write_fetch.ts", output: "lock_write_fetch.ts.out", exit_code: 0, }); itest!(lock_check_ok { args: "run --lock=lock_check_ok.json http://127.0.0.1:4545/cli/tests/003_relative_import.ts", output: "003_relative_import.ts.out", http_server: true, }); // TODO(ry) Re-enable flaky test https://github.com/denoland/deno/issues/4049 itest_ignore!(lock_check_ok2 { args: "run 019_media_types.ts --lock=lock_check_ok2.json", output: "019_media_types.ts.out", http_server: true, }); itest!(lock_check_err { args: "run --lock=lock_check_err.json http://127.0.0.1:4545/cli/tests/003_relative_import.ts", output: "lock_check_err.out", exit_code: 10, http_server: true, }); // TODO(ry) Re-enable flaky test https://github.com/denoland/deno/issues/4049 itest_ignore!(lock_check_err2 { args: "run --lock=lock_check_err2.json 019_media_types.ts", output: "lock_check_err2.out", exit_code: 10, http_server: true, }); itest!(async_error { exit_code: 1, args: "run --reload async_error.ts", output: "async_error.ts.out", }); itest!(bundle { args: "bundle subdir/mod1.ts", output: "bundle.test.out", }); itest!(fmt_stdin { args: "fmt -", input: Some("const a = 1\n"), output_str: Some("const a = 1;\n"), }); itest!(fmt_stdin_check_formatted { args: "fmt --check -", input: Some("const a = 1;\n"), output_str: Some(""), }); itest!(fmt_stdin_check_not_formatted { args: "fmt --check -", input: Some("const a = 1\n"), output_str: Some("Not formatted stdin\n"), }); itest!(circular1 { args: "run --reload circular1.js", output: "circular1.js.out", }); itest!(config { args: "run --reload --config config.tsconfig.json config.ts", exit_code: 1, output: "config.ts.out", }); itest!(error_001 { args: "run --reload error_001.ts", exit_code: 1, output: "error_001.ts.out", }); itest!(error_002 { args: "run --reload error_002.ts", exit_code: 1, output: "error_002.ts.out", }); itest!(error_003_typescript { args: "run --reload error_003_typescript.ts", exit_code: 1, output: "error_003_typescript.ts.out", }); // Supposing that we've already attempted to run error_003_typescript.ts // we want to make sure that JS wasn't emitted. Running again without reload flag // should result in the same output. // https://github.com/denoland/deno/issues/2436 itest!(error_003_typescript2 { args: "run error_003_typescript.ts", exit_code: 1, output: "error_003_typescript.ts.out", }); itest!(error_004_missing_module { args: "run --reload error_004_missing_module.ts", exit_code: 1, output: "error_004_missing_module.ts.out", }); itest!(error_005_missing_dynamic_import { args: "run --reload --allow-read --quiet error_005_missing_dynamic_import.ts", exit_code: 1, output: "error_005_missing_dynamic_import.ts.out", }); itest!(error_006_import_ext_failure { args: "run --reload error_006_import_ext_failure.ts", exit_code: 1, output: "error_006_import_ext_failure.ts.out", }); itest!(error_007_any { args: "run --reload error_007_any.ts", exit_code: 1, output: "error_007_any.ts.out", }); itest!(error_008_checkjs { args: "run --reload error_008_checkjs.js", exit_code: 1, output: "error_008_checkjs.js.out", }); itest!(error_011_bad_module_specifier { args: "run --reload error_011_bad_module_specifier.ts", exit_code: 1, output: "error_011_bad_module_specifier.ts.out", }); itest!(error_012_bad_dynamic_import_specifier { args: "run --reload error_012_bad_dynamic_import_specifier.ts", exit_code: 1, output: "error_012_bad_dynamic_import_specifier.ts.out", }); itest!(error_013_missing_script { args: "run --reload missing_file_name", exit_code: 1, output: "error_013_missing_script.out", }); itest!(error_014_catch_dynamic_import_error { args: "run --reload --allow-read error_014_catch_dynamic_import_error.js", output: "error_014_catch_dynamic_import_error.js.out", }); itest!(error_015_dynamic_import_permissions { args: "run --reload --quiet error_015_dynamic_import_permissions.js", output: "error_015_dynamic_import_permissions.out", exit_code: 1, http_server: true, }); // We have an allow-net flag but not allow-read, it should still result in error. itest!(error_016_dynamic_import_permissions2 { args: "run --reload --allow-net error_016_dynamic_import_permissions2.js", output: "error_016_dynamic_import_permissions2.out", exit_code: 1, http_server: true, }); itest!(error_017_hide_long_source_ts { args: "run --reload error_017_hide_long_source_ts.ts", output: "error_017_hide_long_source_ts.ts.out", exit_code: 1, }); itest!(error_018_hide_long_source_js { args: "run error_018_hide_long_source_js.js", output: "error_018_hide_long_source_js.js.out", exit_code: 1, }); itest!(error_019_stack_function { args: "run error_019_stack_function.ts", output: "error_019_stack_function.ts.out", exit_code: 1, }); itest!(error_020_stack_constructor { args: "run error_020_stack_constructor.ts", output: "error_020_stack_constructor.ts.out", exit_code: 1, }); itest!(error_021_stack_method { args: "run error_021_stack_method.ts", output: "error_021_stack_method.ts.out", exit_code: 1, }); itest!(error_022_stack_custom_error { args: "run error_022_stack_custom_error.ts", output: "error_022_stack_custom_error.ts.out", exit_code: 1, }); itest!(error_023_stack_async { args: "run error_023_stack_async.ts", output: "error_023_stack_async.ts.out", exit_code: 1, }); itest!(error_024_stack_promise_all { args: "run error_024_stack_promise_all.ts", output: "error_024_stack_promise_all.ts.out", exit_code: 1, }); itest!(error_025_tab_indent { args: "run error_025_tab_indent", output: "error_025_tab_indent.out", exit_code: 1, }); itest!(error_syntax { args: "run --reload error_syntax.js", exit_code: 1, output: "error_syntax.js.out", }); itest!(error_syntax_empty_trailing_line { args: "run --reload error_syntax_empty_trailing_line.mjs", exit_code: 1, output: "error_syntax_empty_trailing_line.mjs.out", }); itest!(error_type_definitions { args: "run --reload error_type_definitions.ts", exit_code: 1, output: "error_type_definitions.ts.out", }); itest!(error_local_static_import_from_remote_ts { args: "run --reload http://localhost:4545/cli/tests/error_local_static_import_from_remote.ts", exit_code: 1, http_server: true, output: "error_local_static_import_from_remote.ts.out", }); itest!(error_local_static_import_from_remote_js { args: "run --reload http://localhost:4545/cli/tests/error_local_static_import_from_remote.js", exit_code: 1, http_server: true, output: "error_local_static_import_from_remote.js.out", }); itest!(exit_error42 { exit_code: 42, args: "run --quiet --reload exit_error42.ts", output: "exit_error42.ts.out", }); itest!(https_import { args: "run --quiet --reload https_import.ts", output: "https_import.ts.out", }); itest!(if_main { args: "run --quiet --reload if_main.ts", output: "if_main.ts.out", }); itest!(import_meta { args: "run --quiet --reload import_meta.ts", output: "import_meta.ts.out", }); itest!(main_module { args: "run --quiet --unstable --allow-read --reload main_module.ts", output: "main_module.ts.out", }); itest!(lib_ref { args: "run --quiet --unstable --reload lib_ref.ts", output: "lib_ref.ts.out", }); itest!(lib_runtime_api { args: "run --quiet --unstable --reload lib_runtime_api.ts", output: "lib_runtime_api.ts.out", }); itest!(seed_random { args: "run --seed=100 seed_random.js", output: "seed_random.js.out", }); itest!(type_definitions { args: "run --reload type_definitions.ts", output: "type_definitions.ts.out", }); itest!(type_definitions_for_export { args: "run --reload type_definitions_for_export.ts", output: "type_definitions_for_export.ts.out", exit_code: 1, }); itest!(type_directives_01 { args: "run --reload -L debug type_directives_01.ts", output: "type_directives_01.ts.out", http_server: true, }); itest!(type_directives_02 { args: "run --reload -L debug type_directives_02.ts", output: "type_directives_02.ts.out", }); itest!(type_directives_js_main { args: "run --reload -L debug type_directives_js_main.js", output: "type_directives_js_main.js.out", exit_code: 0, }); itest!(type_directives_redirect { args: "run --reload type_directives_redirect.ts", output: "type_directives_redirect.ts.out", http_server: true, }); itest!(ts_type_imports { args: "run --reload ts_type_imports.ts", output: "ts_type_imports.ts.out", exit_code: 1, }); itest!(ts_decorators { args: "run --reload -c tsconfig.decorators.json ts_decorators.ts", output: "ts_decorators.ts.out", }); itest!(swc_syntax_error { args: "run --reload swc_syntax_error.ts", output: "swc_syntax_error.ts.out", exit_code: 1, }); itest!(types { args: "types", output: "types.out", }); itest!(unbuffered_stderr { args: "run --reload unbuffered_stderr.ts", output: "unbuffered_stderr.ts.out", }); itest!(unbuffered_stdout { args: "run --quiet --reload unbuffered_stdout.ts", output: "unbuffered_stdout.ts.out", }); // Cannot write the expression to evaluate as "console.log(typeof gc)" // because itest! splits args on whitespace. itest!(eval_v8_flags { args: "eval --v8-flags=--expose-gc console.log(typeof(gc))", output: "v8_flags.js.out", }); itest!(run_v8_flags { args: "run --v8-flags=--expose-gc v8_flags.js", output: "v8_flags.js.out", }); itest!(run_v8_help { args: "repl --v8-flags=--help", output: "v8_help.out", }); itest!(unsupported_dynamic_import_scheme { args: "eval import('xxx:')", output: "unsupported_dynamic_import_scheme.out", exit_code: 1, }); itest!(wasm { args: "run --quiet wasm.ts", output: "wasm.ts.out", }); itest!(wasm_async { args: "run wasm_async.js", output: "wasm_async.out", }); itest!(top_level_await { args: "run --allow-read top_level_await.js", output: "top_level_await.out", }); itest!(top_level_await_ts { args: "run --quiet --allow-read top_level_await.ts", output: "top_level_await.out", }); itest!(top_level_for_await { args: "run --quiet top_level_for_await.js", output: "top_level_for_await.out", }); itest!(top_level_for_await_ts { args: "run --quiet top_level_for_await.ts", output: "top_level_for_await.out", }); itest!(unstable_disabled { args: "run --reload unstable.ts", exit_code: 1, output: "unstable_disabled.out", }); itest!(unstable_enabled { args: "run --quiet --reload --unstable unstable.ts", output: "unstable_enabled.out", }); itest!(unstable_disabled_js { args: "run --reload unstable.js", output: "unstable_disabled_js.out", }); itest!(unstable_enabled_js { args: "run --quiet --reload --unstable unstable.ts", output: "unstable_enabled_js.out", }); itest!(_053_import_compression { args: "run --quiet --reload --allow-net 053_import_compression/main.ts", output: "053_import_compression.out", http_server: true, }); itest!(cafile_url_imports { args: "run --quiet --reload --cert tls/RootCA.pem cafile_url_imports.ts", output: "cafile_url_imports.ts.out", http_server: true, }); itest!(cafile_ts_fetch { args: "run --quiet --reload --allow-net --cert tls/RootCA.pem cafile_ts_fetch.ts", output: "cafile_ts_fetch.ts.out", http_server: true, }); itest!(cafile_eval { args: "eval --cert tls/RootCA.pem fetch('https://localhost:5545/cli/tests/cafile_ts_fetch.ts.out').then(r=>r.text()).then(t=>console.log(t.trimEnd()))", output: "cafile_ts_fetch.ts.out", http_server: true, }); itest_ignore!(cafile_info { args: "info --cert tls/RootCA.pem https://localhost:5545/cli/tests/cafile_info.ts", output: "cafile_info.ts.out", http_server: true, }); itest!(disallow_http_from_https_js { args: "run --quiet --reload --cert tls/RootCA.pem https://localhost:5545/cli/tests/disallow_http_from_https.js", output: "disallow_http_from_https_js.out", http_server: true, exit_code: 1, }); itest!(disallow_http_from_https_ts { args: "run --quiet --reload --cert tls/RootCA.pem https://localhost:5545/cli/tests/disallow_http_from_https.ts", output: "disallow_http_from_https_ts.out", http_server: true, exit_code: 1, }); itest!(tsx_imports { args: "run --reload tsx_imports.ts", output: "tsx_imports.ts.out", }); itest!(fix_js_import_js { args: "run --quiet --reload fix_js_import_js.ts", output: "fix_js_import_js.ts.out", }); itest!(fix_js_imports { args: "run --quiet --reload fix_js_imports.ts", output: "fix_js_imports.ts.out", }); itest!(es_private_fields { args: "run --quiet --reload es_private_fields.js", output: "es_private_fields.js.out", }); itest!(cjs_imports { args: "run --quiet --reload cjs_imports.ts", output: "cjs_imports.ts.out", }); itest!(ts_import_from_js { args: "run --quiet --reload ts_import_from_js.js", output: "ts_import_from_js.js.out", http_server: true, }); itest!(single_compile_with_reload { args: "run --reload --allow-read single_compile_with_reload.ts", output: "single_compile_with_reload.ts.out", }); itest!(proto_exploit { args: "run proto_exploit.js", output: "proto_exploit.js.out", }); itest!(deno_lint { args: "lint --unstable lint/file1.js lint/file2.ts lint/ignored_file.ts", output: "lint/expected.out", exit_code: 1, }); itest!(deno_lint_glob { args: "lint --unstable lint/", output: "lint/expected_glob.out", exit_code: 1, }); #[test] fn cafile_fetch() { use url::Url; let g = util::http_server(); let deno_dir = TempDir::new().expect("tempdir fail"); let module_url = Url::parse("http://localhost:4545/cli/tests/cafile_url_imports.ts") .unwrap(); let cafile = util::root_path().join("cli/tests/tls/RootCA.pem"); let output = Command::new(util::deno_exe_path()) .env("DENO_DIR", deno_dir.path()) .current_dir(util::root_path()) .arg("cache") .arg("--cert") .arg(cafile) .arg(module_url.to_string()) .output() .expect("Failed to spawn script"); assert!(output.status.success()); let out = std::str::from_utf8(&output.stdout).unwrap(); assert_eq!(out, ""); drop(g); } #[test] fn cafile_install_remote_module() { let g = util::http_server(); let temp_dir = TempDir::new().expect("tempdir fail"); let bin_dir = temp_dir.path().join("bin"); std::fs::create_dir(&bin_dir).unwrap(); let deno_dir = TempDir::new().expect("tempdir fail"); let cafile = util::root_path().join("cli/tests/tls/RootCA.pem"); let install_output = Command::new(util::deno_exe_path()) .env("DENO_DIR", deno_dir.path()) .current_dir(util::root_path()) .arg("install") .arg("--cert") .arg(cafile) .arg("--root") .arg(temp_dir.path()) .arg("-n") .arg("echo_test") .arg("https://localhost:5545/cli/tests/echo.ts") .output() .expect("Failed to spawn script"); assert!(install_output.status.success()); let mut echo_test_path = bin_dir.join("echo_test"); if cfg!(windows) { echo_test_path = echo_test_path.with_extension("cmd"); } assert!(echo_test_path.exists()); let output = Command::new(echo_test_path) .current_dir(temp_dir.path()) .arg("foo") .env("PATH", util::target_dir()) .output() .expect("failed to spawn script"); let stdout = std::str::from_utf8(&output.stdout).unwrap().trim(); assert!(stdout.ends_with("foo")); drop(deno_dir); drop(temp_dir); drop(g) } #[test] fn cafile_bundle_remote_exports() { let g = util::http_server(); // First we have to generate a bundle of some remote module that has exports. let mod1 = "https://localhost:5545/cli/tests/subdir/mod1.ts"; let cafile = util::root_path().join("cli/tests/tls/RootCA.pem"); let t = TempDir::new().expect("tempdir fail"); let bundle = t.path().join("mod1.bundle.js"); let mut deno = util::deno_cmd() .current_dir(util::root_path()) .arg("bundle") .arg("--cert") .arg(cafile) .arg(mod1) .arg(&bundle) .spawn() .expect("failed to spawn script"); let status = deno.wait().expect("failed to wait for the child process"); assert!(status.success()); assert!(bundle.is_file()); // Now we try to use that bundle from another module. let test = t.path().join("test.js"); std::fs::write( &test, " import { printHello3 } from \"./mod1.bundle.js\"; printHello3(); ", ) .expect("error writing file"); let output = util::deno_cmd() .current_dir(util::root_path()) .arg("run") .arg(&test) .output() .expect("failed to spawn script"); // check the output of the test.ts program. assert!(std::str::from_utf8(&output.stdout) .unwrap() .trim() .ends_with("Hello")); assert_eq!(output.stderr, b""); drop(g) } #[test] fn test_permissions_with_allow() { for permission in &util::PERMISSION_VARIANTS { let status = util::deno_cmd() .current_dir(&util::tests_path()) .arg("run") .arg(format!("--allow-{0}", permission)) .arg("permission_test.ts") .arg(format!("{0}Required", permission)) .spawn() .unwrap() .wait() .unwrap(); assert!(status.success()); } } #[test] fn test_permissions_without_allow() { for permission in &util::PERMISSION_VARIANTS { let (_, err) = util::run_and_collect_output( false, &format!("run permission_test.ts {0}Required", permission), None, None, false, ); assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); } } #[test] fn test_permissions_rw_inside_project_dir() { const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; for permission in &PERMISSION_VARIANTS { let status = util::deno_cmd() .current_dir(&util::tests_path()) .arg("run") .arg(format!( "--allow-{0}={1}", permission, util::root_path().into_os_string().into_string().unwrap() )) .arg("complex_permissions_test.ts") .arg(permission) .arg("complex_permissions_test.ts") .spawn() .unwrap() .wait() .unwrap(); assert!(status.success()); } } #[test] fn test_permissions_rw_outside_test_dir() { const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; for permission in &PERMISSION_VARIANTS { let (_, err) = util::run_and_collect_output( false, &format!( "run --allow-{0}={1} complex_permissions_test.ts {0} {2}", permission, util::root_path() .join("cli") .join("tests") .into_os_string() .into_string() .unwrap(), util::root_path() .join("Cargo.toml") .into_os_string() .into_string() .unwrap(), ), None, None, false, ); assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); } } #[test] fn test_permissions_rw_inside_test_dir() { const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; for permission in &PERMISSION_VARIANTS { let status = util::deno_cmd() .current_dir(&util::tests_path()) .arg("run") .arg(format!( "--allow-{0}={1}", permission, util::root_path() .join("cli") .join("tests") .into_os_string() .into_string() .unwrap() )) .arg("complex_permissions_test.ts") .arg(permission) .arg("complex_permissions_test.ts") .spawn() .unwrap() .wait() .unwrap(); assert!(status.success()); } } #[test] fn test_permissions_rw_outside_test_and_js_dir() { const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; let test_dir = util::root_path() .join("cli") .join("tests") .into_os_string() .into_string() .unwrap(); let js_dir = util::root_path() .join("js") .into_os_string() .into_string() .unwrap(); for permission in &PERMISSION_VARIANTS { let (_, err) = util::run_and_collect_output( false, &format!( "run --allow-{0}={1},{2} complex_permissions_test.ts {0} {3}", permission, test_dir, js_dir, util::root_path() .join("Cargo.toml") .into_os_string() .into_string() .unwrap(), ), None, None, false, ); assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); } } #[test] fn test_permissions_rw_inside_test_and_js_dir() { const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; let test_dir = util::root_path() .join("cli") .join("tests") .into_os_string() .into_string() .unwrap(); let js_dir = util::root_path() .join("js") .into_os_string() .into_string() .unwrap(); for permission in &PERMISSION_VARIANTS { let status = util::deno_cmd() .current_dir(&util::tests_path()) .arg("run") .arg(format!("--allow-{0}={1},{2}", permission, test_dir, js_dir)) .arg("complex_permissions_test.ts") .arg(permission) .arg("complex_permissions_test.ts") .spawn() .unwrap() .wait() .unwrap(); assert!(status.success()); } } #[test] fn test_permissions_rw_relative() { const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; for permission in &PERMISSION_VARIANTS { let status = util::deno_cmd() .current_dir(&util::tests_path()) .arg("run") .arg(format!("--allow-{0}=.", permission)) .arg("complex_permissions_test.ts") .arg(permission) .arg("complex_permissions_test.ts") .spawn() .unwrap() .wait() .unwrap(); assert!(status.success()); } } #[test] fn test_permissions_rw_no_prefix() { const PERMISSION_VARIANTS: [&str; 2] = ["read", "write"]; for permission in &PERMISSION_VARIANTS { let status = util::deno_cmd() .current_dir(&util::tests_path()) .arg("run") .arg(format!("--allow-{0}=tls/../", permission)) .arg("complex_permissions_test.ts") .arg(permission) .arg("complex_permissions_test.ts") .spawn() .unwrap() .wait() .unwrap(); assert!(status.success()); } } #[test] fn test_permissions_net_fetch_allow_localhost_4545() { let (_, err) = util::run_and_collect_output( true, "run --allow-net=localhost:4545 complex_permissions_test.ts netFetch http://localhost:4545/", None, None, true, ); assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); } #[test] fn test_permissions_net_fetch_allow_deno_land() { let (_, err) = util::run_and_collect_output( false, "run --allow-net=deno.land complex_permissions_test.ts netFetch http://localhost:4545/", None, None, true, ); assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); } #[test] fn test_permissions_net_fetch_localhost_4545_fail() { let (_, err) = util::run_and_collect_output( false, "run --allow-net=localhost:4545 complex_permissions_test.ts netFetch http://localhost:4546/", None, None, true, ); assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); } #[test] fn test_permissions_net_fetch_localhost() { let (_, err) = util::run_and_collect_output( true, "run --allow-net=localhost complex_permissions_test.ts netFetch http://localhost:4545/ http://localhost:4546/ http://localhost:4547/", None, None, true, ); assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); } #[test] fn test_permissions_net_connect_allow_localhost_ip_4555() { let (_, err) = util::run_and_collect_output( true, "run --allow-net=127.0.0.1:4545 complex_permissions_test.ts netConnect 127.0.0.1:4545", None, None, true, ); assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); } #[test] fn test_permissions_net_connect_allow_deno_land() { let (_, err) = util::run_and_collect_output( false, "run --allow-net=deno.land complex_permissions_test.ts netConnect 127.0.0.1:4546", None, None, true, ); assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); } #[test] fn test_permissions_net_connect_allow_localhost_ip_4545_fail() { let (_, err) = util::run_and_collect_output( false, "run --allow-net=127.0.0.1:4545 complex_permissions_test.ts netConnect 127.0.0.1:4546", None, None, true, ); assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); } #[test] fn test_permissions_net_connect_allow_localhost_ip() { let (_, err) = util::run_and_collect_output( true, "run --allow-net=127.0.0.1 complex_permissions_test.ts netConnect 127.0.0.1:4545 127.0.0.1:4546 127.0.0.1:4547", None, None, true, ); assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); } #[test] fn test_permissions_net_listen_allow_localhost_4555() { let (_, err) = util::run_and_collect_output( true, "run --allow-net=localhost:4558 complex_permissions_test.ts netListen localhost:4558", None, None, false, ); assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); } #[test] fn test_permissions_net_listen_allow_deno_land() { let (_, err) = util::run_and_collect_output( false, "run --allow-net=deno.land complex_permissions_test.ts netListen localhost:4545", None, None, false, ); assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); } #[test] fn test_permissions_net_listen_allow_localhost_4555_fail() { let (_, err) = util::run_and_collect_output( false, "run --allow-net=localhost:4555 complex_permissions_test.ts netListen localhost:4556", None, None, false, ); assert!(err.contains(util::PERMISSION_DENIED_PATTERN)); } #[test] fn test_permissions_net_listen_allow_localhost() { // Port 4600 is chosen to not colide with those used by tools/http_server.py let (_, err) = util::run_and_collect_output( true, "run --allow-net=localhost complex_permissions_test.ts netListen localhost:4600", None, None, false, ); assert!(!err.contains(util::PERMISSION_DENIED_PATTERN)); } fn inspect_flag_with_unique_port(flag_prefix: &str) -> String { use std::sync::atomic::{AtomicU16, Ordering}; static PORT: AtomicU16 = AtomicU16::new(9229); let port = PORT.fetch_add(1, Ordering::Relaxed); format!("{}=127.0.0.1:{}", flag_prefix, port) } fn extract_ws_url_from_stderr( stderr_lines: &mut impl std::iter::Iterator<Item = String>, ) -> url::Url { let stderr_first_line = stderr_lines.next().unwrap(); assert!(stderr_first_line.starts_with("Debugger listening on ")); let v: Vec<_> = stderr_first_line.match_indices("ws:").collect(); assert_eq!(v.len(), 1); let ws_url_index = v[0].0; let ws_url = &stderr_first_line[ws_url_index..]; url::Url::parse(ws_url).unwrap() } #[tokio::test] async fn inspector_connect() { let script = util::tests_path().join("inspector1.js"); let mut child = util::deno_cmd() .arg("run") .arg(inspect_flag_with_unique_port("--inspect")) .arg(script) .stderr(std::process::Stdio::piped()) .spawn() .unwrap(); let stderr = child.stderr.as_mut().unwrap(); let mut stderr_lines = std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); // We use tokio_tungstenite as a websocket client because warp (which is // a dependency of Deno) uses it. let (_socket, response) = tokio_tungstenite::connect_async(ws_url) .await .expect("Can't connect"); assert_eq!("101 Switching Protocols", response.status().to_string()); child.kill().unwrap(); child.wait().unwrap(); } enum TestStep { StdOut(&'static str), StdErr(&'static str), WsRecv(&'static str), WsSend(&'static str), } #[tokio::test] async fn inspector_break_on_first_line() { let script = util::tests_path().join("inspector2.js"); let mut child = util::deno_cmd() .arg("run") .arg(inspect_flag_with_unique_port("--inspect-brk")) .arg(script) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .spawn() .unwrap(); let stderr = child.stderr.as_mut().unwrap(); let mut stderr_lines = std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); let (socket, response) = tokio_tungstenite::connect_async(ws_url) .await .expect("Can't connect"); assert_eq!(response.status(), 101); // Switching protocols. let (mut socket_tx, socket_rx) = socket.split(); let mut socket_rx = socket_rx.map(|msg| msg.unwrap().to_string()).filter(|msg| { let pass = !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#); futures::future::ready(pass) }); let stdout = child.stdout.as_mut().unwrap(); let mut stdout_lines = std::io::BufReader::new(stdout).lines().map(|r| r.unwrap()); use TestStep::*; let test_steps = vec![ WsSend(r#"{"id":1,"method":"Runtime.enable"}"#), WsSend(r#"{"id":2,"method":"Debugger.enable"}"#), WsRecv( r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, ), WsRecv(r#"{"id":1,"result":{}}"#), WsRecv(r#"{"id":2,"result":{"debuggerId":"#), WsSend(r#"{"id":3,"method":"Runtime.runIfWaitingForDebugger"}"#), WsRecv(r#"{"id":3,"result":{}}"#), WsRecv(r#"{"method":"Debugger.paused","#), WsSend( r#"{"id":4,"method":"Runtime.evaluate","params":{"expression":"Deno.core.print(\"hello from the inspector\\n\")","contextId":1,"includeCommandLineAPI":true,"silent":false,"returnByValue":true}}"#, ), WsRecv(r#"{"id":4,"result":{"result":{"type":"undefined"}}}"#), StdOut("hello from the inspector"), WsSend(r#"{"id":5,"method":"Debugger.resume"}"#), WsRecv(r#"{"id":5,"result":{}}"#), StdOut("hello from the script"), ]; for step in test_steps { match step { StdOut(s) => assert_eq!(&stdout_lines.next().unwrap(), s), WsRecv(s) => assert!(socket_rx.next().await.unwrap().starts_with(s)), WsSend(s) => socket_tx.send(s.into()).await.unwrap(), _ => unreachable!(), } } child.kill().unwrap(); child.wait().unwrap(); } #[tokio::test] async fn inspector_pause() { let script = util::tests_path().join("inspector1.js"); let mut child = util::deno_cmd() .arg("run") .arg(inspect_flag_with_unique_port("--inspect")) .arg(script) .stderr(std::process::Stdio::piped()) .spawn() .unwrap(); let stderr = child.stderr.as_mut().unwrap(); let mut stderr_lines = std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); // We use tokio_tungstenite as a websocket client because warp (which is // a dependency of Deno) uses it. let (mut socket, _) = tokio_tungstenite::connect_async(ws_url) .await .expect("Can't connect"); /// Returns the next websocket message as a string ignoring /// Debugger.scriptParsed messages. async fn ws_read_msg( socket: &mut tokio_tungstenite::WebSocketStream<tokio::net::TcpStream>, ) -> String { use futures::stream::StreamExt; while let Some(msg) = socket.next().await { let msg = msg.unwrap().to_string(); assert!(!msg.contains("error")); if !msg.contains("Debugger.scriptParsed") { return msg; } } unreachable!() } socket .send(r#"{"id":6,"method":"Debugger.enable"}"#.into()) .await .unwrap(); let msg = ws_read_msg(&mut socket).await; println!("response msg 1 {}", msg); assert!(msg.starts_with(r#"{"id":6,"result":{"debuggerId":"#)); socket .send(r#"{"id":31,"method":"Debugger.pause"}"#.into()) .await .unwrap(); let msg = ws_read_msg(&mut socket).await; println!("response msg 2 {}", msg); assert_eq!(msg, r#"{"id":31,"result":{}}"#); child.kill().unwrap(); } #[tokio::test] async fn inspector_port_collision() { let script = util::tests_path().join("inspector1.js"); let inspect_flag = inspect_flag_with_unique_port("--inspect"); let mut child1 = util::deno_cmd() .arg("run") .arg(&inspect_flag) .arg(script.clone()) .stderr(std::process::Stdio::piped()) .spawn() .unwrap(); let stderr_1 = child1.stderr.as_mut().unwrap(); let mut stderr_lines_1 = std::io::BufReader::new(stderr_1) .lines() .map(|r| r.unwrap()); let _ = extract_ws_url_from_stderr(&mut stderr_lines_1); let mut child2 = util::deno_cmd() .arg("run") .arg(&inspect_flag) .arg(script) .stderr(std::process::Stdio::piped()) .spawn() .unwrap(); use std::io::Read; let mut stderr_str_2 = String::new(); child2 .stderr .as_mut() .unwrap() .read_to_string(&mut stderr_str_2) .unwrap(); assert!(stderr_str_2.contains("Cannot start inspector server")); child1.kill().unwrap(); child1.wait().unwrap(); child2.wait().unwrap(); } #[tokio::test] async fn inspector_does_not_hang() { let script = util::tests_path().join("inspector3.js"); let mut child = util::deno_cmd() .arg("run") .arg(inspect_flag_with_unique_port("--inspect-brk")) .env("NO_COLOR", "1") .arg(script) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .spawn() .unwrap(); let stderr = child.stderr.as_mut().unwrap(); let mut stderr_lines = std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); let (socket, response) = tokio_tungstenite::connect_async(ws_url) .await .expect("Can't connect"); assert_eq!(response.status(), 101); // Switching protocols. let (mut socket_tx, socket_rx) = socket.split(); let mut socket_rx = socket_rx.map(|msg| msg.unwrap().to_string()).filter(|msg| { let pass = !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#); futures::future::ready(pass) }); let stdout = child.stdout.as_mut().unwrap(); let mut stdout_lines = std::io::BufReader::new(stdout).lines().map(|r| r.unwrap()); use TestStep::*; let test_steps = vec![ WsSend(r#"{"id":1,"method":"Runtime.enable"}"#), WsSend(r#"{"id":2,"method":"Debugger.enable"}"#), WsRecv( r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, ), WsRecv(r#"{"id":1,"result":{}}"#), WsRecv(r#"{"id":2,"result":{"debuggerId":"#), WsSend(r#"{"id":3,"method":"Runtime.runIfWaitingForDebugger"}"#), WsRecv(r#"{"id":3,"result":{}}"#), WsRecv(r#"{"method":"Debugger.paused","#), WsSend(r#"{"id":4,"method":"Debugger.resume"}"#), WsRecv(r#"{"id":4,"result":{}}"#), WsRecv(r#"{"method":"Debugger.resumed","params":{}}"#), ]; for step in test_steps { match step { WsRecv(s) => assert!(socket_rx.next().await.unwrap().starts_with(s)), WsSend(s) => socket_tx.send(s.into()).await.unwrap(), _ => unreachable!(), } } for i in 0..128u32 { let request_id = i + 10; // Expect the number {i} on stdout. let s = format!("{}", i); assert_eq!(stdout_lines.next().unwrap(), s); // Expect hitting the `debugger` statement. let s = r#"{"method":"Debugger.paused","#; assert!(socket_rx.next().await.unwrap().starts_with(s)); // Send the 'Debugger.resume' request. let s = format!(r#"{{"id":{},"method":"Debugger.resume"}}"#, request_id); socket_tx.send(s.into()).await.unwrap(); // Expect confirmation of the 'Debugger.resume' request. let s = format!(r#"{{"id":{},"result":{{}}}}"#, request_id); assert_eq!(socket_rx.next().await.unwrap(), s); let s = r#"{"method":"Debugger.resumed","params":{}}"#; assert_eq!(socket_rx.next().await.unwrap(), s); } // Check that we can gracefully close the websocket connection. socket_tx.close().await.unwrap(); socket_rx.for_each(|_| async {}).await; assert_eq!(&stdout_lines.next().unwrap(), "done"); assert!(child.wait().unwrap().success()); } #[tokio::test] async fn inspector_without_brk_runs_code() { let script = util::tests_path().join("inspector4.js"); let mut child = util::deno_cmd() .arg("run") .arg(inspect_flag_with_unique_port("--inspect")) .arg(script) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .spawn() .unwrap(); let stderr = child.stderr.as_mut().unwrap(); let mut stderr_lines = std::io::BufReader::new(stderr).lines().map(|r| r.unwrap()); let _ = extract_ws_url_from_stderr(&mut stderr_lines); // Check that inspector actually runs code without waiting for inspector // connection. let stdout = child.stdout.as_mut().unwrap(); let mut stdout_lines = std::io::BufReader::new(stdout).lines().map(|r| r.unwrap()); let stdout_first_line = stdout_lines.next().unwrap(); assert_eq!(stdout_first_line, "hello"); child.kill().unwrap(); child.wait().unwrap(); } #[tokio::test] async fn inspector_runtime_evaluate_does_not_crash() { let mut child = util::deno_cmd() .arg("repl") .arg(inspect_flag_with_unique_port("--inspect")) .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .spawn() .unwrap(); let stderr = child.stderr.as_mut().unwrap(); let mut stderr_lines = std::io::BufReader::new(stderr) .lines() .map(|r| r.unwrap()) .filter(|s| s.as_str() != "Debugger session started."); let ws_url = extract_ws_url_from_stderr(&mut stderr_lines); let (socket, response) = tokio_tungstenite::connect_async(ws_url) .await .expect("Can't connect"); assert_eq!(response.status(), 101); // Switching protocols. let (mut socket_tx, socket_rx) = socket.split(); let mut socket_rx = socket_rx.map(|msg| msg.unwrap().to_string()).filter(|msg| { let pass = !msg.starts_with(r#"{"method":"Debugger.scriptParsed","#); futures::future::ready(pass) }); let stdin = child.stdin.take().unwrap(); let stdout = child.stdout.as_mut().unwrap(); let mut stdout_lines = std::io::BufReader::new(stdout) .lines() .map(|r| r.unwrap()) .filter(|s| !s.starts_with("Deno ")); use TestStep::*; let test_steps = vec![ WsSend(r#"{"id":1,"method":"Runtime.enable"}"#), WsSend(r#"{"id":2,"method":"Debugger.enable"}"#), WsRecv( r#"{"method":"Runtime.executionContextCreated","params":{"context":{"id":1,"#, ), WsRecv(r#"{"id":1,"result":{}}"#), WsRecv(r#"{"id":2,"result":{"debuggerId":"#), WsSend(r#"{"id":3,"method":"Runtime.runIfWaitingForDebugger"}"#), WsRecv(r#"{"id":3,"result":{}}"#), StdOut("exit using ctrl+d or close()"), WsSend( r#"{"id":4,"method":"Runtime.compileScript","params":{"expression":"Deno.cwd()","sourceURL":"","persistScript":false,"executionContextId":1}}"#, ), WsRecv(r#"{"id":4,"result":{}}"#), WsSend( r#"{"id":5,"method":"Runtime.evaluate","params":{"expression":"Deno.cwd()","objectGroup":"console","includeCommandLineAPI":true,"silent":false,"contextId":1,"returnByValue":true,"generatePreview":true,"userGesture":true,"awaitPromise":false,"replMode":true}}"#, ), WsRecv(r#"{"id":5,"result":{"result":{"type":"string","value":""#), WsSend( r#"{"id":6,"method":"Runtime.evaluate","params":{"expression":"console.error('done');","objectGroup":"console","includeCommandLineAPI":true,"silent":false,"contextId":1,"returnByValue":true,"generatePreview":true,"userGesture":true,"awaitPromise":false,"replMode":true}}"#, ), WsRecv(r#"{"id":6,"result":{"result":{"type":"undefined"}}}"#), StdErr("done"), ]; for step in test_steps { match step { StdOut(s) => assert_eq!(&stdout_lines.next().unwrap(), s), StdErr(s) => assert_eq!(&stderr_lines.next().unwrap(), s), WsRecv(s) => assert!(socket_rx.next().await.unwrap().starts_with(s)), WsSend(s) => socket_tx.send(s.into()).await.unwrap(), } } std::mem::drop(stdin); child.wait().unwrap(); } #[test] fn exec_path() { let output = util::deno_cmd() .current_dir(util::root_path()) .arg("run") .arg("--allow-read") .arg("cli/tests/exec_path.ts") .stdout(std::process::Stdio::piped()) .spawn() .unwrap() .wait_with_output() .unwrap(); assert!(output.status.success()); let stdout_str = std::str::from_utf8(&output.stdout).unwrap().trim(); let actual = std::fs::canonicalize(&std::path::Path::new(stdout_str)).unwrap(); let expected = std::fs::canonicalize(util::deno_exe_path()).unwrap(); assert_eq!(expected, actual); } mod util { use os_pipe::pipe; use regex::Regex; use std::io::Read; use std::io::Write; use std::path::PathBuf; use std::process::Child; use std::process::Command; use std::process::Output; use std::process::Stdio; use std::sync::Mutex; use std::sync::MutexGuard; use tempfile::TempDir; pub const PERMISSION_VARIANTS: [&str; 5] = ["read", "write", "env", "net", "run"]; pub const PERMISSION_DENIED_PATTERN: &str = "PermissionDenied"; lazy_static! { static ref DENO_DIR: TempDir = TempDir::new().expect("tempdir fail"); // STRIP_ANSI_RE and strip_ansi_codes are lifted from the "console" crate. // Copyright 2017 Armin Ronacher <armin.ronacher@active-4.com>. MIT License. static ref STRIP_ANSI_RE: Regex = Regex::new( r"[\x1b\x9b][\[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]" ).unwrap(); static ref GUARD: Mutex<()> = Mutex::new(()); } pub fn root_path() -> PathBuf { PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/..")) } pub fn tests_path() -> PathBuf { root_path().join("cli").join("tests") } pub fn target_dir() -> PathBuf { let current_exe = std::env::current_exe().unwrap(); let target_dir = current_exe.parent().unwrap().parent().unwrap(); println!("target_dir {}", target_dir.display()); target_dir.into() } pub fn deno_exe_path() -> PathBuf { // Something like /Users/rld/src/deno/target/debug/deps/deno let mut p = target_dir().join("deno"); if cfg!(windows) { p.set_extension("exe"); } p } pub struct HttpServerGuard<'a> { #[allow(dead_code)] g: MutexGuard<'a, ()>, child: Child, } impl<'a> Drop for HttpServerGuard<'a> { fn drop(&mut self) { match self.child.try_wait() { Ok(None) => { self.child.kill().expect("failed to kill http_server.py"); } Ok(Some(status)) => { panic!("http_server.py exited unexpectedly {}", status) } Err(e) => panic!("http_server.py err {}", e), } } } /// Starts tools/http_server.py when the returned guard is dropped, the server /// will be killed. pub fn http_server<'a>() -> HttpServerGuard<'a> { // TODO(bartlomieju) Allow tests to use the http server in parallel. let g = GUARD.lock().unwrap(); println!("tools/http_server.py starting..."); let mut child = Command::new("python") .current_dir(root_path()) .args(&["-u", "tools/http_server.py"]) .stdout(Stdio::piped()) .spawn() .expect("failed to execute child"); let stdout = child.stdout.as_mut().unwrap(); use std::io::{BufRead, BufReader}; let lines = BufReader::new(stdout).lines(); // Wait for "ready" on stdout. See tools/http_server.py for maybe_line in lines { if let Ok(line) = maybe_line { if line.starts_with("ready") { break; } } else { panic!(maybe_line.unwrap_err()); } } HttpServerGuard { child, g } } /// Helper function to strip ansi codes. pub fn strip_ansi_codes(s: &str) -> std::borrow::Cow<str> { STRIP_ANSI_RE.replace_all(s, "") } pub fn run_and_collect_output( expect_success: bool, args: &str, input: Option<Vec<&str>>, envs: Option<Vec<(String, String)>>, need_http_server: bool, ) -> (String, String) { let mut deno_process_builder = deno_cmd(); deno_process_builder .args(args.split_whitespace()) .current_dir(&tests_path()) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); if let Some(envs) = envs { deno_process_builder.envs(envs); } let http_guard = if need_http_server { Some(http_server()) } else { None }; let mut deno = deno_process_builder .spawn() .expect("failed to spawn script"); if let Some(lines) = input { let stdin = deno.stdin.as_mut().expect("failed to get stdin"); stdin .write_all(lines.join("\n").as_bytes()) .expect("failed to write to stdin"); } let Output { stdout, stderr, status, } = deno.wait_with_output().expect("failed to wait on child"); drop(http_guard); let stdout = String::from_utf8(stdout).unwrap(); let stderr = String::from_utf8(stderr).unwrap(); if expect_success != status.success() { eprintln!("stdout: <<<{}>>>", stdout); eprintln!("stderr: <<<{}>>>", stderr); panic!("Unexpected exit code: {:?}", status.code()); } (stdout, stderr) } pub fn deno_cmd() -> Command { let e = deno_exe_path(); assert!(e.exists()); let mut c = Command::new(e); c.env("DENO_DIR", DENO_DIR.path()); c } pub fn run_python_script(script: &str) { let output = Command::new("python") .env("DENO_DIR", DENO_DIR.path()) .current_dir(root_path()) .arg(script) .arg(format!("--build-dir={}", target_dir().display())) .arg(format!("--executable={}", deno_exe_path().display())) .output() .expect("failed to spawn script"); if !output.status.success() { let stdout = String::from_utf8(output.stdout).unwrap(); let stderr = String::from_utf8(output.stderr).unwrap(); panic!( "{} executed with failing error code\n{}{}", script, stdout, stderr ); } } #[derive(Debug, Default)] pub struct CheckOutputIntegrationTest { pub args: &'static str, pub output: &'static str, pub input: Option<&'static str>, pub output_str: Option<&'static str>, pub exit_code: i32, pub http_server: bool, } impl CheckOutputIntegrationTest { pub fn run(&self) { let args = self.args.split_whitespace(); let root = root_path(); let deno_exe = deno_exe_path(); println!("root path {}", root.display()); println!("deno_exe path {}", deno_exe.display()); let http_server_guard = if self.http_server { Some(http_server()) } else { None }; let (mut reader, writer) = pipe().unwrap(); let tests_dir = root.join("cli").join("tests"); let mut command = deno_cmd(); println!("deno_exe args {}", self.args); println!("deno_exe tests path {:?}", &tests_dir); command.args(args); command.current_dir(&tests_dir); command.stdin(Stdio::piped()); let writer_clone = writer.try_clone().unwrap(); command.stderr(writer_clone); command.stdout(writer); let mut process = command.spawn().expect("failed to execute process"); if let Some(input) = self.input { let mut p_stdin = process.stdin.take().unwrap(); write!(p_stdin, "{}", input).unwrap(); } // Very important when using pipes: This parent process is still // holding its copies of the write ends, and we have to close them // before we read, otherwise the read end will never report EOF. The // Command object owns the writers now, and dropping it closes them. drop(command); let mut actual = String::new(); reader.read_to_string(&mut actual).unwrap(); let status = process.wait().expect("failed to finish process"); let exit_code = status.code().unwrap(); drop(http_server_guard); actual = strip_ansi_codes(&actual).to_string(); if self.exit_code != exit_code { println!("OUTPUT\n{}\nOUTPUT", actual); panic!( "bad exit code, expected: {:?}, actual: {:?}", self.exit_code, exit_code ); } let expected = if let Some(s) = self.output_str { s.to_owned() } else { let output_path = tests_dir.join(self.output); println!("output path {}", output_path.display()); std::fs::read_to_string(output_path).expect("cannot read output") }; if !wildcard_match(&expected, &actual) { println!("OUTPUT\n{}\nOUTPUT", actual); println!("EXPECTED\n{}\nEXPECTED", expected); panic!("pattern match failed"); } } } fn wildcard_match(pattern: &str, s: &str) -> bool { pattern_match(pattern, s, "[WILDCARD]") } pub fn pattern_match(pattern: &str, s: &str, wildcard: &str) -> bool { // Normalize line endings let mut s = s.replace("\r\n", "\n"); let pattern = pattern.replace("\r\n", "\n"); if pattern == wildcard { return true; } let parts = pattern.split(wildcard).collect::<Vec<&str>>(); if parts.len() == 1 { return pattern == s; } if !s.starts_with(parts[0]) { return false; } // If the first line of the pattern is just a wildcard the newline character // needs to be pre-pended so it can safely match anything or nothing and // continue matching. if pattern.lines().next() == Some(wildcard) { s.insert_str(0, "\n"); } let mut t = s.split_at(parts[0].len()); for (i, part) in parts.iter().enumerate() { if i == 0 { continue; } dbg!(part, i); if i == parts.len() - 1 && (*part == "" || *part == "\n") { dbg!("exit 1 true", i); return true; } if let Some(found) = t.1.find(*part) { dbg!("found ", found); t = t.1.split_at(found + part.len()); } else { dbg!("exit false ", i); return false; } } dbg!("end ", t.1.len()); t.1.is_empty() } #[test] fn test_wildcard_match() { let fixtures = vec![ ("foobarbaz", "foobarbaz", true), ("[WILDCARD]", "foobarbaz", true), ("foobar", "foobarbaz", false), ("foo[WILDCARD]baz", "foobarbaz", true), ("foo[WILDCARD]baz", "foobazbar", false), ("foo[WILDCARD]baz[WILDCARD]qux", "foobarbazqatqux", true), ("foo[WILDCARD]", "foobar", true), ("foo[WILDCARD]baz[WILDCARD]", "foobarbazqat", true), // check with different line endings ("foo[WILDCARD]\nbaz[WILDCARD]\n", "foobar\nbazqat\n", true), ( "foo[WILDCARD]\nbaz[WILDCARD]\n", "foobar\r\nbazqat\r\n", true, ), ( "foo[WILDCARD]\r\nbaz[WILDCARD]\n", "foobar\nbazqat\r\n", true, ), ( "foo[WILDCARD]\r\nbaz[WILDCARD]\r\n", "foobar\nbazqat\n", true, ), ( "foo[WILDCARD]\r\nbaz[WILDCARD]\r\n", "foobar\r\nbazqat\r\n", true, ), ]; // Iterate through the fixture lists, testing each one for (pattern, string, expected) in fixtures { let actual = wildcard_match(pattern, string); dbg!(pattern, string, expected); assert_eq!(actual, expected); } } }
27.406105
279
0.641115
0910b878890cb569194238f104047080ab265e3f
44,135
use crate::prelude::*; macro intrinsic_pat { (_) => { _ }, ($name:ident) => { stringify!($name) }, ($name:literal) => { stringify!($name) }, ($x:ident . $($xs:tt).*) => { concat!(stringify!($x), ".", intrinsic_pat!($($xs).*)) } } macro intrinsic_arg { (o $fx:expr, $arg:ident) => { $arg }, (c $fx:expr, $arg:ident) => { trans_operand($fx, $arg) }, (v $fx:expr, $arg:ident) => { trans_operand($fx, $arg).load_scalar($fx) } } macro intrinsic_substs { ($substs:expr, $index:expr,) => {}, ($substs:expr, $index:expr, $first:ident $(,$rest:ident)*) => { let $first = $substs.type_at($index); intrinsic_substs!($substs, $index+1, $($rest),*); } } pub macro intrinsic_match { ($fx:expr, $intrinsic:expr, $substs:expr, $args:expr, _ => $unknown:block; $( $($($name:tt).*)|+ $(if $cond:expr)?, $(<$($subst:ident),*>)? ($($a:ident $arg:ident),*) $content:block; )*) => { match $intrinsic { $( $(intrinsic_pat!($($name).*))|* $(if $cond)? => { #[allow(unused_parens, non_snake_case)] { $( intrinsic_substs!($substs, 0, $($subst),*); )? if let [$($arg),*] = $args { let ($($arg,)*) = ( $(intrinsic_arg!($a $fx, $arg),)* ); #[warn(unused_parens, non_snake_case)] { $content } } else { bug!("wrong number of args for intrinsic {:?}", $intrinsic); } } } )* _ => $unknown, } } } macro_rules! call_intrinsic_match { ($fx:expr, $intrinsic:expr, $substs:expr, $ret:expr, $destination:expr, $args:expr, $( $name:ident($($arg:ident),*) -> $ty:ident => $func:ident, )*) => { match $intrinsic { $( stringify!($name) => { assert!($substs.is_noop()); if let [$(ref $arg),*] = *$args { let ($($arg,)*) = ( $(trans_operand($fx, $arg),)* ); let res = $fx.easy_call(stringify!($func), &[$($arg),*], $fx.tcx.types.$ty); $ret.write_cvalue($fx, res); if let Some((_, dest)) = $destination { let ret_ebb = $fx.get_ebb(dest); $fx.bcx.ins().jump(ret_ebb, &[]); return; } else { unreachable!(); } } else { bug!("wrong number of args for intrinsic {:?}", $intrinsic); } } )* _ => {} } } } macro_rules! atomic_binop_return_old { ($fx:expr, $op:ident<$T:ident>($ptr:ident, $src:ident) -> $ret:ident) => { let clif_ty = $fx.clif_type($T).unwrap(); let old = $fx.bcx.ins().load(clif_ty, MemFlags::new(), $ptr, 0); let new = $fx.bcx.ins().$op(old, $src); $fx.bcx.ins().store(MemFlags::new(), new, $ptr, 0); $ret.write_cvalue($fx, CValue::by_val(old, $fx.layout_of($T))); }; } macro_rules! atomic_minmax { ($fx:expr, $cc:expr, <$T:ident> ($ptr:ident, $src:ident) -> $ret:ident) => { // Read old let clif_ty = $fx.clif_type($T).unwrap(); let old = $fx.bcx.ins().load(clif_ty, MemFlags::new(), $ptr, 0); // Compare let is_eq = codegen_icmp($fx, IntCC::SignedGreaterThan, old, $src); let new = codegen_select(&mut $fx.bcx, is_eq, old, $src); // Write new $fx.bcx.ins().store(MemFlags::new(), new, $ptr, 0); let ret_val = CValue::by_val(old, $ret.layout()); $ret.write_cvalue($fx, ret_val); }; } pub fn lane_type_and_count<'tcx>( fx: &FunctionCx<'_, 'tcx, impl Backend>, layout: TyLayout<'tcx>, intrinsic: &str, ) -> (TyLayout<'tcx>, u32) { assert!(layout.ty.is_simd()); let lane_count = match layout.fields { layout::FieldPlacement::Array { stride: _, count } => u32::try_from(count).unwrap(), _ => panic!( "Non vector type {:?} passed to or returned from simd_* intrinsic {}", layout.ty, intrinsic ), }; let lane_layout = layout.field(fx, 0); (lane_layout, lane_count) } pub fn simd_for_each_lane<'tcx, B: Backend>( fx: &mut FunctionCx<'_, 'tcx, B>, intrinsic: &str, x: CValue<'tcx>, y: CValue<'tcx>, ret: CPlace<'tcx>, f: impl Fn( &mut FunctionCx<'_, 'tcx, B>, TyLayout<'tcx>, TyLayout<'tcx>, Value, Value, ) -> CValue<'tcx>, ) { assert_eq!(x.layout(), y.layout()); let layout = x.layout(); let (lane_layout, lane_count) = lane_type_and_count(fx, layout, intrinsic); let (ret_lane_layout, ret_lane_count) = lane_type_and_count(fx, ret.layout(), intrinsic); assert_eq!(lane_count, ret_lane_count); for lane in 0..lane_count { let lane = mir::Field::new(lane.try_into().unwrap()); let x_lane = x.value_field(fx, lane).load_scalar(fx); let y_lane = y.value_field(fx, lane).load_scalar(fx); let res_lane = f(fx, lane_layout, ret_lane_layout, x_lane, y_lane); ret.place_field(fx, lane).write_cvalue(fx, res_lane); } } pub fn bool_to_zero_or_max_uint<'tcx>( fx: &mut FunctionCx<'_, 'tcx, impl Backend>, layout: TyLayout<'tcx>, val: Value, ) -> CValue<'tcx> { let ty = fx.clif_type(layout.ty).unwrap(); let int_ty = match ty { types::F32 => types::I32, types::F64 => types::I64, ty => ty, }; let zero = fx.bcx.ins().iconst(int_ty, 0); let max = fx .bcx .ins() .iconst(int_ty, (u64::max_value() >> (64 - int_ty.bits())) as i64); let mut res = crate::common::codegen_select(&mut fx.bcx, val, max, zero); if ty.is_float() { res = fx.bcx.ins().bitcast(ty, res); } CValue::by_val(res, layout) } macro_rules! simd_cmp { ($fx:expr, $intrinsic:expr, $cc:ident($x:ident, $y:ident) -> $ret:ident) => { simd_for_each_lane( $fx, $intrinsic, $x, $y, $ret, |fx, lane_layout, res_lane_layout, x_lane, y_lane| { let res_lane = match lane_layout.ty.kind { ty::Uint(_) | ty::Int(_) => codegen_icmp(fx, IntCC::$cc, x_lane, y_lane), _ => unreachable!("{:?}", lane_layout.ty), }; bool_to_zero_or_max_uint(fx, res_lane_layout, res_lane) }, ); }; ($fx:expr, $intrinsic:expr, $cc_u:ident|$cc_s:ident($x:ident, $y:ident) -> $ret:ident) => { simd_for_each_lane( $fx, $intrinsic, $x, $y, $ret, |fx, lane_layout, res_lane_layout, x_lane, y_lane| { let res_lane = match lane_layout.ty.kind { ty::Uint(_) => codegen_icmp(fx, IntCC::$cc_u, x_lane, y_lane), ty::Int(_) => codegen_icmp(fx, IntCC::$cc_s, x_lane, y_lane), _ => unreachable!("{:?}", lane_layout.ty), }; bool_to_zero_or_max_uint(fx, res_lane_layout, res_lane) }, ); }; } macro_rules! simd_int_binop { ($fx:expr, $intrinsic:expr, $op:ident($x:ident, $y:ident) -> $ret:ident) => { simd_for_each_lane( $fx, $intrinsic, $x, $y, $ret, |fx, lane_layout, ret_lane_layout, x_lane, y_lane| { let res_lane = match lane_layout.ty.kind { ty::Uint(_) | ty::Int(_) => fx.bcx.ins().$op(x_lane, y_lane), _ => unreachable!("{:?}", lane_layout.ty), }; CValue::by_val(res_lane, ret_lane_layout) }, ); }; ($fx:expr, $intrinsic:expr, $op_u:ident|$op_s:ident($x:ident, $y:ident) -> $ret:ident) => { simd_for_each_lane( $fx, $intrinsic, $x, $y, $ret, |fx, lane_layout, ret_lane_layout, x_lane, y_lane| { let res_lane = match lane_layout.ty.kind { ty::Uint(_) => fx.bcx.ins().$op_u(x_lane, y_lane), ty::Int(_) => fx.bcx.ins().$op_s(x_lane, y_lane), _ => unreachable!("{:?}", lane_layout.ty), }; CValue::by_val(res_lane, ret_lane_layout) }, ); }; } macro_rules! simd_int_flt_binop { ($fx:expr, $intrinsic:expr, $op:ident|$op_f:ident($x:ident, $y:ident) -> $ret:ident) => { simd_for_each_lane( $fx, $intrinsic, $x, $y, $ret, |fx, lane_layout, ret_lane_layout, x_lane, y_lane| { let res_lane = match lane_layout.ty.kind { ty::Uint(_) | ty::Int(_) => fx.bcx.ins().$op(x_lane, y_lane), ty::Float(_) => fx.bcx.ins().$op_f(x_lane, y_lane), _ => unreachable!("{:?}", lane_layout.ty), }; CValue::by_val(res_lane, ret_lane_layout) }, ); }; ($fx:expr, $intrinsic:expr, $op_u:ident|$op_s:ident|$op_f:ident($x:ident, $y:ident) -> $ret:ident) => { simd_for_each_lane( $fx, $intrinsic, $x, $y, $ret, |fx, lane_layout, ret_lane_layout, x_lane, y_lane| { let res_lane = match lane_layout.ty.kind { ty::Uint(_) => fx.bcx.ins().$op_u(x_lane, y_lane), ty::Int(_) => fx.bcx.ins().$op_s(x_lane, y_lane), ty::Float(_) => fx.bcx.ins().$op_f(x_lane, y_lane), _ => unreachable!("{:?}", lane_layout.ty), }; CValue::by_val(res_lane, ret_lane_layout) }, ); }; } macro_rules! simd_flt_binop { ($fx:expr, $intrinsic:expr, $op:ident($x:ident, $y:ident) -> $ret:ident) => { simd_for_each_lane( $fx, $intrinsic, $x, $y, $ret, |fx, lane_layout, ret_lane_layout, x_lane, y_lane| { let res_lane = match lane_layout.ty.kind { ty::Float(_) => fx.bcx.ins().$op(x_lane, y_lane), _ => unreachable!("{:?}", lane_layout.ty), }; CValue::by_val(res_lane, ret_lane_layout) }, ); }; } pub fn codegen_intrinsic_call<'tcx>( fx: &mut FunctionCx<'_, 'tcx, impl Backend>, instance: Instance<'tcx>, args: &[mir::Operand<'tcx>], destination: Option<(CPlace<'tcx>, BasicBlock)>, ) { let def_id = instance.def_id(); let substs = instance.substs; let intrinsic = fx.tcx.item_name(def_id).as_str(); let intrinsic = &intrinsic[..]; let ret = match destination { Some((place, _)) => place, None => { // Insert non returning intrinsics here match intrinsic { "abort" => { trap_panic(fx, "Called intrinsic::abort."); } "unreachable" => { trap_unreachable(fx, "[corruption] Called intrinsic::unreachable."); } "transmute" => { trap_unreachable( fx, "[corruption] Called intrinsic::transmute with uninhabited argument.", ); } _ => unimplemented!("unsupported instrinsic {}", intrinsic), } return; } }; let usize_layout = fx.layout_of(fx.tcx.types.usize); call_intrinsic_match! { fx, intrinsic, substs, ret, destination, args, expf32(flt) -> f32 => expf, expf64(flt) -> f64 => exp, exp2f32(flt) -> f32 => exp2f, exp2f64(flt) -> f64 => exp2, sqrtf32(flt) -> f32 => sqrtf, sqrtf64(flt) -> f64 => sqrt, powif32(a, x) -> f32 => __powisf2, // compiler-builtins powif64(a, x) -> f64 => __powidf2, // compiler-builtins powf32(a, x) -> f32 => powf, powf64(a, x) -> f64 => pow, logf32(flt) -> f32 => logf, logf64(flt) -> f64 => log, log2f32(flt) -> f32 => log2f, log2f64(flt) -> f64 => log2, fabsf32(flt) -> f32 => fabsf, fabsf64(flt) -> f64 => fabs, fmaf32(x, y, z) -> f32 => fmaf, fmaf64(x, y, z) -> f64 => fma, copysignf32(x, y) -> f32 => copysignf, copysignf64(x, y) -> f64 => copysign, // rounding variants // FIXME use clif insts floorf32(flt) -> f32 => floorf, floorf64(flt) -> f64 => floor, ceilf32(flt) -> f32 => ceilf, ceilf64(flt) -> f64 => ceil, truncf32(flt) -> f32 => truncf, truncf64(flt) -> f64 => trunc, roundf32(flt) -> f32 => roundf, roundf64(flt) -> f64 => round, // trigonometry sinf32(flt) -> f32 => sinf, sinf64(flt) -> f64 => sin, cosf32(flt) -> f32 => cosf, cosf64(flt) -> f64 => cos, tanf32(flt) -> f32 => tanf, tanf64(flt) -> f64 => tan, } intrinsic_match! { fx, intrinsic, substs, args, _ => { unimpl!("unsupported intrinsic {}", intrinsic) }; assume, (c _a) {}; likely | unlikely, (c a) { ret.write_cvalue(fx, a); }; breakpoint, () { fx.bcx.ins().debugtrap(); }; copy | copy_nonoverlapping, <elem_ty> (v src, v dst, v count) { let elem_size: u64 = fx.layout_of(elem_ty).size.bytes(); let elem_size = fx .bcx .ins() .iconst(fx.pointer_type, elem_size as i64); assert_eq!(args.len(), 3); let byte_amount = fx.bcx.ins().imul(count, elem_size); if intrinsic.ends_with("_nonoverlapping") { fx.bcx.call_memcpy(fx.module.target_config(), dst, src, byte_amount); } else { fx.bcx.call_memmove(fx.module.target_config(), dst, src, byte_amount); } }; discriminant_value, (c ptr) { let pointee_layout = fx.layout_of(ptr.layout().ty.builtin_deref(true).unwrap().ty); let val = CValue::by_ref(ptr.load_scalar(fx), pointee_layout); let discr = crate::discriminant::codegen_get_discriminant(fx, val, ret.layout()); ret.write_cvalue(fx, discr); }; size_of_val, <T> (c ptr) { let layout = fx.layout_of(T); let size = if layout.is_unsized() { let (_ptr, info) = ptr.load_scalar_pair(fx); let (size, _align) = crate::unsize::size_and_align_of_dst(fx, layout.ty, info); size } else { fx .bcx .ins() .iconst(fx.pointer_type, layout.size.bytes() as i64) }; ret.write_cvalue(fx, CValue::by_val(size, usize_layout)); }; min_align_of_val, <T> (c ptr) { let layout = fx.layout_of(T); let align = if layout.is_unsized() { let (_ptr, info) = ptr.load_scalar_pair(fx); let (_size, align) = crate::unsize::size_and_align_of_dst(fx, layout.ty, info); align } else { fx .bcx .ins() .iconst(fx.pointer_type, layout.align.abi.bytes() as i64) }; ret.write_cvalue(fx, CValue::by_val(align, usize_layout)); }; _ if intrinsic.starts_with("unchecked_") || intrinsic == "exact_div", (c x, c y) { // FIXME trap on overflow let bin_op = match intrinsic { "unchecked_sub" => BinOp::Sub, "unchecked_div" | "exact_div" => BinOp::Div, "unchecked_rem" => BinOp::Rem, "unchecked_shl" => BinOp::Shl, "unchecked_shr" => BinOp::Shr, _ => unimplemented!("intrinsic {}", intrinsic), }; let res = crate::num::trans_int_binop(fx, bin_op, x, y); ret.write_cvalue(fx, res); }; _ if intrinsic.ends_with("_with_overflow"), (c x, c y) { assert_eq!(x.layout().ty, y.layout().ty); let bin_op = match intrinsic { "add_with_overflow" => BinOp::Add, "sub_with_overflow" => BinOp::Sub, "mul_with_overflow" => BinOp::Mul, _ => unimplemented!("intrinsic {}", intrinsic), }; let res = crate::num::trans_checked_int_binop( fx, bin_op, x, y, ); ret.write_cvalue(fx, res); }; _ if intrinsic.starts_with("wrapping_"), (c x, c y) { assert_eq!(x.layout().ty, y.layout().ty); let bin_op = match intrinsic { "wrapping_add" => BinOp::Add, "wrapping_sub" => BinOp::Sub, "wrapping_mul" => BinOp::Mul, _ => unimplemented!("intrinsic {}", intrinsic), }; let res = crate::num::trans_int_binop( fx, bin_op, x, y, ); ret.write_cvalue(fx, res); }; _ if intrinsic.starts_with("saturating_"), <T> (c lhs, c rhs) { assert_eq!(lhs.layout().ty, rhs.layout().ty); let bin_op = match intrinsic { "saturating_add" => BinOp::Add, "saturating_sub" => BinOp::Sub, _ => unimplemented!("intrinsic {}", intrinsic), }; let signed = type_sign(T); let checked_res = crate::num::trans_checked_int_binop( fx, bin_op, lhs, rhs, ); let (val, has_overflow) = checked_res.load_scalar_pair(fx); let clif_ty = fx.clif_type(T).unwrap(); // `select.i8` is not implemented by Cranelift. let has_overflow = fx.bcx.ins().uextend(types::I32, has_overflow); let (min, max) = type_min_max_value(clif_ty, signed); let min = fx.bcx.ins().iconst(clif_ty, min); let max = fx.bcx.ins().iconst(clif_ty, max); let val = match (intrinsic, signed) { ("saturating_add", false) => codegen_select(&mut fx.bcx, has_overflow, max, val), ("saturating_sub", false) => codegen_select(&mut fx.bcx, has_overflow, min, val), ("saturating_add", true) => { let rhs = rhs.load_scalar(fx); let rhs_ge_zero = fx.bcx.ins().icmp_imm(IntCC::SignedGreaterThanOrEqual, rhs, 0); let sat_val = codegen_select(&mut fx.bcx, rhs_ge_zero, max, min); codegen_select(&mut fx.bcx, has_overflow, sat_val, val) } ("saturating_sub", true) => { let rhs = rhs.load_scalar(fx); let rhs_ge_zero = fx.bcx.ins().icmp_imm(IntCC::SignedGreaterThanOrEqual, rhs, 0); let sat_val = codegen_select(&mut fx.bcx, rhs_ge_zero, min, max); codegen_select(&mut fx.bcx, has_overflow, sat_val, val) } _ => unreachable!(), }; let res = CValue::by_val(val, fx.layout_of(T)); ret.write_cvalue(fx, res); }; rotate_left, <T>(v x, v y) { let layout = fx.layout_of(T); let res = fx.bcx.ins().rotl(x, y); ret.write_cvalue(fx, CValue::by_val(res, layout)); }; rotate_right, <T>(v x, v y) { let layout = fx.layout_of(T); let res = fx.bcx.ins().rotr(x, y); ret.write_cvalue(fx, CValue::by_val(res, layout)); }; // The only difference between offset and arith_offset is regarding UB. Because Cranelift // doesn't have UB both are codegen'ed the same way offset | arith_offset, (c base, v offset) { let pointee_ty = base.layout().ty.builtin_deref(true).unwrap().ty; let pointee_size = fx.layout_of(pointee_ty).size.bytes(); let ptr_diff = fx.bcx.ins().imul_imm(offset, pointee_size as i64); let base_val = base.load_scalar(fx); let res = fx.bcx.ins().iadd(base_val, ptr_diff); ret.write_cvalue(fx, CValue::by_val(res, base.layout())); }; transmute, <src_ty, dst_ty> (c from) { assert_eq!(from.layout().ty, src_ty); let addr = from.force_stack(fx); let dst_layout = fx.layout_of(dst_ty); ret.write_cvalue(fx, CValue::by_ref(addr, dst_layout)) }; init, () { let layout = ret.layout(); if layout.abi == Abi::Uninhabited { crate::trap::trap_panic(fx, "[panic] Called intrinsic::init for uninhabited type."); return; } match *ret.inner() { CPlaceInner::NoPlace => {} CPlaceInner::Var(var) => { let clif_ty = fx.clif_type(layout.ty).unwrap(); let val = match clif_ty { types::I8 | types::I16 | types::I32 | types::I64 => fx.bcx.ins().iconst(clif_ty, 0), types::F32 => { let zero = fx.bcx.ins().iconst(types::I32, 0); fx.bcx.ins().bitcast(types::F32, zero) } types::F64 => { let zero = fx.bcx.ins().iconst(types::I64, 0); fx.bcx.ins().bitcast(types::F64, zero) } _ => panic!("clif_type returned {}", clif_ty), }; fx.bcx.def_var(mir_var(var), val); } _ => { let addr = ret.to_addr(fx); let layout = ret.layout(); fx.bcx.emit_small_memset(fx.module.target_config(), addr, 0, layout.size.bytes(), 1); } } }; uninit, () { let layout = ret.layout(); if layout.abi == Abi::Uninhabited { crate::trap::trap_panic(fx, "[panic] Called intrinsic::uninit for uninhabited type."); return; } match *ret.inner() { CPlaceInner::NoPlace => {}, CPlaceInner::Var(var) => { let clif_ty = fx.clif_type(layout.ty).unwrap(); let val = match clif_ty { types::I8 | types::I16 | types::I32 | types::I64 => fx.bcx.ins().iconst(clif_ty, 42), types::F32 => { let zero = fx.bcx.ins().iconst(types::I32, 0xdeadbeef); fx.bcx.ins().bitcast(types::F32, zero) } types::F64 => { let zero = fx.bcx.ins().iconst(types::I64, 0xcafebabedeadbeefu64 as i64); fx.bcx.ins().bitcast(types::F64, zero) } _ => panic!("clif_type returned {}", clif_ty), }; fx.bcx.def_var(mir_var(var), val); } CPlaceInner::Addr(_, _) | CPlaceInner::Stack(_) => { // Don't write to `ret`, as the destination memory is already uninitialized. } } }; write_bytes, (c dst, v val, v count) { let pointee_ty = dst.layout().ty.builtin_deref(true).unwrap().ty; let pointee_size = fx.layout_of(pointee_ty).size.bytes(); let count = fx.bcx.ins().imul_imm(count, pointee_size as i64); let dst_ptr = dst.load_scalar(fx); fx.bcx.call_memset(fx.module.target_config(), dst_ptr, val, count); }; ctlz | ctlz_nonzero, <T> (v arg) { // FIXME trap on `ctlz_nonzero` with zero arg. let res = if T == fx.tcx.types.u128 || T == fx.tcx.types.i128 { // FIXME verify this algorithm is correct let (lsb, msb) = fx.bcx.ins().isplit(arg); let lsb_lz = fx.bcx.ins().clz(lsb); let msb_lz = fx.bcx.ins().clz(msb); let msb_is_zero = fx.bcx.ins().icmp_imm(IntCC::Equal, msb, 0); let lsb_lz_plus_64 = fx.bcx.ins().iadd_imm(lsb_lz, 64); fx.bcx.ins().select(msb_is_zero, lsb_lz_plus_64, msb_lz) } else { fx.bcx.ins().clz(arg) }; let res = CValue::by_val(res, fx.layout_of(T)); ret.write_cvalue(fx, res); }; cttz | cttz_nonzero, <T> (v arg) { // FIXME trap on `cttz_nonzero` with zero arg. let res = if T == fx.tcx.types.u128 || T == fx.tcx.types.i128 { // FIXME verify this algorithm is correct let (lsb, msb) = fx.bcx.ins().isplit(arg); let lsb_tz = fx.bcx.ins().ctz(lsb); let msb_tz = fx.bcx.ins().ctz(msb); let lsb_is_zero = fx.bcx.ins().icmp_imm(IntCC::Equal, lsb, 0); let msb_tz_plus_64 = fx.bcx.ins().iadd_imm(msb_tz, 64); fx.bcx.ins().select(lsb_is_zero, msb_tz_plus_64, lsb_tz) } else { fx.bcx.ins().ctz(arg) }; let res = CValue::by_val(res, fx.layout_of(T)); ret.write_cvalue(fx, res); }; ctpop, <T> (v arg) { let res = if T == fx.tcx.types.u128 || T == fx.tcx.types.i128 { let (lo, hi) = fx.bcx.ins().isplit(arg); let lo_popcnt = fx.bcx.ins().popcnt(lo); let hi_popcnt = fx.bcx.ins().popcnt(hi); let popcnt = fx.bcx.ins().iadd(lo_popcnt, hi_popcnt); crate::cast::clif_intcast(fx, popcnt, types::I128, false) } else { fx.bcx.ins().popcnt(arg) }; let res = CValue::by_val(res, fx.layout_of(T)); ret.write_cvalue(fx, res); }; bitreverse, <T> (v arg) { let res = if T == fx.tcx.types.u128 || T == fx.tcx.types.i128 { let (lo, hi) = fx.bcx.ins().isplit(arg); let lo_bitrev = fx.bcx.ins().bitrev(lo); let hi_bitrev = fx.bcx.ins().bitrev(hi); let bitrev = fx.bcx.ins().iconcat(hi_bitrev, lo_bitrev); crate::cast::clif_intcast(fx, bitrev, types::I128, false) } else { fx.bcx.ins().bitrev(arg) }; let res = CValue::by_val(res, fx.layout_of(T)); ret.write_cvalue(fx, res); }; bswap, <T> (v arg) { // FIXME(CraneStation/cranelift#794) add bswap instruction to cranelift fn swap(bcx: &mut FunctionBuilder, v: Value) -> Value { match bcx.func.dfg.value_type(v) { types::I8 => v, // https://code.woboq.org/gcc/include/bits/byteswap.h.html types::I16 => { let tmp1 = bcx.ins().ishl_imm(v, 8); let n1 = bcx.ins().band_imm(tmp1, 0xFF00); let tmp2 = bcx.ins().ushr_imm(v, 8); let n2 = bcx.ins().band_imm(tmp2, 0x00FF); bcx.ins().bor(n1, n2) } types::I32 => { let tmp1 = bcx.ins().ishl_imm(v, 24); let n1 = bcx.ins().band_imm(tmp1, 0xFF00_0000); let tmp2 = bcx.ins().ishl_imm(v, 8); let n2 = bcx.ins().band_imm(tmp2, 0x00FF_0000); let tmp3 = bcx.ins().ushr_imm(v, 8); let n3 = bcx.ins().band_imm(tmp3, 0x0000_FF00); let tmp4 = bcx.ins().ushr_imm(v, 24); let n4 = bcx.ins().band_imm(tmp4, 0x0000_00FF); let or_tmp1 = bcx.ins().bor(n1, n2); let or_tmp2 = bcx.ins().bor(n3, n4); bcx.ins().bor(or_tmp1, or_tmp2) } types::I64 => { let tmp1 = bcx.ins().ishl_imm(v, 56); let n1 = bcx.ins().band_imm(tmp1, 0xFF00_0000_0000_0000u64 as i64); let tmp2 = bcx.ins().ishl_imm(v, 40); let n2 = bcx.ins().band_imm(tmp2, 0x00FF_0000_0000_0000u64 as i64); let tmp3 = bcx.ins().ishl_imm(v, 24); let n3 = bcx.ins().band_imm(tmp3, 0x0000_FF00_0000_0000u64 as i64); let tmp4 = bcx.ins().ishl_imm(v, 8); let n4 = bcx.ins().band_imm(tmp4, 0x0000_00FF_0000_0000u64 as i64); let tmp5 = bcx.ins().ushr_imm(v, 8); let n5 = bcx.ins().band_imm(tmp5, 0x0000_0000_FF00_0000u64 as i64); let tmp6 = bcx.ins().ushr_imm(v, 24); let n6 = bcx.ins().band_imm(tmp6, 0x0000_0000_00FF_0000u64 as i64); let tmp7 = bcx.ins().ushr_imm(v, 40); let n7 = bcx.ins().band_imm(tmp7, 0x0000_0000_0000_FF00u64 as i64); let tmp8 = bcx.ins().ushr_imm(v, 56); let n8 = bcx.ins().band_imm(tmp8, 0x0000_0000_0000_00FFu64 as i64); let or_tmp1 = bcx.ins().bor(n1, n2); let or_tmp2 = bcx.ins().bor(n3, n4); let or_tmp3 = bcx.ins().bor(n5, n6); let or_tmp4 = bcx.ins().bor(n7, n8); let or_tmp5 = bcx.ins().bor(or_tmp1, or_tmp2); let or_tmp6 = bcx.ins().bor(or_tmp3, or_tmp4); bcx.ins().bor(or_tmp5, or_tmp6) } types::I128 => { let (lo, hi) = bcx.ins().isplit(v); let lo = swap(bcx, lo); let hi = swap(bcx, hi); bcx.ins().iconcat(hi, lo) } ty => unimplemented!("bswap {}", ty), } }; let res = CValue::by_val(swap(&mut fx.bcx, arg), fx.layout_of(T)); ret.write_cvalue(fx, res); }; panic_if_uninhabited, <T> () { if fx.layout_of(T).abi.is_uninhabited() { crate::trap::trap_panic(fx, "[panic] Called intrinsic::panic_if_uninhabited for uninhabited type."); return; } }; volatile_load, (c ptr) { // Cranelift treats loads as volatile by default let inner_layout = fx.layout_of(ptr.layout().ty.builtin_deref(true).unwrap().ty); let val = CValue::by_ref(ptr.load_scalar(fx), inner_layout); ret.write_cvalue(fx, val); }; volatile_store, (v ptr, c val) { // Cranelift treats stores as volatile by default let dest = CPlace::for_addr(ptr, val.layout()); dest.write_cvalue(fx, val); }; size_of | pref_align_of | min_align_of | needs_drop | type_id | type_name, () { let gid = rustc::mir::interpret::GlobalId { instance, promoted: None, }; let const_val = fx.tcx.const_eval(ParamEnv::reveal_all().and(gid)).unwrap(); let val = crate::constant::trans_const_value(fx, const_val); ret.write_cvalue(fx, val); }; _ if intrinsic.starts_with("atomic_fence"), () {}; _ if intrinsic.starts_with("atomic_singlethreadfence"), () {}; _ if intrinsic.starts_with("atomic_load"), (c ptr) { let inner_layout = fx.layout_of(ptr.layout().ty.builtin_deref(true).unwrap().ty); let val = CValue::by_ref(ptr.load_scalar(fx), inner_layout); ret.write_cvalue(fx, val); }; _ if intrinsic.starts_with("atomic_store"), (v ptr, c val) { let dest = CPlace::for_addr(ptr, val.layout()); dest.write_cvalue(fx, val); }; _ if intrinsic.starts_with("atomic_xchg"), <T> (v ptr, c src) { // Read old let clif_ty = fx.clif_type(T).unwrap(); let old = fx.bcx.ins().load(clif_ty, MemFlags::new(), ptr, 0); ret.write_cvalue(fx, CValue::by_val(old, fx.layout_of(T))); // Write new let dest = CPlace::for_addr(ptr, src.layout()); dest.write_cvalue(fx, src); }; _ if intrinsic.starts_with("atomic_cxchg"), <T> (v ptr, v test_old, v new) { // both atomic_cxchg_* and atomic_cxchgweak_* // Read old let clif_ty = fx.clif_type(T).unwrap(); let old = fx.bcx.ins().load(clif_ty, MemFlags::new(), ptr, 0); // Compare let is_eq = codegen_icmp(fx, IntCC::Equal, old, test_old); let new = crate::common::codegen_select(&mut fx.bcx, is_eq, new, old); // Keep old if not equal to test_old // Write new fx.bcx.ins().store(MemFlags::new(), new, ptr, 0); let ret_val = CValue::by_val_pair(old, fx.bcx.ins().bint(types::I8, is_eq), ret.layout()); ret.write_cvalue(fx, ret_val); }; _ if intrinsic.starts_with("atomic_xadd"), <T> (v ptr, v amount) { atomic_binop_return_old! (fx, iadd<T>(ptr, amount) -> ret); }; _ if intrinsic.starts_with("atomic_xsub"), <T> (v ptr, v amount) { atomic_binop_return_old! (fx, isub<T>(ptr, amount) -> ret); }; _ if intrinsic.starts_with("atomic_and"), <T> (v ptr, v src) { atomic_binop_return_old! (fx, band<T>(ptr, src) -> ret); }; _ if intrinsic.starts_with("atomic_nand"), <T> (v ptr, v src) { let clif_ty = fx.clif_type(T).unwrap(); let old = fx.bcx.ins().load(clif_ty, MemFlags::new(), ptr, 0); let and = fx.bcx.ins().band(old, src); let new = fx.bcx.ins().bnot(and); fx.bcx.ins().store(MemFlags::new(), new, ptr, 0); ret.write_cvalue(fx, CValue::by_val(old, fx.layout_of(T))); }; _ if intrinsic.starts_with("atomic_or"), <T> (v ptr, v src) { atomic_binop_return_old! (fx, bor<T>(ptr, src) -> ret); }; _ if intrinsic.starts_with("atomic_xor"), <T> (v ptr, v src) { atomic_binop_return_old! (fx, bxor<T>(ptr, src) -> ret); }; _ if intrinsic.starts_with("atomic_max"), <T> (v ptr, v src) { atomic_minmax!(fx, IntCC::SignedGreaterThan, <T> (ptr, src) -> ret); }; _ if intrinsic.starts_with("atomic_umax"), <T> (v ptr, v src) { atomic_minmax!(fx, IntCC::UnsignedGreaterThan, <T> (ptr, src) -> ret); }; _ if intrinsic.starts_with("atomic_min"), <T> (v ptr, v src) { atomic_minmax!(fx, IntCC::SignedLessThan, <T> (ptr, src) -> ret); }; _ if intrinsic.starts_with("atomic_umin"), <T> (v ptr, v src) { atomic_minmax!(fx, IntCC::UnsignedLessThan, <T> (ptr, src) -> ret); }; minnumf32, (v a, v b) { let val = fx.bcx.ins().fmin(a, b); let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32)); ret.write_cvalue(fx, val); }; minnumf64, (v a, v b) { let val = fx.bcx.ins().fmin(a, b); let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64)); ret.write_cvalue(fx, val); }; maxnumf32, (v a, v b) { let val = fx.bcx.ins().fmax(a, b); let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f32)); ret.write_cvalue(fx, val); }; maxnumf64, (v a, v b) { let val = fx.bcx.ins().fmax(a, b); let val = CValue::by_val(val, fx.layout_of(fx.tcx.types.f64)); ret.write_cvalue(fx, val); }; simd_cast, (c a) { let (lane_layout, lane_count) = lane_type_and_count(fx, a.layout(), intrinsic); let (ret_lane_layout, ret_lane_count) = lane_type_and_count(fx, ret.layout(), intrinsic); assert_eq!(lane_count, ret_lane_count); let ret_lane_ty = fx.clif_type(ret_lane_layout.ty).unwrap(); let from_signed = type_sign(lane_layout.ty); let to_signed = type_sign(ret_lane_layout.ty); for lane in 0..lane_count { let lane = mir::Field::new(lane.try_into().unwrap()); let a_lane = a.value_field(fx, lane).load_scalar(fx); let res = clif_int_or_float_cast(fx, a_lane, from_signed, ret_lane_ty, to_signed); ret.place_field(fx, lane).write_cvalue(fx, CValue::by_val(res, ret_lane_layout)); } }; simd_eq, (c x, c y) { simd_cmp!(fx, intrinsic, Equal(x, y) -> ret); }; simd_ne, (c x, c y) { simd_cmp!(fx, intrinsic, NotEqual(x, y) -> ret); }; simd_lt, (c x, c y) { simd_cmp!(fx, intrinsic, UnsignedLessThan|SignedLessThan(x, y) -> ret); }; simd_le, (c x, c y) { simd_cmp!(fx, intrinsic, UnsignedLessThanOrEqual|SignedLessThanOrEqual(x, y) -> ret); }; simd_gt, (c x, c y) { simd_cmp!(fx, intrinsic, UnsignedGreaterThan|SignedGreaterThan(x, y) -> ret); }; simd_ge, (c x, c y) { simd_cmp!(fx, intrinsic, UnsignedGreaterThanOrEqual|SignedGreaterThanOrEqual(x, y) -> ret); }; // simd_shuffle32<T, U>(x: T, y: T, idx: [u32; 32]) -> U _ if intrinsic.starts_with("simd_shuffle"), (c x, c y, o idx) { let n: u32 = intrinsic["simd_shuffle".len()..].parse().unwrap(); assert_eq!(x.layout(), y.layout()); let layout = x.layout(); let (lane_type, lane_count) = lane_type_and_count(fx, layout, intrinsic); let (ret_lane_type, ret_lane_count) = lane_type_and_count(fx, ret.layout(), intrinsic); assert_eq!(lane_type, ret_lane_type); assert_eq!(n, ret_lane_count); let total_len = lane_count * 2; let indexes = { use rustc::mir::interpret::*; let idx_const = crate::constant::mir_operand_get_const_val(fx, idx).expect("simd_shuffle* idx not const"); let idx_bytes = match idx_const.val { ConstValue::ByRef { alloc, offset } => { let ptr = Pointer::new(AllocId(0 /* dummy */), offset); let size = Size::from_bytes(4 * u64::from(ret_lane_count) /* size_of([u32; ret_lane_count]) */); alloc.get_bytes(fx, ptr, size).unwrap() } _ => unreachable!("{:?}", idx_const), }; (0..ret_lane_count).map(|i| { let i = usize::try_from(i).unwrap(); let idx = rustc::mir::interpret::read_target_uint( fx.tcx.data_layout.endian, &idx_bytes[4*i.. 4*i + 4], ).expect("read_target_uint"); u32::try_from(idx).expect("try_from u32") }).collect::<Vec<u32>>() }; for &idx in &indexes { assert!(idx < total_len, "idx {} out of range 0..{}", idx, total_len); } for (out_idx, in_idx) in indexes.into_iter().enumerate() { let in_lane = if in_idx < lane_count { x.value_field(fx, mir::Field::new(in_idx.try_into().unwrap())) } else { y.value_field(fx, mir::Field::new((in_idx - lane_count).try_into().unwrap())) }; let out_lane = ret.place_field(fx, mir::Field::new(out_idx)); out_lane.write_cvalue(fx, in_lane); } }; simd_extract, (c v, o idx) { let idx_const = if let Some(idx_const) = crate::constant::mir_operand_get_const_val(fx, idx) { idx_const } else { fx.tcx.sess.span_warn( fx.mir.span, "`#[rustc_arg_required_const(..)]` is not yet supported. Calling this function will panic.", ); crate::trap::trap_panic(fx, "`#[rustc_arg_required_const(..)]` is not yet supported."); return; }; let idx = idx_const.val.try_to_bits(Size::from_bytes(4 /* u32*/)).expect(&format!("kind not scalar: {:?}", idx_const)); let (_lane_type, lane_count) = lane_type_and_count(fx, v.layout(), intrinsic); if idx >= lane_count.into() { fx.tcx.sess.span_fatal(fx.mir.span, &format!("[simd_extract] idx {} >= lane_count {}", idx, lane_count)); } let ret_lane = v.value_field(fx, mir::Field::new(idx.try_into().unwrap())); ret.write_cvalue(fx, ret_lane); }; simd_add, (c x, c y) { simd_int_flt_binop!(fx, intrinsic, iadd|fadd(x, y) -> ret); }; simd_sub, (c x, c y) { simd_int_flt_binop!(fx, intrinsic, isub|fsub(x, y) -> ret); }; simd_mul, (c x, c y) { simd_int_flt_binop!(fx, intrinsic, imul|fmul(x, y) -> ret); }; simd_div, (c x, c y) { simd_int_flt_binop!(fx, intrinsic, udiv|sdiv|fdiv(x, y) -> ret); }; simd_shl, (c x, c y) { simd_int_binop!(fx, intrinsic, ishl(x, y) -> ret); }; simd_shr, (c x, c y) { simd_int_binop!(fx, intrinsic, ushr|sshr(x, y) -> ret); }; simd_and, (c x, c y) { simd_int_binop!(fx, intrinsic, band(x, y) -> ret); }; simd_or, (c x, c y) { simd_int_binop!(fx, intrinsic, bor(x, y) -> ret); }; simd_xor, (c x, c y) { simd_int_binop!(fx, intrinsic, bxor(x, y) -> ret); }; simd_fmin, (c x, c y) { simd_flt_binop!(fx, intrinsic, fmin(x, y) -> ret); }; simd_fmax, (c x, c y) { simd_flt_binop!(fx, intrinsic, fmax(x, y) -> ret); }; try, (v f, v data, v _local_ptr) { // FIXME once unwinding is supported, change this to actually catch panics let f_sig = fx.bcx.func.import_signature(Signature { call_conv: crate::default_call_conv(fx.tcx.sess), params: vec![AbiParam::new(fx.bcx.func.dfg.value_type(data))], returns: vec![], }); fx.bcx.ins().call_indirect(f_sig, f, &[data]); let ret_val = CValue::const_val(fx, ret.layout().ty, 0); ret.write_cvalue(fx, ret_val); }; } if let Some((_, dest)) = destination { let ret_ebb = fx.get_ebb(dest); fx.bcx.ins().jump(ret_ebb, &[]); } else { trap_unreachable(fx, "[corruption] Diverging intrinsic returned."); } }
40.013599
131
0.482905
50deb4aa3da1c97fbd2a01c3d7c2620850e799ff
13,911
pub mod mock; use crate::mock::{MockComponentBuilder, MockFile, MockInstallerBuilder}; use rustup::dist::component::Components; use rustup::dist::component::Transaction; use rustup::dist::component::{DirectoryPackage, Package}; use rustup::dist::dist::DEFAULT_DIST_SERVER; use rustup::dist::prefix::InstallPrefix; use rustup::dist::temp; use rustup::dist::Notification; use rustup::utils::utils; use rustup::ErrorKind; use std::fs::File; use std::io::Write; use tempdir::TempDir; // Just testing that the mocks work #[test] fn mock_smoke_test() { let tempdir = TempDir::new("rustup").unwrap(); let mock = MockInstallerBuilder { components: vec![ MockComponentBuilder { name: "mycomponent".to_string(), files: vec![ MockFile::new("bin/foo", b"foo"), MockFile::new("lib/bar", b"bar"), MockFile::new_dir("doc/stuff", &[("doc1", b"", false), ("doc2", b"", false)]), ], }, MockComponentBuilder { name: "mycomponent2".to_string(), files: vec![MockFile::new("bin/quux", b"quux")], }, ], }; mock.build(tempdir.path()); assert!(tempdir.path().join("components").exists()); assert!(tempdir.path().join("mycomponent/manifest.in").exists()); assert!(tempdir.path().join("mycomponent/bin/foo").exists()); assert!(tempdir.path().join("mycomponent/lib/bar").exists()); assert!(tempdir.path().join("mycomponent/doc/stuff/doc1").exists()); assert!(tempdir.path().join("mycomponent/doc/stuff/doc2").exists()); assert!(tempdir.path().join("mycomponent2/manifest.in").exists()); assert!(tempdir.path().join("mycomponent2/bin/quux").exists()); } #[test] fn package_contains() { let tempdir = TempDir::new("rustup").unwrap(); let mock = MockInstallerBuilder { components: vec![ MockComponentBuilder { name: "mycomponent".to_string(), files: vec![MockFile::new("bin/foo", b"foo")], }, MockComponentBuilder { name: "mycomponent2".to_string(), files: vec![MockFile::new("bin/bar", b"bar")], }, ], }; mock.build(tempdir.path()); let package = DirectoryPackage::new(tempdir.path().to_owned(), true).unwrap(); assert!(package.contains("mycomponent", None)); assert!(package.contains("mycomponent2", None)); } #[test] fn package_bad_version() { let tempdir = TempDir::new("rustup").unwrap(); let mock = MockInstallerBuilder { components: vec![MockComponentBuilder { name: "mycomponent".to_string(), files: vec![MockFile::new("bin/foo", b"foo")], }], }; mock.build(tempdir.path()); let mut ver = File::create(tempdir.path().join("rust-installer-version")).unwrap(); writeln!(ver, "100").unwrap(); assert!(DirectoryPackage::new(tempdir.path().to_owned(), true).is_err()); } #[test] fn basic_install() { let pkgdir = TempDir::new("rustup").unwrap(); let mock = MockInstallerBuilder { components: vec![MockComponentBuilder { name: "mycomponent".to_string(), files: vec![ MockFile::new("bin/foo", b"foo"), MockFile::new("lib/bar", b"bar"), MockFile::new_dir("doc/stuff", &[("doc1", b"", false), ("doc2", b"", false)]), ], }], }; mock.build(pkgdir.path()); let instdir = TempDir::new("rustup").unwrap(); let prefix = InstallPrefix::from(instdir.path().to_owned()); let tmpdir = TempDir::new("rustup").unwrap(); let tmpcfg = temp::Cfg::new( tmpdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ()), ); let notify = |_: Notification<'_>| (); let tx = Transaction::new(prefix.clone(), &tmpcfg, &notify); let components = Components::open(prefix.clone()).unwrap(); let pkg = DirectoryPackage::new(pkgdir.path().to_owned(), true).unwrap(); let tx = pkg.install(&components, "mycomponent", None, tx).unwrap(); tx.commit(); assert!(utils::path_exists(instdir.path().join("bin/foo"))); assert!(utils::path_exists(instdir.path().join("lib/bar"))); assert!(utils::path_exists(instdir.path().join("doc/stuff/doc1"))); assert!(utils::path_exists(instdir.path().join("doc/stuff/doc2"))); assert!(components.find("mycomponent").unwrap().is_some()); } #[test] fn multiple_component_install() { let pkgdir = TempDir::new("rustup").unwrap(); let mock = MockInstallerBuilder { components: vec![ MockComponentBuilder { name: "mycomponent".to_string(), files: vec![MockFile::new("bin/foo", b"foo")], }, MockComponentBuilder { name: "mycomponent2".to_string(), files: vec![MockFile::new("lib/bar", b"bar")], }, ], }; mock.build(pkgdir.path()); let instdir = TempDir::new("rustup").unwrap(); let prefix = InstallPrefix::from(instdir.path().to_owned()); let tmpdir = TempDir::new("rustup").unwrap(); let tmpcfg = temp::Cfg::new( tmpdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ()), ); let notify = |_: Notification<'_>| (); let tx = Transaction::new(prefix.clone(), &tmpcfg, &notify); let components = Components::open(prefix.clone()).unwrap(); let pkg = DirectoryPackage::new(pkgdir.path().to_owned(), true).unwrap(); let tx = pkg.install(&components, "mycomponent", None, tx).unwrap(); let tx = pkg.install(&components, "mycomponent2", None, tx).unwrap(); tx.commit(); assert!(utils::path_exists(instdir.path().join("bin/foo"))); assert!(utils::path_exists(instdir.path().join("lib/bar"))); assert!(components.find("mycomponent").unwrap().is_some()); assert!(components.find("mycomponent2").unwrap().is_some()); } #[test] fn uninstall() { let pkgdir = TempDir::new("rustup").unwrap(); let mock = MockInstallerBuilder { components: vec![ MockComponentBuilder { name: "mycomponent".to_string(), files: vec![ MockFile::new("bin/foo", b"foo"), MockFile::new("lib/bar", b"bar"), MockFile::new_dir("doc/stuff", &[("doc1", b"", false), ("doc2", b"", false)]), ], }, MockComponentBuilder { name: "mycomponent2".to_string(), files: vec![MockFile::new("lib/quux", b"quux")], }, ], }; mock.build(pkgdir.path()); let instdir = TempDir::new("rustup").unwrap(); let prefix = InstallPrefix::from(instdir.path().to_owned()); let tmpdir = TempDir::new("rustup").unwrap(); let tmpcfg = temp::Cfg::new( tmpdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ()), ); let notify = |_: Notification<'_>| (); let tx = Transaction::new(prefix.clone(), &tmpcfg, &notify); let components = Components::open(prefix.clone()).unwrap(); let pkg = DirectoryPackage::new(pkgdir.path().to_owned(), true).unwrap(); let tx = pkg.install(&components, "mycomponent", None, tx).unwrap(); let tx = pkg.install(&components, "mycomponent2", None, tx).unwrap(); tx.commit(); // Now uninstall let notify = |_: Notification<'_>| (); let mut tx = Transaction::new(prefix.clone(), &tmpcfg, &notify); for component in components.list().unwrap() { tx = component.uninstall(tx).unwrap(); } tx.commit(); assert!(!utils::path_exists(instdir.path().join("bin/foo"))); assert!(!utils::path_exists(instdir.path().join("lib/bar"))); assert!(!utils::path_exists(instdir.path().join("doc/stuff/doc1"))); assert!(!utils::path_exists(instdir.path().join("doc/stuff/doc2"))); assert!(!utils::path_exists(instdir.path().join("doc/stuff"))); assert!(components.find("mycomponent").unwrap().is_none()); assert!(components.find("mycomponent2").unwrap().is_none()); } // If any single file can't be uninstalled, it is not a fatal error // and the subsequent files will still be removed. #[test] fn uninstall_best_effort() { //unimplemented!() } #[test] fn component_bad_version() { let pkgdir = TempDir::new("rustup").unwrap(); let mock = MockInstallerBuilder { components: vec![MockComponentBuilder { name: "mycomponent".to_string(), files: vec![MockFile::new("bin/foo", b"foo")], }], }; mock.build(pkgdir.path()); let instdir = TempDir::new("rustup").unwrap(); let prefix = InstallPrefix::from(instdir.path().to_owned()); let tmpdir = TempDir::new("rustup").unwrap(); let tmpcfg = temp::Cfg::new( tmpdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ()), ); let notify = |_: Notification<'_>| (); let tx = Transaction::new(prefix.clone(), &tmpcfg, &notify); let components = Components::open(prefix.clone()).unwrap(); let pkg = DirectoryPackage::new(pkgdir.path().to_owned(), true).unwrap(); let tx = pkg.install(&components, "mycomponent", None, tx).unwrap(); tx.commit(); // Write a bogus version to the component manifest directory utils::write_file("", &prefix.manifest_file("rust-installer-version"), "100\n").unwrap(); // Can't open components now let e = Components::open(prefix.clone()).unwrap_err(); if let ErrorKind::BadInstalledMetadataVersion(_) = *e.kind() { } else { panic!() } } // Directories should be 0755, normal files 0644, files that come // from the bin/ directory 0755. #[test] #[cfg(unix)] fn unix_permissions() { use std::fs; use std::os::unix::fs::PermissionsExt; let pkgdir = TempDir::new("rustup").unwrap(); let mock = MockInstallerBuilder { components: vec![MockComponentBuilder { name: "mycomponent".to_string(), files: vec![ MockFile::new("bin/foo", b"foo"), MockFile::new("lib/bar", b"bar"), MockFile::new("lib/foobar", b"foobar").executable(true), MockFile::new_dir( "doc/stuff", &[ ("doc1", b"", false), ("morestuff/doc2", b"", false), ("morestuff/tool", b"", true), ], ), ], }], }; mock.build(pkgdir.path()); let instdir = TempDir::new("rustup").unwrap(); let prefix = InstallPrefix::from(instdir.path().to_owned()); let tmpdir = TempDir::new("rustup").unwrap(); let tmpcfg = temp::Cfg::new( tmpdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ()), ); let notify = |_: Notification<'_>| (); let tx = Transaction::new(prefix.clone(), &tmpcfg, &notify); let components = Components::open(prefix.clone()).unwrap(); let pkg = DirectoryPackage::new(pkgdir.path().to_owned(), true).unwrap(); let tx = pkg.install(&components, "mycomponent", None, tx).unwrap(); tx.commit(); let m = 0o777 & fs::metadata(instdir.path().join("bin/foo")) .unwrap() .permissions() .mode(); assert_eq!(m, 0o755); let m = 0o777 & fs::metadata(instdir.path().join("lib/bar")) .unwrap() .permissions() .mode(); assert_eq!(m, 0o644); let m = 0o777 & fs::metadata(instdir.path().join("lib/foobar")) .unwrap() .permissions() .mode(); assert_eq!(m, 0o755); let m = 0o777 & fs::metadata(instdir.path().join("doc/stuff/")) .unwrap() .permissions() .mode(); assert_eq!(m, 0o755); let m = 0o777 & fs::metadata(instdir.path().join("doc/stuff/doc1")) .unwrap() .permissions() .mode(); assert_eq!(m, 0o644); let m = 0o777 & fs::metadata(instdir.path().join("doc/stuff/morestuff")) .unwrap() .permissions() .mode(); assert_eq!(m, 0o755); let m = 0o777 & fs::metadata(instdir.path().join("doc/stuff/morestuff/doc2")) .unwrap() .permissions() .mode(); assert_eq!(m, 0o644); let m = 0o777 & fs::metadata(instdir.path().join("doc/stuff/morestuff/tool")) .unwrap() .permissions() .mode(); assert_eq!(m, 0o755); } // Installing to a prefix that doesn't exist creates it automatically #[test] fn install_to_prefix_that_does_not_exist() { let pkgdir = TempDir::new("rustup").unwrap(); let mock = MockInstallerBuilder { components: vec![MockComponentBuilder { name: "mycomponent".to_string(), files: vec![MockFile::new("bin/foo", b"foo")], }], }; mock.build(pkgdir.path()); let instdir = TempDir::new("rustup").unwrap(); // The directory that does not exist let does_not_exist = instdir.path().join("super_not_real"); let prefix = InstallPrefix::from(does_not_exist.clone()); let tmpdir = TempDir::new("rustup").unwrap(); let tmpcfg = temp::Cfg::new( tmpdir.path().to_owned(), DEFAULT_DIST_SERVER, Box::new(|_| ()), ); let notify = |_: Notification<'_>| (); let tx = Transaction::new(prefix.clone(), &tmpcfg, &notify); let components = Components::open(prefix.clone()).unwrap(); let pkg = DirectoryPackage::new(pkgdir.path().to_owned(), true).unwrap(); let tx = pkg.install(&components, "mycomponent", None, tx).unwrap(); tx.commit(); assert!(utils::path_exists(does_not_exist.join("bin/foo"))); }
32.276102
98
0.572568
11861d23a0602b6c42a609bedaf1c428e1fe8f28
8,764
mod candidate_uncles; use crate::component::entry::TxEntry; use crate::config::BlockAssemblerConfig; use crate::error::BlockAssemblerError as Error; pub use candidate_uncles::CandidateUncles; use ckb_chain_spec::consensus::Consensus; use ckb_jsonrpc_types::{BlockTemplate, CellbaseTemplate, TransactionTemplate, UncleTemplate}; use ckb_reward_calculator::RewardCalculator; use ckb_snapshot::Snapshot; use ckb_store::ChainStore; use ckb_types::{ bytes::Bytes, core::{ BlockNumber, Capacity, Cycle, EpochExt, HeaderView, TransactionBuilder, TransactionView, UncleBlockView, Version, }, packed::{self, Byte32, CellInput, CellOutput, CellbaseWitness, ProposalShortId, Transaction}, prelude::*, }; use failure::Error as FailureError; use lru_cache::LruCache; use std::collections::HashSet; use std::sync::Arc; use std::sync::{atomic::AtomicU64, atomic::AtomicUsize}; use tokio::sync::lock::Lock; const BLOCK_TEMPLATE_TIMEOUT: u64 = 3000; const TEMPLATE_CACHE_SIZE: usize = 10; pub struct TemplateCache { pub time: u64, pub uncles_updated_at: u64, pub txs_updated_at: u64, pub template: BlockTemplate, } impl TemplateCache { pub fn is_outdate(&self, current_time: u64) -> bool { current_time.saturating_sub(self.time) > BLOCK_TEMPLATE_TIMEOUT } pub fn is_modified(&self, last_uncles_updated_at: u64, last_txs_updated_at: u64) -> bool { last_uncles_updated_at != self.uncles_updated_at || last_txs_updated_at != self.txs_updated_at } } pub type BlockTemplateCacheKey = (Byte32, Cycle, u64, Version); #[derive(Clone)] pub struct BlockAssembler { pub(crate) config: Arc<BlockAssemblerConfig>, pub(crate) work_id: Arc<AtomicUsize>, pub(crate) last_uncles_updated_at: Arc<AtomicU64>, pub(crate) template_caches: Lock<LruCache<BlockTemplateCacheKey, TemplateCache>>, pub(crate) candidate_uncles: Lock<CandidateUncles>, } impl BlockAssembler { pub fn new(config: BlockAssemblerConfig) -> Self { Self { config: Arc::new(config), work_id: Arc::new(AtomicUsize::new(0)), last_uncles_updated_at: Arc::new(AtomicU64::new(0)), template_caches: Lock::new(LruCache::new(TEMPLATE_CACHE_SIZE)), candidate_uncles: Lock::new(CandidateUncles::new()), } } pub(crate) fn transform_params( consensus: &Consensus, bytes_limit: Option<u64>, proposals_limit: Option<u64>, max_version: Option<Version>, ) -> (u64, u64, Version) { let bytes_limit = bytes_limit .min(Some(consensus.max_block_bytes())) .unwrap_or_else(|| consensus.max_block_bytes()); let proposals_limit = proposals_limit .min(Some(consensus.max_block_proposals_limit())) .unwrap_or_else(|| consensus.max_block_proposals_limit()); let version = max_version .min(Some(consensus.block_version())) .unwrap_or_else(|| consensus.block_version()); (bytes_limit, proposals_limit, version) } pub(crate) fn transform_uncle(uncle: &UncleBlockView) -> UncleTemplate { UncleTemplate { hash: uncle.hash().unpack(), required: false, proposals: uncle .data() .proposals() .into_iter() .map(Into::into) .collect(), header: uncle.data().header().into(), } } pub(crate) fn transform_cellbase( tx: &TransactionView, cycles: Option<Cycle>, ) -> CellbaseTemplate { CellbaseTemplate { hash: tx.hash().unpack(), cycles: cycles.map(Into::into), data: tx.data().into(), } } pub(crate) fn transform_tx( tx: &TxEntry, required: bool, depends: Option<Vec<u32>>, ) -> TransactionTemplate { TransactionTemplate { hash: tx.transaction.hash().unpack(), required, cycles: Some(tx.cycles.into()), depends: depends.map(|deps| deps.into_iter().map(|x| u64::from(x).into()).collect()), data: tx.transaction.data().into(), } } pub(crate) fn calculate_txs_size_limit( bytes_limit: u64, cellbase: Transaction, uncles: &[UncleBlockView], proposals: &HashSet<ProposalShortId>, ) -> Result<usize, FailureError> { let empty_dao = packed::Byte32::default(); let raw_header = packed::RawHeader::new_builder().dao(empty_dao).build(); let header = packed::Header::new_builder().raw(raw_header).build(); let block = packed::Block::new_builder() .header(header) .transactions(vec![cellbase].pack()) .uncles(uncles.iter().map(|u| u.data()).pack()) .proposals( proposals .iter() .map(ToOwned::to_owned) .collect::<Vec<_>>() .pack(), ) .build(); let serialized_size = block.serialized_size_without_uncle_proposals(); let bytes_limit = bytes_limit as usize; bytes_limit .checked_sub(serialized_size) .ok_or_else(|| Error::InvalidParams(format!("bytes_limit {}", bytes_limit)).into()) } /// Miner mined block H(c), the block reward will be finalized at H(c + w_far + 1). /// Miner specify own lock in cellbase witness. /// The cellbase have only one output, /// miner should collect the block reward for finalize target H(max(0, c - w_far - 1)) pub(crate) fn build_cellbase( snapshot: &Snapshot, tip: &HeaderView, cellbase_witness: CellbaseWitness, ) -> Result<TransactionView, FailureError> { let candidate_number = tip.number() + 1; let tx = { let (target_lock, block_reward) = RewardCalculator::new(snapshot.consensus(), snapshot).block_reward(tip)?; let input = CellInput::new_cellbase_input(candidate_number); let output = CellOutput::new_builder() .capacity(block_reward.total.pack()) .lock(target_lock) .build(); let witness = cellbase_witness.as_bytes().pack(); let no_finalization_target = candidate_number <= snapshot.consensus().finalization_delay_length(); let tx_builder = TransactionBuilder::default().input(input).witness(witness); let insufficient_reward_to_create_cell = output.is_lack_of_capacity(Capacity::zero())?; if no_finalization_target || insufficient_reward_to_create_cell { tx_builder.build() } else { tx_builder .output(output) .output_data(Bytes::default().pack()) .build() } }; Ok(tx) } // A block B1 is considered to be the uncle of another block B2 if all of the following conditions are met: // (1) they are in the same epoch, sharing the same difficulty; // (2) height(B2) > height(B1); // (3) B1's parent is either B2's ancestor or embedded in B2 or its ancestors as an uncle; // and (4) B2 is the first block in its chain to refer to B1. pub(crate) fn prepare_uncles( snapshot: &Snapshot, candidate_number: BlockNumber, current_epoch_ext: &EpochExt, candidate_uncles: &mut CandidateUncles, ) -> Vec<UncleBlockView> { let epoch_number = current_epoch_ext.number(); let max_uncles_num = snapshot.consensus().max_uncles_num(); let mut uncles: Vec<UncleBlockView> = Vec::with_capacity(max_uncles_num); let mut removed = Vec::new(); for uncle in candidate_uncles.values() { if uncles.len() == max_uncles_num { break; } let parent_hash = uncle.header().parent_hash(); if uncle.compact_target() != current_epoch_ext.compact_target() || uncle.epoch().number() != epoch_number || snapshot.get_block_number(&uncle.hash()).is_some() || snapshot.is_uncle(&uncle.hash()) || !(uncles.iter().any(|u| u.hash() == parent_hash) || snapshot.get_block_number(&parent_hash).is_some() || snapshot.is_uncle(&parent_hash)) || uncle.number() >= candidate_number { removed.push(uncle.clone()); } else { uncles.push(uncle.clone()); } } for r in removed { candidate_uncles.remove(&r); } uncles } }
36.978903
111
0.60372
e2623f788d01c618830dddc169ee8a2dece7f25b
1,256
mod camera; mod font_data; mod image_data; mod mesh_data; mod mesh_group; mod mesh_instance; mod window; use self::{camera::*, font_data::*, image_data::*, mesh_data::*, mesh_group::*, mesh_instance::*, window::*}; use crate::game_graph_driver::GGD_RenderEngine; pub const RENDER_ENGINE: GGD_RenderEngine = GGD_RenderEngine { Name: "nIce Engine".as_ptr() as _, Priority: 10, GraphicsAPI: 100, Validate: None, Shutdown: None, Window_Alloc, Window_Free, Window_IsValid, Window_Resize, Window_SetCamera, Window_SetOverlay, Window_Draw, MeshData_Alloc_Polygon, MeshData_Alloc_Field: None, MeshData_Free, ImageData_Alloc, ImageData_Free, ImageData_ReadPixelData, ImageData_DrawPixelData, ImageData_DrawCamera, ImageData_DrawImage, ImageData_DrawText, FontData_Alloc, FontData_Free, FontData_SetGlyph, MeshGroup_Alloc, MeshGroup_Free, MeshGroup_SetSky, MeshInstance_Alloc, MeshInstance_Free, MeshInstance_SetMeshData, MeshInstance_SetMeshSubset, MeshInstance_SetImageData, MeshInstance_SetAnimation, MeshInstance_SetTransform, MeshInstance_SetBoneTransform, Camera_Alloc, Camera_Free, Camera_SetPerspective, Camera_SetOrthographic: None, Camera_SetParabolic: None, Camera_SetMeshGroup, Camera_SetTransform, };
19.625
109
0.806529
481527f04b1ee267da0b93ba9b1b7ccc26d1709c
2,587
// Copyright 2019 Mats Kindahl // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. use crate::devices::DeviceUpdate; use crate::state::State; use crate::view::ViewUpdate; use bytes::BytesMut; use serde_cbor::{from_slice, to_vec}; use std::net::SocketAddr; use tokio::codec::{Decoder, Encoder}; use uuid::Uuid; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum Gossip { DebugMessage { text: String }, DeviceGossip(DeviceUpdate), ViewGossip(ViewUpdate), } impl Gossip { pub fn update_state( &self, state: &mut State, sender: &Uuid, timestamp_millis: i64, peer: &SocketAddr, ) { match self { Gossip::DebugMessage { text } => info!("From {} {}", peer, text), Gossip::DeviceGossip(device_gossip) => { state.update_devices(device_gossip, sender, timestamp_millis) } Gossip::ViewGossip(view_gossip) => { state.update_view(view_gossip, sender, timestamp_millis) } } } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Message { pub sender: Uuid, pub timestamp_millis: i64, pub hops: u32, pub payload: Option<Gossip>, } impl Message { pub fn update_state(&self, state: &mut State, peer: &SocketAddr) { if let Some(ref gossip) = self.payload { gossip.update_state(state, &self.sender, self.timestamp_millis, peer) } } } pub struct GossipCodec; impl GossipCodec { pub fn new() -> GossipCodec { GossipCodec {} } } impl Encoder for GossipCodec { type Item = Message; type Error = std::io::Error; fn encode(&mut self, item: Self::Item, buf: &mut BytesMut) -> std::io::Result<()> { let bytes = to_vec(&item).unwrap(); buf.extend_from_slice(&bytes); Ok(()) } } impl Decoder for GossipCodec { type Item = Message; type Error = std::io::Error; fn decode(&mut self, buf: &mut BytesMut) -> std::io::Result<Option<Self::Item>> { Ok(from_slice(&buf).unwrap()) } }
26.947917
87
0.635872
d6a0e604de841a8aaf3a9c558330ff1a6f09142a
17,396
// Generated by gir (https://github.com/gtk-rs/gir @ ee37253c10af) // from gir-files (https://github.com/gtk-rs/gir-files @ 5502d32880f5) // from gst-gir-files (https://gitlab.freedesktop.org/gstreamer/gir-files-rs.git @ f05404723520) // DO NOT EDIT #![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)] #![allow( clippy::approx_constant, clippy::type_complexity, clippy::unreadable_literal, clippy::upper_case_acronyms )] #![cfg_attr(feature = "dox", feature(doc_cfg))] #[allow(unused_imports)] use libc::{ c_char, c_double, c_float, c_int, c_long, c_short, c_uchar, c_uint, c_ulong, c_ushort, c_void, intptr_t, size_t, ssize_t, uintptr_t, FILE, }; #[allow(unused_imports)] use glib::{gboolean, gconstpointer, gpointer, GType}; // Callbacks pub type GstHarnessPrepareBufferFunc = Option<unsafe extern "C" fn(*mut GstHarness, gpointer) -> *mut gst::GstBuffer>; pub type GstHarnessPrepareEventFunc = Option<unsafe extern "C" fn(*mut GstHarness, gpointer) -> *mut gst::GstEvent>; // Records #[derive(Copy, Clone)] #[repr(C)] pub struct GstHarness { pub element: *mut gst::GstElement, pub srcpad: *mut gst::GstPad, pub sinkpad: *mut gst::GstPad, pub src_harness: *mut GstHarness, pub sink_harness: *mut GstHarness, pub priv_: *mut GstHarnessPrivate, } impl ::std::fmt::Debug for GstHarness { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstHarness @ {:p}", self)) .field("element", &self.element) .field("srcpad", &self.srcpad) .field("sinkpad", &self.sinkpad) .field("src_harness", &self.src_harness) .field("sink_harness", &self.sink_harness) .finish() } } #[repr(C)] pub struct _GstHarnessPrivate { _data: [u8; 0], _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>, } pub type GstHarnessPrivate = *mut _GstHarnessPrivate; #[repr(C)] pub struct _GstHarnessThread { _data: [u8; 0], _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>, } pub type GstHarnessThread = *mut _GstHarnessThread; #[repr(C)] pub struct _GstStreamConsistency { _data: [u8; 0], _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>, } pub type GstStreamConsistency = *mut _GstStreamConsistency; #[derive(Copy, Clone)] #[repr(C)] pub struct GstTestClockClass { pub parent_class: gst::GstClockClass, } impl ::std::fmt::Debug for GstTestClockClass { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstTestClockClass @ {:p}", self)) .field("parent_class", &self.parent_class) .finish() } } #[repr(C)] pub struct _GstTestClockPrivate { _data: [u8; 0], _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>, } pub type GstTestClockPrivate = *mut _GstTestClockPrivate; // Classes #[derive(Copy, Clone)] #[repr(C)] pub struct GstTestClock { pub parent: gst::GstClock, pub priv_: *mut GstTestClockPrivate, } impl ::std::fmt::Debug for GstTestClock { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstTestClock @ {:p}", self)) .field("parent", &self.parent) .finish() } } #[link(name = "gstcheck-1.0")] extern "C" { //========================================================================= // GstHarness //========================================================================= pub fn gst_harness_add_element_full( h: *mut GstHarness, element: *mut gst::GstElement, hsrc: *mut gst::GstStaticPadTemplate, element_sinkpad_name: *const c_char, hsink: *mut gst::GstStaticPadTemplate, element_srcpad_name: *const c_char, ); pub fn gst_harness_add_element_sink_pad(h: *mut GstHarness, sinkpad: *mut gst::GstPad); pub fn gst_harness_add_element_src_pad(h: *mut GstHarness, srcpad: *mut gst::GstPad); pub fn gst_harness_add_parse(h: *mut GstHarness, launchline: *const c_char); pub fn gst_harness_add_probe( h: *mut GstHarness, element_name: *const c_char, pad_name: *const c_char, mask: gst::GstPadProbeType, callback: gst::GstPadProbeCallback, user_data: gpointer, destroy_data: glib::GDestroyNotify, ); #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_harness_add_propose_allocation_meta( h: *mut GstHarness, api: GType, params: *const gst::GstStructure, ); pub fn gst_harness_add_sink(h: *mut GstHarness, sink_element_name: *const c_char); pub fn gst_harness_add_sink_harness(h: *mut GstHarness, sink_harness: *mut GstHarness); pub fn gst_harness_add_sink_parse(h: *mut GstHarness, launchline: *const c_char); pub fn gst_harness_add_src( h: *mut GstHarness, src_element_name: *const c_char, has_clock_wait: gboolean, ); pub fn gst_harness_add_src_harness( h: *mut GstHarness, src_harness: *mut GstHarness, has_clock_wait: gboolean, ); pub fn gst_harness_add_src_parse( h: *mut GstHarness, launchline: *const c_char, has_clock_wait: gboolean, ); pub fn gst_harness_buffers_in_queue(h: *mut GstHarness) -> c_uint; pub fn gst_harness_buffers_received(h: *mut GstHarness) -> c_uint; pub fn gst_harness_crank_multiple_clock_waits(h: *mut GstHarness, waits: c_uint) -> gboolean; pub fn gst_harness_crank_single_clock_wait(h: *mut GstHarness) -> gboolean; pub fn gst_harness_create_buffer(h: *mut GstHarness, size: size_t) -> *mut gst::GstBuffer; pub fn gst_harness_dump_to_file(h: *mut GstHarness, filename: *const c_char); pub fn gst_harness_events_in_queue(h: *mut GstHarness) -> c_uint; pub fn gst_harness_events_received(h: *mut GstHarness) -> c_uint; pub fn gst_harness_find_element( h: *mut GstHarness, element_name: *const c_char, ) -> *mut gst::GstElement; pub fn gst_harness_get( h: *mut GstHarness, element_name: *const c_char, first_property_name: *const c_char, ... ); pub fn gst_harness_get_allocator( h: *mut GstHarness, allocator: *mut *mut gst::GstAllocator, params: *mut gst::GstAllocationParams, ); pub fn gst_harness_get_last_pushed_timestamp(h: *mut GstHarness) -> gst::GstClockTime; pub fn gst_harness_get_testclock(h: *mut GstHarness) -> *mut GstTestClock; pub fn gst_harness_play(h: *mut GstHarness); pub fn gst_harness_pull(h: *mut GstHarness) -> *mut gst::GstBuffer; pub fn gst_harness_pull_event(h: *mut GstHarness) -> *mut gst::GstEvent; #[cfg(any(feature = "v1_18", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_18")))] pub fn gst_harness_pull_until_eos( h: *mut GstHarness, buf: *mut *mut gst::GstBuffer, ) -> gboolean; pub fn gst_harness_pull_upstream_event(h: *mut GstHarness) -> *mut gst::GstEvent; pub fn gst_harness_push(h: *mut GstHarness, buffer: *mut gst::GstBuffer) -> gst::GstFlowReturn; pub fn gst_harness_push_and_pull( h: *mut GstHarness, buffer: *mut gst::GstBuffer, ) -> *mut gst::GstBuffer; pub fn gst_harness_push_event(h: *mut GstHarness, event: *mut gst::GstEvent) -> gboolean; pub fn gst_harness_push_from_src(h: *mut GstHarness) -> gst::GstFlowReturn; pub fn gst_harness_push_to_sink(h: *mut GstHarness) -> gst::GstFlowReturn; pub fn gst_harness_push_upstream_event( h: *mut GstHarness, event: *mut gst::GstEvent, ) -> gboolean; pub fn gst_harness_query_latency(h: *mut GstHarness) -> gst::GstClockTime; pub fn gst_harness_set( h: *mut GstHarness, element_name: *const c_char, first_property_name: *const c_char, ... ); pub fn gst_harness_set_blocking_push_mode(h: *mut GstHarness); pub fn gst_harness_set_caps(h: *mut GstHarness, in_: *mut gst::GstCaps, out: *mut gst::GstCaps); pub fn gst_harness_set_caps_str(h: *mut GstHarness, in_: *const c_char, out: *const c_char); pub fn gst_harness_set_drop_buffers(h: *mut GstHarness, drop_buffers: gboolean); pub fn gst_harness_set_forwarding(h: *mut GstHarness, forwarding: gboolean); #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_harness_set_live(h: *mut GstHarness, is_live: gboolean); pub fn gst_harness_set_propose_allocator( h: *mut GstHarness, allocator: *mut gst::GstAllocator, params: *const gst::GstAllocationParams, ); pub fn gst_harness_set_sink_caps(h: *mut GstHarness, caps: *mut gst::GstCaps); pub fn gst_harness_set_sink_caps_str(h: *mut GstHarness, str: *const c_char); pub fn gst_harness_set_src_caps(h: *mut GstHarness, caps: *mut gst::GstCaps); pub fn gst_harness_set_src_caps_str(h: *mut GstHarness, str: *const c_char); pub fn gst_harness_set_time(h: *mut GstHarness, time: gst::GstClockTime) -> gboolean; pub fn gst_harness_set_upstream_latency(h: *mut GstHarness, latency: gst::GstClockTime); pub fn gst_harness_sink_push_many(h: *mut GstHarness, pushes: c_int) -> gst::GstFlowReturn; pub fn gst_harness_src_crank_and_push_many( h: *mut GstHarness, cranks: c_int, pushes: c_int, ) -> gst::GstFlowReturn; pub fn gst_harness_src_push_event(h: *mut GstHarness) -> gboolean; pub fn gst_harness_stress_custom_start( h: *mut GstHarness, init: glib::GFunc, callback: glib::GFunc, data: gpointer, sleep: c_ulong, ) -> *mut GstHarnessThread; pub fn gst_harness_stress_property_start_full( h: *mut GstHarness, name: *const c_char, value: *const gobject::GValue, sleep: c_ulong, ) -> *mut GstHarnessThread; pub fn gst_harness_stress_push_buffer_start_full( h: *mut GstHarness, caps: *mut gst::GstCaps, segment: *const gst::GstSegment, buf: *mut gst::GstBuffer, sleep: c_ulong, ) -> *mut GstHarnessThread; pub fn gst_harness_stress_push_buffer_with_cb_start_full( h: *mut GstHarness, caps: *mut gst::GstCaps, segment: *const gst::GstSegment, func: GstHarnessPrepareBufferFunc, data: gpointer, notify: glib::GDestroyNotify, sleep: c_ulong, ) -> *mut GstHarnessThread; pub fn gst_harness_stress_push_event_start_full( h: *mut GstHarness, event: *mut gst::GstEvent, sleep: c_ulong, ) -> *mut GstHarnessThread; pub fn gst_harness_stress_push_event_with_cb_start_full( h: *mut GstHarness, func: GstHarnessPrepareEventFunc, data: gpointer, notify: glib::GDestroyNotify, sleep: c_ulong, ) -> *mut GstHarnessThread; pub fn gst_harness_stress_push_upstream_event_start_full( h: *mut GstHarness, event: *mut gst::GstEvent, sleep: c_ulong, ) -> *mut GstHarnessThread; pub fn gst_harness_stress_push_upstream_event_with_cb_start_full( h: *mut GstHarness, func: GstHarnessPrepareEventFunc, data: gpointer, notify: glib::GDestroyNotify, sleep: c_ulong, ) -> *mut GstHarnessThread; pub fn gst_harness_stress_requestpad_start_full( h: *mut GstHarness, templ: *mut gst::GstPadTemplate, name: *const c_char, caps: *mut gst::GstCaps, release: gboolean, sleep: c_ulong, ) -> *mut GstHarnessThread; pub fn gst_harness_stress_statechange_start_full( h: *mut GstHarness, sleep: c_ulong, ) -> *mut GstHarnessThread; #[cfg(any(feature = "v1_14", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_14")))] pub fn gst_harness_take_all_data(h: *mut GstHarness, size: *mut size_t) -> *mut u8; #[cfg(any(feature = "v1_14", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_14")))] pub fn gst_harness_take_all_data_as_buffer(h: *mut GstHarness) -> *mut gst::GstBuffer; #[cfg(any(feature = "v1_14", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_14")))] pub fn gst_harness_take_all_data_as_bytes(h: *mut GstHarness) -> *mut glib::GBytes; pub fn gst_harness_teardown(h: *mut GstHarness); pub fn gst_harness_try_pull(h: *mut GstHarness) -> *mut gst::GstBuffer; pub fn gst_harness_try_pull_event(h: *mut GstHarness) -> *mut gst::GstEvent; pub fn gst_harness_try_pull_upstream_event(h: *mut GstHarness) -> *mut gst::GstEvent; pub fn gst_harness_upstream_events_in_queue(h: *mut GstHarness) -> c_uint; pub fn gst_harness_upstream_events_received(h: *mut GstHarness) -> c_uint; pub fn gst_harness_use_systemclock(h: *mut GstHarness); pub fn gst_harness_use_testclock(h: *mut GstHarness); pub fn gst_harness_wait_for_clock_id_waits( h: *mut GstHarness, waits: c_uint, timeout: c_uint, ) -> gboolean; pub fn gst_harness_new(element_name: *const c_char) -> *mut GstHarness; pub fn gst_harness_new_empty() -> *mut GstHarness; pub fn gst_harness_new_full( element: *mut gst::GstElement, hsrc: *mut gst::GstStaticPadTemplate, element_sinkpad_name: *const c_char, hsink: *mut gst::GstStaticPadTemplate, element_srcpad_name: *const c_char, ) -> *mut GstHarness; pub fn gst_harness_new_parse(launchline: *const c_char) -> *mut GstHarness; pub fn gst_harness_new_with_element( element: *mut gst::GstElement, element_sinkpad_name: *const c_char, element_srcpad_name: *const c_char, ) -> *mut GstHarness; pub fn gst_harness_new_with_padnames( element_name: *const c_char, element_sinkpad_name: *const c_char, element_srcpad_name: *const c_char, ) -> *mut GstHarness; pub fn gst_harness_new_with_templates( element_name: *const c_char, hsrc: *mut gst::GstStaticPadTemplate, hsink: *mut gst::GstStaticPadTemplate, ) -> *mut GstHarness; pub fn gst_harness_stress_thread_stop(t: *mut GstHarnessThread) -> c_uint; //========================================================================= // GstTestClock //========================================================================= pub fn gst_test_clock_get_type() -> GType; pub fn gst_test_clock_new() -> *mut gst::GstClock; pub fn gst_test_clock_new_with_start_time(start_time: gst::GstClockTime) -> *mut gst::GstClock; pub fn gst_test_clock_id_list_get_latest_time( pending_list: *const glib::GList, ) -> gst::GstClockTime; pub fn gst_test_clock_advance_time(test_clock: *mut GstTestClock, delta: gst::GstClockTimeDiff); pub fn gst_test_clock_crank(test_clock: *mut GstTestClock) -> gboolean; pub fn gst_test_clock_get_next_entry_time(test_clock: *mut GstTestClock) -> gst::GstClockTime; pub fn gst_test_clock_has_id(test_clock: *mut GstTestClock, id: gst::GstClockID) -> gboolean; pub fn gst_test_clock_peek_id_count(test_clock: *mut GstTestClock) -> c_uint; pub fn gst_test_clock_peek_next_pending_id( test_clock: *mut GstTestClock, pending_id: *mut gst::GstClockID, ) -> gboolean; #[cfg(any(feature = "v1_18", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_18")))] pub fn gst_test_clock_process_id( test_clock: *mut GstTestClock, pending_id: gst::GstClockID, ) -> gboolean; pub fn gst_test_clock_process_id_list( test_clock: *mut GstTestClock, pending_list: *const glib::GList, ) -> c_uint; pub fn gst_test_clock_process_next_clock_id(test_clock: *mut GstTestClock) -> gst::GstClockID; pub fn gst_test_clock_set_time(test_clock: *mut GstTestClock, new_time: gst::GstClockTime); #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_test_clock_timed_wait_for_multiple_pending_ids( test_clock: *mut GstTestClock, count: c_uint, timeout_ms: c_uint, pending_list: *mut *mut glib::GList, ) -> gboolean; pub fn gst_test_clock_wait_for_multiple_pending_ids( test_clock: *mut GstTestClock, count: c_uint, pending_list: *mut *mut glib::GList, ); pub fn gst_test_clock_wait_for_next_pending_id( test_clock: *mut GstTestClock, pending_id: *mut gst::GstClockID, ); pub fn gst_test_clock_wait_for_pending_id_count(test_clock: *mut GstTestClock, count: c_uint); //========================================================================= // Other functions //========================================================================= pub fn gst_consistency_checker_add_pad( consist: *mut GstStreamConsistency, pad: *mut gst::GstPad, ) -> gboolean; pub fn gst_consistency_checker_free(consist: *mut GstStreamConsistency); pub fn gst_consistency_checker_new(pad: *mut gst::GstPad) -> *mut GstStreamConsistency; pub fn gst_consistency_checker_reset(consist: *mut GstStreamConsistency); }
41.222749
100
0.656415
2fc12cdeb6d80972366fc7391498c2b76cd9e2de
8,937
#[doc = "Register `PRSET2` writer"] pub struct W(crate::W<PRSET2_SPEC>); impl core::ops::Deref for W { type Target = crate::W<PRSET2_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<PRSET2_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<PRSET2_SPEC>) -> Self { W(writer) } } #[doc = "WDT Reset Assert\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum WDTRS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: Assert reset"] VALUE2 = 1, } impl From<WDTRS_AW> for bool { #[inline(always)] fn from(variant: WDTRS_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `WDTRS` writer - WDT Reset Assert"] pub struct WDTRS_W<'a> { w: &'a mut W, } impl<'a> WDTRS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: WDTRS_AW) -> &'a mut W { self.bit(variant.into()) } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(WDTRS_AW::VALUE1) } #[doc = "Assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(WDTRS_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1); self.w } } #[doc = "ETH0 Reset Assert\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ETH0RS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: Assert reset"] VALUE2 = 1, } impl From<ETH0RS_AW> for bool { #[inline(always)] fn from(variant: ETH0RS_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `ETH0RS` writer - ETH0 Reset Assert"] pub struct ETH0RS_W<'a> { w: &'a mut W, } impl<'a> ETH0RS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ETH0RS_AW) -> &'a mut W { self.bit(variant.into()) } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(ETH0RS_AW::VALUE1) } #[doc = "Assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(ETH0RS_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | ((value as u32 & 0x01) << 2); self.w } } #[doc = "DMA0 Reset Assert\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DMA0RS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: Assert reset"] VALUE2 = 1, } impl From<DMA0RS_AW> for bool { #[inline(always)] fn from(variant: DMA0RS_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `DMA0RS` writer - DMA0 Reset Assert"] pub struct DMA0RS_W<'a> { w: &'a mut W, } impl<'a> DMA0RS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DMA0RS_AW) -> &'a mut W { self.bit(variant.into()) } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(DMA0RS_AW::VALUE1) } #[doc = "Assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(DMA0RS_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u32 & 0x01) << 4); self.w } } #[doc = "FCE Reset Assert\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FCERS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: Assert reset"] VALUE2 = 1, } impl From<FCERS_AW> for bool { #[inline(always)] fn from(variant: FCERS_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `FCERS` writer - FCE Reset Assert"] pub struct FCERS_W<'a> { w: &'a mut W, } impl<'a> FCERS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FCERS_AW) -> &'a mut W { self.bit(variant.into()) } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(FCERS_AW::VALUE1) } #[doc = "Assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(FCERS_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | ((value as u32 & 0x01) << 6); self.w } } #[doc = "USB Reset Assert\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USBRS_AW { #[doc = "0: No effect"] VALUE1 = 0, #[doc = "1: Assert reset"] VALUE2 = 1, } impl From<USBRS_AW> for bool { #[inline(always)] fn from(variant: USBRS_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `USBRS` writer - USB Reset Assert"] pub struct USBRS_W<'a> { w: &'a mut W, } impl<'a> USBRS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USBRS_AW) -> &'a mut W { self.bit(variant.into()) } #[doc = "No effect"] #[inline(always)] pub fn value1(self) -> &'a mut W { self.variant(USBRS_AW::VALUE1) } #[doc = "Assert reset"] #[inline(always)] pub fn value2(self) -> &'a mut W { self.variant(USBRS_AW::VALUE2) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | ((value as u32 & 0x01) << 7); self.w } } impl W { #[doc = "Bit 1 - WDT Reset Assert"] #[inline(always)] pub fn wdtrs(&mut self) -> WDTRS_W { WDTRS_W { w: self } } #[doc = "Bit 2 - ETH0 Reset Assert"] #[inline(always)] pub fn eth0rs(&mut self) -> ETH0RS_W { ETH0RS_W { w: self } } #[doc = "Bit 4 - DMA0 Reset Assert"] #[inline(always)] pub fn dma0rs(&mut self) -> DMA0RS_W { DMA0RS_W { w: self } } #[doc = "Bit 6 - FCE Reset Assert"] #[inline(always)] pub fn fcers(&mut self) -> FCERS_W { FCERS_W { w: self } } #[doc = "Bit 7 - USB Reset Assert"] #[inline(always)] pub fn usbrs(&mut self) -> USBRS_W { USBRS_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 = "RCU Peripheral 2 Reset Set\n\nThis register you can [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [prset2](index.html) module"] pub struct PRSET2_SPEC; impl crate::RegisterSpec for PRSET2_SPEC { type Ux = u32; } #[doc = "`write(|w| ..)` method takes [prset2::W](W) writer structure"] impl crate::Writable for PRSET2_SPEC { type Writer = W; } #[doc = "`reset()` method sets PRSET2 to value 0"] impl crate::Resettable for PRSET2_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
27.41411
335
0.548059
23b548dacd45303e75dbb651f79e3a36457b3a9d
25,730
//! Lower-level client connection API. //! //! The types in this module are to provide a lower-level API based around a //! single connection. Connecting to a host, pooling connections, and the like //! are not handled at this level. This module provides the building blocks to //! customize those things externally. //! //! If don't have need to manage connections yourself, consider using the //! higher-level [Client](super) API. //! //! ## Example //! A simple example that uses the `SendRequest` struct to talk HTTP over a Tokio TCP stream //! ```no_run //! # #[cfg(all(feature = "client", feature = "http1", feature = "runtime"))] //! # mod rt { //! use http::{Request, StatusCode}; //! use hyper::{client::conn::Builder, Body}; //! use tokio::net::TcpStream; //! //! #[tokio::main] //! async fn main() -> Result<(), Box<dyn std::error::Error>> { //! let target_stream = TcpStream::connect("example.com:80").await?; //! //! let (mut request_sender, connection) = Builder::new() //! .handshake::<TcpStream, Body>(target_stream) //! .await?; //! //! // spawn a task to poll the connection and drive the HTTP state //! tokio::spawn(async move { //! if let Err(e) = connection.await { //! eprintln!("Error in connection: {}", e); //! } //! }); //! //! let request = Request::builder() //! // We need to manually add the host header because SendRequest does not //! .header("Host", "example.com") //! .method("GET") //! .body(Body::from(""))?; //! //! let response = request_sender.send_request(request).await?; //! assert!(response.status() == StatusCode::OK); //! Ok(()) //! } //! //! # } //! ``` use std::error::Error as StdError; use std::fmt; #[cfg(feature = "http2")] use std::marker::PhantomData; use std::sync::Arc; #[cfg(feature = "runtime")] #[cfg(feature = "http2")] use std::time::Duration; use bytes::Bytes; use futures_util::future::{self, Either, FutureExt as _}; use pin_project::pin_project; use tokio::io::{AsyncRead, AsyncWrite}; use tower_service::Service; use super::dispatch; use crate::body::HttpBody; use crate::common::{task, exec::{BoxSendFuture, Exec}, Future, Pin, Poll}; use crate::proto; use crate::rt::Executor; #[cfg(feature = "http1")] use crate::upgrade::Upgraded; use crate::{Body, Request, Response}; #[cfg(feature = "http1")] type Http1Dispatcher<T, B, R> = proto::dispatch::Dispatcher<proto::dispatch::Client<B>, B, T, R>; #[pin_project(project = ProtoClientProj)] enum ProtoClient<T, B> where B: HttpBody, { #[cfg(feature = "http1")] H1(#[pin] Http1Dispatcher<T, B, proto::h1::ClientTransaction>), #[cfg(feature = "http2")] H2(#[pin] proto::h2::ClientTask<B>, PhantomData<fn(T)>), } /// Returns a handshake future over some IO. /// /// This is a shortcut for `Builder::new().handshake(io)`. pub async fn handshake<T>( io: T, ) -> crate::Result<(SendRequest<crate::Body>, Connection<T, crate::Body>)> where T: AsyncRead + AsyncWrite + Unpin + Send + 'static, { Builder::new().handshake(io).await } /// The sender side of an established connection. pub struct SendRequest<B> { dispatch: dispatch::Sender<Request<B>, Response<Body>>, } /// A future that processes all HTTP state for the IO object. /// /// In most cases, this should just be spawned into an executor, so that it /// can process incoming and outgoing messages, notice hangups, and the like. #[must_use = "futures do nothing unless polled"] pub struct Connection<T, B> where T: AsyncRead + AsyncWrite + Send + 'static, B: HttpBody + 'static, { inner: Option<ProtoClient<T, B>>, } /// A builder to configure an HTTP connection. /// /// After setting options, the builder is used to create a handshake future. #[derive(Clone, Debug)] pub struct Builder { pub(super) exec: Exec, h1_title_case_headers: bool, h1_read_buf_exact_size: Option<usize>, h1_max_buf_size: Option<usize>, #[cfg(feature = "http2")] h2_builder: proto::h2::client::Config, version: Proto, } #[derive(Clone, Debug)] enum Proto { #[cfg(feature = "http1")] Http1, #[cfg(feature = "http2")] Http2, } /// A future returned by `SendRequest::send_request`. /// /// Yields a `Response` if successful. #[must_use = "futures do nothing unless polled"] pub struct ResponseFuture { inner: ResponseFutureState, } enum ResponseFutureState { Waiting(dispatch::Promise<Response<Body>>), // Option is to be able to `take()` it in `poll` Error(Option<crate::Error>), } /// Deconstructed parts of a `Connection`. /// /// This allows taking apart a `Connection` at a later time, in order to /// reclaim the IO object, and additional related pieces. #[derive(Debug)] pub struct Parts<T> { /// The original IO object used in the handshake. pub io: T, /// A buffer of bytes that have been read but not processed as HTTP. /// /// For instance, if the `Connection` is used for an HTTP upgrade request, /// it is possible the server sent back the first bytes of the new protocol /// along with the response upgrade. /// /// You will want to check for any existing bytes if you plan to continue /// communicating on the IO object. pub read_buf: Bytes, _inner: (), } // ========== internal client api // A `SendRequest` that can be cloned to send HTTP2 requests. // private for now, probably not a great idea of a type... #[must_use = "futures do nothing unless polled"] #[cfg(feature = "http2")] pub(super) struct Http2SendRequest<B> { dispatch: dispatch::UnboundedSender<Request<B>, Response<Body>>, } // ===== impl SendRequest impl<B> SendRequest<B> { /// Polls to determine whether this sender can be used yet for a request. /// /// If the associated connection is closed, this returns an Error. pub fn poll_ready(&mut self, cx: &mut task::Context<'_>) -> Poll<crate::Result<()>> { self.dispatch.poll_ready(cx) } pub(super) fn when_ready(self) -> impl Future<Output = crate::Result<Self>> { let mut me = Some(self); future::poll_fn(move |cx| { ready!(me.as_mut().unwrap().poll_ready(cx))?; Poll::Ready(Ok(me.take().unwrap())) }) } pub(super) fn is_ready(&self) -> bool { self.dispatch.is_ready() } pub(super) fn is_closed(&self) -> bool { self.dispatch.is_closed() } #[cfg(feature = "http2")] pub(super) fn into_http2(self) -> Http2SendRequest<B> { Http2SendRequest { dispatch: self.dispatch.unbound(), } } } impl<B> SendRequest<B> where B: HttpBody + 'static, { /// Sends a `Request` on the associated connection. /// /// Returns a future that if successful, yields the `Response`. /// /// # Note /// /// There are some key differences in what automatic things the `Client` /// does for you that will not be done here: /// /// - `Client` requires absolute-form `Uri`s, since the scheme and /// authority are needed to connect. They aren't required here. /// - Since the `Client` requires absolute-form `Uri`s, it can add /// the `Host` header based on it. You must add a `Host` header yourself /// before calling this method. /// - Since absolute-form `Uri`s are not required, if received, they will /// be serialized as-is. /// /// # Example /// /// ``` /// # use http::header::HOST; /// # use hyper::client::conn::SendRequest; /// # use hyper::Body; /// use hyper::Request; /// /// # async fn doc(mut tx: SendRequest<Body>) -> hyper::Result<()> { /// // build a Request /// let req = Request::builder() /// .uri("/foo/bar") /// .header(HOST, "hyper.rs") /// .body(Body::empty()) /// .unwrap(); /// /// // send it and await a Response /// let res = tx.send_request(req).await?; /// // assert the Response /// assert!(res.status().is_success()); /// # Ok(()) /// # } /// # fn main() {} /// ``` pub fn send_request(&mut self, req: Request<B>) -> ResponseFuture { let inner = match self.dispatch.send(req) { Ok(rx) => ResponseFutureState::Waiting(rx), Err(_req) => { debug!("connection was not ready"); let err = crate::Error::new_canceled().with("connection was not ready"); ResponseFutureState::Error(Some(err)) } }; ResponseFuture { inner } } pub(crate) fn send_request_retryable( &mut self, req: Request<B>, ) -> impl Future<Output = Result<Response<Body>, (crate::Error, Option<Request<B>>)>> + Unpin where B: Send, { match self.dispatch.try_send(req) { Ok(rx) => { Either::Left(rx.then(move |res| { match res { Ok(Ok(res)) => future::ok(res), Ok(Err(err)) => future::err(err), // this is definite bug if it happens, but it shouldn't happen! Err(_) => panic!("dispatch dropped without returning error"), } })) } Err(req) => { debug!("connection was not ready"); let err = crate::Error::new_canceled().with("connection was not ready"); Either::Right(future::err((err, Some(req)))) } } } } impl<B> Service<Request<B>> for SendRequest<B> where B: HttpBody + 'static, { type Response = Response<Body>; type Error = crate::Error; type Future = ResponseFuture; fn poll_ready(&mut self, cx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> { self.poll_ready(cx) } fn call(&mut self, req: Request<B>) -> Self::Future { self.send_request(req) } } impl<B> fmt::Debug for SendRequest<B> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SendRequest").finish() } } // ===== impl Http2SendRequest #[cfg(feature = "http2")] impl<B> Http2SendRequest<B> { pub(super) fn is_ready(&self) -> bool { self.dispatch.is_ready() } pub(super) fn is_closed(&self) -> bool { self.dispatch.is_closed() } } #[cfg(feature = "http2")] impl<B> Http2SendRequest<B> where B: HttpBody + 'static, { pub(super) fn send_request_retryable( &mut self, req: Request<B>, ) -> impl Future<Output = Result<Response<Body>, (crate::Error, Option<Request<B>>)>> where B: Send, { match self.dispatch.try_send(req) { Ok(rx) => { Either::Left(rx.then(move |res| { match res { Ok(Ok(res)) => future::ok(res), Ok(Err(err)) => future::err(err), // this is definite bug if it happens, but it shouldn't happen! Err(_) => panic!("dispatch dropped without returning error"), } })) } Err(req) => { debug!("connection was not ready"); let err = crate::Error::new_canceled().with("connection was not ready"); Either::Right(future::err((err, Some(req)))) } } } } #[cfg(feature = "http2")] impl<B> fmt::Debug for Http2SendRequest<B> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Http2SendRequest").finish() } } #[cfg(feature = "http2")] impl<B> Clone for Http2SendRequest<B> { fn clone(&self) -> Self { Http2SendRequest { dispatch: self.dispatch.clone(), } } } // ===== impl Connection impl<T, B> Connection<T, B> where T: AsyncRead + AsyncWrite + Unpin + Send + 'static, B: HttpBody + Unpin + Send + 'static, B::Data: Send, B::Error: Into<Box<dyn StdError + Send + Sync>>, { /// Return the inner IO object, and additional information. /// /// Only works for HTTP/1 connections. HTTP/2 connections will panic. pub fn into_parts(self) -> Parts<T> { match self.inner.expect("already upgraded") { #[cfg(feature = "http1")] ProtoClient::H1(h1) => { let (io, read_buf, _) = h1.into_inner(); Parts { io, read_buf, _inner: (), } } #[cfg(feature = "http2")] ProtoClient::H2(..) => { panic!("http2 cannot into_inner"); } } } /// Poll the connection for completion, but without calling `shutdown` /// on the underlying IO. /// /// This is useful to allow running a connection while doing an HTTP /// upgrade. Once the upgrade is completed, the connection would be "done", /// but it is not desired to actually shutdown the IO object. Instead you /// would take it back using `into_parts`. /// /// Use [`poll_fn`](https://docs.rs/futures/0.1.25/futures/future/fn.poll_fn.html) /// and [`try_ready!`](https://docs.rs/futures/0.1.25/futures/macro.try_ready.html) /// to work with this function; or use the `without_shutdown` wrapper. pub fn poll_without_shutdown(&mut self, cx: &mut task::Context<'_>) -> Poll<crate::Result<()>> { match *self.inner.as_mut().expect("already upgraded") { #[cfg(feature = "http1")] ProtoClient::H1(ref mut h1) => h1.poll_without_shutdown(cx), #[cfg(feature = "http2")] ProtoClient::H2(ref mut h2, _) => Pin::new(h2).poll(cx).map_ok(|_| ()), } } /// Prevent shutdown of the underlying IO object at the end of service the request, /// instead run `into_parts`. This is a convenience wrapper over `poll_without_shutdown`. pub fn without_shutdown(self) -> impl Future<Output = crate::Result<Parts<T>>> { let mut conn = Some(self); future::poll_fn(move |cx| -> Poll<crate::Result<Parts<T>>> { ready!(conn.as_mut().unwrap().poll_without_shutdown(cx))?; Poll::Ready(Ok(conn.take().unwrap().into_parts())) }) } } impl<T, B> Future for Connection<T, B> where T: AsyncRead + AsyncWrite + Unpin + Send + 'static, B: HttpBody + Send + 'static, B::Data: Send, B::Error: Into<Box<dyn StdError + Send + Sync>>, { type Output = crate::Result<()>; fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> { match ready!(Pin::new(self.inner.as_mut().unwrap()).poll(cx))? { proto::Dispatched::Shutdown => Poll::Ready(Ok(())), #[cfg(feature = "http1")] proto::Dispatched::Upgrade(pending) => match self.inner.take() { Some(ProtoClient::H1(h1)) => { let (io, buf, _) = h1.into_inner(); pending.fulfill(Upgraded::new(io, buf)); Poll::Ready(Ok(())) } _ => { drop(pending); unreachable!("Upgrade expects h1"); } }, } } } impl<T, B> fmt::Debug for Connection<T, B> where T: AsyncRead + AsyncWrite + fmt::Debug + Send + 'static, B: HttpBody + 'static, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Connection").finish() } } // ===== impl Builder impl Builder { /// Creates a new connection builder. #[inline] pub fn new() -> Builder { Builder { exec: Exec::Default, h1_read_buf_exact_size: None, h1_title_case_headers: false, h1_max_buf_size: None, #[cfg(feature = "http2")] h2_builder: Default::default(), #[cfg(feature = "http1")] version: Proto::Http1, #[cfg(not(feature = "http1"))] version: Proto::Http2, } } /// Provide an executor to execute background HTTP2 tasks. pub fn executor<E>(&mut self, exec: E) -> &mut Builder where E: Executor<BoxSendFuture> + Send + Sync + 'static, { self.exec = Exec::Executor(Arc::new(exec)); self } pub(super) fn h1_title_case_headers(&mut self, enabled: bool) -> &mut Builder { self.h1_title_case_headers = enabled; self } pub(super) fn h1_read_buf_exact_size(&mut self, sz: Option<usize>) -> &mut Builder { self.h1_read_buf_exact_size = sz; self.h1_max_buf_size = None; self } #[cfg(feature = "http1")] pub(super) fn h1_max_buf_size(&mut self, max: usize) -> &mut Self { assert!( max >= proto::h1::MINIMUM_MAX_BUFFER_SIZE, "the max_buf_size cannot be smaller than the minimum that h1 specifies." ); self.h1_max_buf_size = Some(max); self.h1_read_buf_exact_size = None; self } /// Sets whether HTTP2 is required. /// /// Default is false. #[cfg(feature = "http2")] #[cfg_attr(docsrs, doc(cfg(feature = "http2")))] pub fn http2_only(&mut self, enabled: bool) -> &mut Builder { if enabled { self.version = Proto::Http2 } self } /// Sets the [`SETTINGS_INITIAL_WINDOW_SIZE`][spec] option for HTTP2 /// stream-level flow control. /// /// Passing `None` will do nothing. /// /// If not set, hyper will use a default. /// /// [spec]: https://http2.github.io/http2-spec/#SETTINGS_INITIAL_WINDOW_SIZE #[cfg(feature = "http2")] #[cfg_attr(docsrs, doc(cfg(feature = "http2")))] pub fn http2_initial_stream_window_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self { if let Some(sz) = sz.into() { self.h2_builder.adaptive_window = false; self.h2_builder.initial_stream_window_size = sz; } self } /// Sets the max connection-level flow control for HTTP2 /// /// Passing `None` will do nothing. /// /// If not set, hyper will use a default. #[cfg(feature = "http2")] #[cfg_attr(docsrs, doc(cfg(feature = "http2")))] pub fn http2_initial_connection_window_size( &mut self, sz: impl Into<Option<u32>>, ) -> &mut Self { if let Some(sz) = sz.into() { self.h2_builder.adaptive_window = false; self.h2_builder.initial_conn_window_size = sz; } self } /// Sets whether to use an adaptive flow control. /// /// Enabling this will override the limits set in /// `http2_initial_stream_window_size` and /// `http2_initial_connection_window_size`. #[cfg(feature = "http2")] #[cfg_attr(docsrs, doc(cfg(feature = "http2")))] pub fn http2_adaptive_window(&mut self, enabled: bool) -> &mut Self { use proto::h2::SPEC_WINDOW_SIZE; self.h2_builder.adaptive_window = enabled; if enabled { self.h2_builder.initial_conn_window_size = SPEC_WINDOW_SIZE; self.h2_builder.initial_stream_window_size = SPEC_WINDOW_SIZE; } self } /// Sets the maximum frame size to use for HTTP2. /// /// Passing `None` will do nothing. /// /// If not set, hyper will use a default. #[cfg(feature = "http2")] #[cfg_attr(docsrs, doc(cfg(feature = "http2")))] pub fn http2_max_frame_size(&mut self, sz: impl Into<Option<u32>>) -> &mut Self { if let Some(sz) = sz.into() { self.h2_builder.max_frame_size = sz; } self } /// Sets an interval for HTTP2 Ping frames should be sent to keep a /// connection alive. /// /// Pass `None` to disable HTTP2 keep-alive. /// /// Default is currently disabled. /// /// # Cargo Feature /// /// Requires the `runtime` cargo feature to be enabled. #[cfg(feature = "runtime")] #[cfg(feature = "http2")] #[cfg_attr(docsrs, doc(cfg(feature = "http2")))] pub fn http2_keep_alive_interval( &mut self, interval: impl Into<Option<Duration>>, ) -> &mut Self { self.h2_builder.keep_alive_interval = interval.into(); self } /// Sets a timeout for receiving an acknowledgement of the keep-alive ping. /// /// If the ping is not acknowledged within the timeout, the connection will /// be closed. Does nothing if `http2_keep_alive_interval` is disabled. /// /// Default is 20 seconds. /// /// # Cargo Feature /// /// Requires the `runtime` cargo feature to be enabled. #[cfg(feature = "runtime")] #[cfg(feature = "http2")] #[cfg_attr(docsrs, doc(cfg(feature = "http2")))] pub fn http2_keep_alive_timeout(&mut self, timeout: Duration) -> &mut Self { self.h2_builder.keep_alive_timeout = timeout; self } /// Sets whether HTTP2 keep-alive should apply while the connection is idle. /// /// If disabled, keep-alive pings are only sent while there are open /// request/responses streams. If enabled, pings are also sent when no /// streams are active. Does nothing if `http2_keep_alive_interval` is /// disabled. /// /// Default is `false`. /// /// # Cargo Feature /// /// Requires the `runtime` cargo feature to be enabled. #[cfg(feature = "runtime")] #[cfg(feature = "http2")] #[cfg_attr(docsrs, doc(cfg(feature = "http2")))] pub fn http2_keep_alive_while_idle(&mut self, enabled: bool) -> &mut Self { self.h2_builder.keep_alive_while_idle = enabled; self } /// Constructs a connection with the configured options and IO. pub fn handshake<T, B>( &self, io: T, ) -> impl Future<Output = crate::Result<(SendRequest<B>, Connection<T, B>)>> where T: AsyncRead + AsyncWrite + Unpin + Send + 'static, B: HttpBody + 'static, B::Data: Send, B::Error: Into<Box<dyn StdError + Send + Sync>>, { let opts = self.clone(); async move { trace!("client handshake {:?}", opts.version); let (tx, rx) = dispatch::channel(); let proto = match opts.version { #[cfg(feature = "http1")] Proto::Http1 => { let mut conn = proto::Conn::new(io); if opts.h1_title_case_headers { conn.set_title_case_headers(); } if let Some(sz) = opts.h1_read_buf_exact_size { conn.set_read_buf_exact_size(sz); } if let Some(max) = opts.h1_max_buf_size { conn.set_max_buf_size(max); } let cd = proto::h1::dispatch::Client::new(rx); let dispatch = proto::h1::Dispatcher::new(cd, conn); ProtoClient::H1(dispatch) } #[cfg(feature = "http2")] Proto::Http2 => { let h2 = proto::h2::client::handshake(io, rx, &opts.h2_builder, opts.exec.clone()) .await?; ProtoClient::H2(h2, PhantomData) } }; Ok(( SendRequest { dispatch: tx }, Connection { inner: Some(proto) }, )) } } } // ===== impl ResponseFuture impl Future for ResponseFuture { type Output = crate::Result<Response<Body>>; fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> { match self.inner { ResponseFutureState::Waiting(ref mut rx) => { Pin::new(rx).poll(cx).map(|res| match res { Ok(Ok(resp)) => Ok(resp), Ok(Err(err)) => Err(err), // this is definite bug if it happens, but it shouldn't happen! Err(_canceled) => panic!("dispatch dropped without returning error"), }) } ResponseFutureState::Error(ref mut err) => { Poll::Ready(Err(err.take().expect("polled after ready"))) } } } } impl fmt::Debug for ResponseFuture { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ResponseFuture").finish() } } // ===== impl ProtoClient impl<T, B> Future for ProtoClient<T, B> where T: AsyncRead + AsyncWrite + Send + Unpin + 'static, B: HttpBody + Send + 'static, B::Data: Send, B::Error: Into<Box<dyn StdError + Send + Sync>>, { type Output = crate::Result<proto::Dispatched>; fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> { match self.project() { #[cfg(feature = "http1")] ProtoClientProj::H1(c) => c.poll(cx), #[cfg(feature = "http2")] ProtoClientProj::H2(c, _) => c.poll(cx), } } } // assert trait markers trait AssertSend: Send {} trait AssertSendSync: Send + Sync {} #[doc(hidden)] impl<B: Send> AssertSendSync for SendRequest<B> {} #[doc(hidden)] impl<T: Send, B: Send> AssertSend for Connection<T, B> where T: AsyncRead + AsyncWrite + Send + 'static, B: HttpBody + 'static, B::Data: Send, { } #[doc(hidden)] impl<T: Send + Sync, B: Send + Sync> AssertSendSync for Connection<T, B> where T: AsyncRead + AsyncWrite + Send + 'static, B: HttpBody + 'static, B::Data: Send + Sync + 'static, { } #[doc(hidden)] impl AssertSendSync for Builder {} #[doc(hidden)] impl AssertSend for ResponseFuture {}
31.883519
100
0.568558
ab1116ec036565f74a263c6aa18d9522539a4169
1,554
use std::fmt; use crate::expression::Value; #[derive(Debug, Clone)] pub enum Type { // Single character tokens LeftParen, RightParen, LeftBrace, RightBrace, Comma, Dot, Minus, Plus, Semicolon, Slash, Star, // One or two character tokens Bang, BangEqual, Equal, EqualEqual, Greater, GreaterEqual, Less, LessEqual, // Literals Identifier, String(String), Number(f64), // Keywords And, Class, Else, False, Fun, For, If, Nil, Or, Print, Return, Super, This, True, Var, While, EOF } impl Type { pub fn to_value(self) -> Value { match self { Type::String(s) => Value::String(s), Type::Number(n) => Value::Number(n), Type::False => Value::False, Type::True => Value::True, Type::Nil => Value::Nil, _ => panic!("Attepted to convert invalid token type to value!") } } } #[derive(Clone)] pub struct Token { token_type: Type, lexeme: String, line: usize, } impl Token { pub fn new(token_type: Type, lexeme: String, line: usize) -> Self { Self { token_type, lexeme, line, } } pub fn lexeme(&self) -> &str { &self.lexeme } pub fn token_type(&self) -> &Type { &self.token_type } pub fn line(&self) -> usize { self.line } } impl fmt::Display for Token { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?} {}", self.token_type, self.lexeme) } }
21
75
0.545689
1ae9c345cdd93d1923a7d3c1590a0cae4999b90c
922
use serde::{de, Deserialize, Deserializer, Serializer}; use serde_with::{DeserializeAs, SerializeAs}; pub struct BoolFromNumber; impl SerializeAs<bool> for BoolFromNumber { fn serialize_as<S>(source: &bool, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if *source { serializer.serialize_u8(1) } else { serializer.serialize_u8(0) } } } impl<'de> DeserializeAs<'de, bool> for BoolFromNumber { fn deserialize_as<D>(deserializer: D) -> Result<bool, D::Error> where D: Deserializer<'de>, { match u8::deserialize(deserializer) { Ok(v) if v == 1 => Ok(true), Ok(v) if v == 0 => Ok(false), Ok(v) => Err(de::Error::invalid_value( de::Unexpected::Unsigned(v.into()), &"0 or 1", )), Err(e) => Err(e), } } }
26.342857
79
0.533623
56f6d717e1ea84399cf501a22b2e53205d0cb430
7,178
use std::io; use std::io::{ErrorKind, Result}; use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::{env, fs}; use yaml_rust::yaml::Hash; use yaml_rust::{Yaml, YamlEmitter, YamlLoader}; pub struct Config { pub coordinator: Option<reqwest::Url>, pub helper_bind: SocketAddr, pub coordinator_bind: SocketAddr, pub process_limit: usize, pub cache_dir: PathBuf, pub cache_limit_mb: u32, } const CONFIG_FILE_NAME: &str = "octobuild.conf"; #[cfg(windows)] const DEFAULT_CACHE_DIR: &str = "~/.octobuild"; #[cfg(unix)] const DEFAULT_CACHE_DIR: &str = "~/.cache/octobuild"; const PARAM_HELPER_BIND: &str = "helper_bind"; const PARAM_COORDINATOR_BIND: &str = "coordinator_bind"; const PARAM_COORDINATOR: &str = "coordinator"; const PARAM_CACHE_LIMIT: &str = "cache_limit_mb"; const PARAM_CACHE_PATH: &str = "cache_path"; const PARAM_PROCESS_LIMIT: &str = "process_limit"; impl Config { pub fn new() -> Result<Self> { let local = get_local_config_path().and_then(|v| load_config(v).ok()); let global = get_global_config_path().and_then(|v| load_config(v).ok()); Config::load(&local, &global, false) } pub fn get_coordinator_addrs(&self) -> Result<Vec<SocketAddr>> { match self.coordinator { Some(ref url) => url.socket_addrs(|| match url.scheme() { "http" => Some(80), _ => None, }), None => Ok(Vec::new()), } } pub fn defaults() -> Result<Self> { Config::load(&None, &None, true) } fn load(local: &Option<Yaml>, global: &Option<Yaml>, defaults: bool) -> Result<Self> { let cache_limit_mb = get_config(local, global, PARAM_CACHE_LIMIT, |v| { v.as_i64().map(|v| v as u32) }) .unwrap_or(16 * 1024); let cache_path = if defaults { None } else { env::var("OCTOBUILD_CACHE") .ok() .and_then(|v| if v.is_empty() { None } else { Some(v) }) } .or_else(|| { get_config(local, global, PARAM_CACHE_PATH, |v| { v.as_str().map(|v| v.to_string()) }) }) .unwrap_or_else(|| DEFAULT_CACHE_DIR.to_string()); let process_limit = get_config(local, global, PARAM_PROCESS_LIMIT, |v| { v.as_i64().map(|v| v as usize) }) .unwrap_or_else(num_cpus::get); let coordinator = get_config(local, global, PARAM_COORDINATOR, |v| { if v.is_null() { None } else { v.as_str().and_then(|v| { reqwest::Url::parse(v) .map(|mut v| { v.set_path(""); v }) .ok() }) } }); let helper_bind = get_config(local, global, PARAM_HELPER_BIND, |v| { v.as_str().and_then(|v| FromStr::from_str(v).ok()) }) .unwrap_or_else(|| SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0))); let coordinator_bind = get_config(local, global, PARAM_COORDINATOR_BIND, |v| { v.as_str().and_then(|v| FromStr::from_str(v).ok()) }) .unwrap_or_else(|| SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 3000))); Ok(Config { process_limit, cache_dir: replace_home(&cache_path)?, cache_limit_mb, coordinator, helper_bind, coordinator_bind, }) } fn show(&self) { let mut content = String::new(); let mut y = Hash::new(); y.insert( Yaml::String(PARAM_PROCESS_LIMIT.to_string()), Yaml::Integer(self.process_limit as i64), ); y.insert( Yaml::String(PARAM_CACHE_LIMIT.to_string()), Yaml::Integer(i64::from(self.cache_limit_mb)), ); y.insert( Yaml::String(PARAM_CACHE_PATH.to_string()), Yaml::String(self.cache_dir.to_str().unwrap().to_string()), ); y.insert( Yaml::String(PARAM_COORDINATOR.to_string()), self.coordinator .as_ref() .map_or(Yaml::Null, |v| Yaml::String(v.as_str().to_string())), ); y.insert( Yaml::String(PARAM_HELPER_BIND.to_string()), Yaml::String(self.helper_bind.to_string()), ); y.insert( Yaml::String(PARAM_COORDINATOR_BIND.to_string()), Yaml::String(self.coordinator_bind.to_string()), ); YamlEmitter::new(&mut content).dump(&Yaml::Hash(y)).unwrap(); println!("{}", content); } pub fn help() { println!("Octobuild configuration:"); println!( " system config path: {}", get_global_config_path() .map(|v| v.to_str().unwrap().to_string()) .unwrap_or_else(|| "none".to_string()) ); println!( " user config path: {}", get_local_config_path() .map(|v| v.to_str().unwrap().to_string()) .unwrap_or_else(|| "none".to_string()) ); println!(); println!("Actual configuration:"); match Config::new() { Ok(c) => { c.show(); } Err(e) => { println!(" ERROR: {}", e); } } println!(); println!("Default configuration:"); match Config::defaults() { Ok(c) => { c.show(); } Err(e) => { println!(" ERROR: {}", e); } } println!(); } } fn get_config<F, T>(local: &Option<Yaml>, global: &Option<Yaml>, param: &str, op: F) -> Option<T> where F: Fn(&Yaml) -> Option<T>, { None.or_else(|| local.as_ref().and_then(|i| op(&i[param]))) .or_else(|| global.as_ref().and_then(|i| op(&i[param]))) } fn load_config<P: AsRef<Path>>(path: P) -> Result<Yaml> { let content = fs::read_to_string(path)?; match YamlLoader::load_from_str(&content) { Ok(ref mut docs) => Ok(docs.pop().unwrap()), Err(e) => Err(io::Error::new(ErrorKind::InvalidInput, e)), } } fn get_local_config_path() -> Option<PathBuf> { dirs::home_dir().map(|v| v.join(&(".".to_string() + CONFIG_FILE_NAME))) } #[cfg(windows)] fn get_global_config_path() -> Option<PathBuf> { env::var("ProgramData") .ok() .map(|v| Path::new(&v).join("octobuild").join(CONFIG_FILE_NAME)) } #[allow(clippy::unnecessary_wraps)] #[cfg(unix)] fn get_global_config_path() -> Option<PathBuf> { Some(Path::new("/etc/octobuild").join(CONFIG_FILE_NAME)) } fn replace_home(path: &str) -> Result<PathBuf> { if path.starts_with("~/") { dirs::home_dir() .map(|v| v.join(&path[2..])) .ok_or_else(|| io::Error::new(ErrorKind::NotFound, "Can't determinate user HOME path")) } else { Ok(Path::new(path).to_path_buf()) } }
31.902222
99
0.530092
799c7612611824b7a71a33c7b576d04690fe268b
2,710
extern crate clap; use clap::{App, Arg}; fn main() { // Positional arguments are those values after the program name which are not preceded by any // identifier (such as "myapp some_file"). Positionals support many of the same options as // flags, as well as a few additional ones. let matches = App::new("MyApp") // Regular App configuration goes here... // We'll add two positional arguments, a input file, and a config file. // // I'll explain each possible setting that "positionals" accept. Keep in // mind that you DO NOT need to set each of these for every flag, only the // ones that apply to your individual case. .arg( Arg::with_name("input") .help("the input file to use") // Displayed when showing help info .index(1) // Set the order in which the user must // specify this argument (Starts at 1) .requires("config") // Says, "If the user uses "input", they MUST // also use this other 'config' arg too" // Can also specifiy a list using // requires_all(Vec<&str>) .conflicts_with("output") // Opposite of requires(), says "if the // user uses -a, they CANNOT use 'output'" // also has a conflicts_with_all(Vec<&str>) .required(true), // By default this argument MUST be present // NOTE: mutual exclusions take precedence over // required arguments ) .arg( Arg::with_name("config") .help("the config file to use") .index(2), ) // Note, we do not need to specify required(true) // if we don't want to, because "input" already // requires "config" // Note, we also do not need to specify requires("input") // because requires lists are automatically two-way // NOTE: In order to compile this example, comment out conflicts_with() // because we have not defined an "output" argument. .get_matches(); // We can find out whether or not "input" or "config" were used if matches.is_present("input") { println!("An input file was specified"); } // We can also get the values for those arguments if let Some(ref in_file) = matches.value_of("input") { // It's safe to call unwrap() because of the required options we set above println!( "Doing work with {} and {}", in_file, matches.value_of("config").unwrap() ); } // Continued program logic goes here... }
44.42623
97
0.573063
e29b1fd50b70caefaa17d024c25153d314be601a
1,629
use crate::co; use crate::comctl::decl::HIMAGELIST; use crate::kernel::decl::WinResult; use crate::prelude::{ComctlHimagelist, UserHicon}; use crate::shell::decl::{SHFILEINFO, SHGetFileInfo}; impl ComctlShellHimagelist for HIMAGELIST {} /// [`HIMAGELIST`](crate::HIMAGELIST) methods from `comctl`+`shell` features. #[cfg_attr(docsrs, doc(cfg(all(feature = "comctl", feature = "shell"))))] pub trait ComctlShellHimagelist: ComctlHimagelist { /// Calls [`SHGetFileInfo`](crate::SHGetFileInfo) to retrieve one or more /// shell file icons, then passes them to /// [`AddIcon`](crate::prelude::ComctlHimagelist::AddIcon). /// /// # Examples /// /// ```rust,no_run /// use winsafe::prelude::*; /// use winsafe::{co, HIMAGELIST, SIZE}; /// /// let himgl = HIMAGELIST::Create( /// SIZE::new(16, 16), co::ILC::COLOR32, 1, 1)?; /// /// himgl.add_icon_from_shell(&["mp3", "wav"])?; /// /// himgl.Destroy()?; /// # Ok::<_, co::ERROR>(()) /// ``` fn add_icon_from_shell(self, file_extensions: &[&str]) -> WinResult<()> { let sz = self.GetIconSize()?; if !sz.is(16, 16) && !sz.is(32, 32) { return Err(co::ERROR::NOT_SUPPORTED); // only 16x16 or 32x32 icons can be loaded } let mut shfi = SHFILEINFO::default(); for file_extension in file_extensions.iter() { SHGetFileInfo(&format!("*.{}", file_extension), co::FILE_ATTRIBUTE::NORMAL, &mut shfi, co::SHGFI::USEFILEATTRIBUTES | co::SHGFI::ICON | if sz.is(16, 16) { co::SHGFI::SMALLICON } else { co::SHGFI::LARGEICON })?; self.AddIcon(shfi.hIcon)?; shfi.hIcon.DestroyIcon()?; } Ok(()) } }
34.659574
84
0.626765
4ae02f608bd115370aeacaa989754bd3f53fc717
32,873
// Copyright 2018 Google LLC // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. //! The BoringSSL API. //! //! This module provides a safe access to the BoringSSL API. //! //! It accomplishes this using the following structure: //! - The internal `raw` module provides nearly-raw access to the BoringSSL API. //! For each function in the BoringSSL API, it exposes an equivalent Rust //! function which performs error checking. Functions which return pointers //! return `Result<NonNull<T>, BoringError>`, functions which return status //! codes return `Result<(), BoringError>`, etc. This API makes it less likely //! to accidentally forget to check for null pointers or error status codes. //! - The internal `wrapper` module provides types which wrap C objects and //! handle many of the details of their lifecycles. These include //! `CStackWrapper`, which handles initializing and destructing //! stack-allocated C objects; `CHeapWrapper`, which is analogous to Rust's //! `Box` or `Rc`, and handles allocation, reference counting, and freeing; //! and `CRef`, which is analogous to a Rust reference. //! - This module builds on top of the `raw` and `wrapper` modules to provide a //! safe API. This allows us to `#![forbid(unsafe_code)]` in the rest of the //! crate, which in turn means that this is the only module whose memory //! safety needs to be manually verified. //! //! # Usage //! //! Each type, `T`, from the BoringSSL API is exposed as either a //! `CStackWrapper<T>`, a `CHeapWrapper<T>`, or a `CRef<T>`. Each function from //! the BoringSSL API which operates on a particular type is exposed as a method //! on the wrapped version of that type. For example, the BoringSSL `CBS_len` //! function operates on a `CBS`; we provide the `cbs_len` method on the //! `CStackWrapper<CBS>` type. While BoringSSL functions that operate on a //! particular type take the form `TYPE_method`, the Rust equivalents are all //! lower-case - `type_method`. //! //! Some functions which do not make sense as methods are exposed as bare //! functions. For example, the BoringSSL `ECDSA_sign` function is exposed as a //! bare function as `ecdsa_sign`. //! //! Types which can be constructed without arguments implement `Default`. Types //! which require arguments to be constructed provide associated functions which //! take those arguments and return a new instance of that type. For example, //! the `CHeapWrapper<EC_KEY>::ec_key_parse_private_key` function parses a //! private key from an input stream and returns a new `CHeapWrapper<EC_KEY>`. //! //! # API Guidelines //! //! This module is meant to be as close as possible to a direct set of FFI //! bindings while still providing a safe API. While memory safety is handled //! internally, and certain error conditions which could affect memory safety //! are checked internally (and cause the process to abort if they fail), most //! errors are returned from the API, as they are considered business logic, //! which is outside the scope of this module. // NOTES on safety requirements of the BoringSSL API: // - Though it may not be explicitly documented, calling methods on uinitialized // values is UB. Remember, this is C! Always initialize (usually via XXX_init // or a similarly-named function) before calling any methods or functions. // - Any BoringSSL documentation that says "x property must hold" means that, if // that property doesn't hold, it may cause UB - you are not guaranteed that // it will be detected and an error will be returned. // - If a pointer parameter is const, the function does NOT take ownership of // the object. If the pointer parameter is not const, it MAY take ownership // depending on documentation. Generally, ownership is only taken if // explicitly documented, but documentation bugs may exist, so be careful. // NOTE(joshlf): It's important to define this module before the abort module, // or else all of the assertions that are auto-generated by bindgen would result // in compilation errors. #[path = "../../boringssl/boringssl.rs"] mod ffi; #[macro_use] mod abort; #[macro_use] mod wrapper; mod raw; // C types pub use boringssl::ffi::{ BIGNUM, CBB, CBS, EC_GROUP, EC_KEY, EVP_MD, EVP_PKEY, HMAC_CTX, RSA, RSA_F4, SHA256_CTX, SHA512_CTX, SHA_CTX, }; // C constants pub use boringssl::ffi::{ NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, NID_sha1, NID_sha256, NID_sha384, NID_sha512, ED25519_PRIVATE_KEY_LEN, ED25519_PUBLIC_KEY_LEN, ED25519_SIGNATURE_LEN, SHA256_DIGEST_LENGTH, SHA384_DIGEST_LENGTH, SHA512_DIGEST_LENGTH, SHA_DIGEST_LENGTH, }; // wrapper types pub use boringssl::wrapper::{CHeapWrapper, CRef, CStackWrapper}; use std::convert::TryInto; use std::ffi::CStr; use std::fmt::{self, Debug, Display, Formatter}; use std::num::NonZeroUsize; use std::os::raw::{c_char, c_int, c_uint, c_void}; use std::{mem, ptr, slice}; use boringssl::abort::UnwrapAbort; use boringssl::raw::{ BN_set_u64, CBB_data, CBB_init, CBB_len, CBS_init, CBS_len, CRYPTO_memcmp, ECDSA_sign, ECDSA_size, ECDSA_verify, EC_GROUP_get_curve_name, EC_GROUP_new_by_curve_name, EC_KEY_generate_key, EC_KEY_get0_group, EC_KEY_marshal_private_key, EC_KEY_parse_private_key, EC_KEY_set_group, EC_curve_nid2nist, ED25519_keypair, ED25519_keypair_from_seed, ED25519_sign, ED25519_verify, ERR_print_errors_cb, EVP_PBE_scrypt, EVP_PKEY_assign_EC_KEY, EVP_PKEY_assign_RSA, EVP_PKEY_get1_EC_KEY, EVP_PKEY_get1_RSA, EVP_marshal_public_key, EVP_parse_public_key, HMAC_CTX_init, HMAC_Final, HMAC_Init_ex, HMAC_Update, HMAC_size, RAND_bytes, RSA_bits, RSA_generate_key_ex, RSA_marshal_private_key, RSA_parse_private_key, RSA_sign_pss_mgf1, RSA_size, RSA_verify_pss_mgf1, SHA384_Init, }; #[cfg(feature = "rsa-pkcs1v15")] use boringssl::raw::{RSA_sign, RSA_verify}; impl CStackWrapper<BIGNUM> { /// The `BN_set_u64` function. #[must_use] pub fn bn_set_u64(&mut self, value: u64) -> Result<(), BoringError> { unsafe { BN_set_u64(self.as_mut(), value) } } } impl CStackWrapper<CBB> { /// Creates a new `CBB` and initializes it with `CBB_init`. /// /// `cbb_new` can only fail due to OOM. #[must_use] pub fn cbb_new(initial_capacity: usize) -> Result<CStackWrapper<CBB>, BoringError> { unsafe { let mut cbb = mem::uninitialized(); CBB_init(&mut cbb, initial_capacity)?; Ok(CStackWrapper::new(cbb)) } } /// Invokes a callback on the contents of a `CBB`. /// /// `cbb_with_data` accepts a callback, and invokes that callback, passing a /// slice of the current contents of this `CBB`. #[must_use] pub fn cbb_with_data<O, F: Fn(&[u8]) -> O>(&self, with_data: F) -> O { unsafe { // NOTE: The return value of CBB_data is only valid until the next // operation on the CBB. This method is safe because the slice // reference cannot outlive this function body, and thus cannot live // beyond another method call that could invalidate the buffer. let len = CBB_len(self.as_const()); if len == 0 { // If len is 0, then CBB_data could technically return a null // pointer. Constructing a slice from a null pointer is likely // invalid, so we do this instead. with_data(&[]) } else { // Since the length is non-zero, CBB_data should not return a // null pointer. let ptr = CBB_data(self.as_const()).unwrap_abort(); // TODO(joshlf): Can with_data use this to smuggle out the // reference, outliving the lifetime of self? with_data(slice::from_raw_parts(ptr.as_ptr(), len)) } } } } impl CStackWrapper<CBS> { /// The `CBS_len` function. #[must_use] pub fn cbs_len(&self) -> usize { unsafe { CBS_len(self.as_const()) } } /// Invokes a callback on a temporary `CBS`. /// /// `cbs_with_temp_buffer` constructs a `CBS` from the provided byte slice, /// and invokes a callback on the `CBS`. The `CBS` is destructed before /// `cbs_with_temp_buffer` returns. // TODO(joshlf): Holdover until we figure out how to put lifetimes in CStackWrappers. #[must_use] pub fn cbs_with_temp_buffer<O, F: Fn(&mut CStackWrapper<CBS>) -> O>( bytes: &[u8], with_cbs: F, ) -> O { unsafe { let mut cbs = mem::uninitialized(); CBS_init(&mut cbs, bytes.as_ptr(), bytes.len()); let mut cbs = CStackWrapper::new(cbs); with_cbs(&mut cbs) } } } impl CRef<'static, EC_GROUP> { /// The `EC_GROUP_new_by_curve_name` function. #[must_use] pub fn ec_group_new_by_curve_name(nid: c_int) -> Result<CRef<'static, EC_GROUP>, BoringError> { unsafe { Ok(CRef::new(EC_GROUP_new_by_curve_name(nid)?)) } } } impl<'a> CRef<'a, EC_GROUP> { /// The `EC_GROUP_get_curve_name` function. #[must_use] pub fn ec_group_get_curve_name(&self) -> c_int { unsafe { EC_GROUP_get_curve_name(self.as_const()) } } } /// The `EC_curve_nid2nist` function. #[must_use] pub fn ec_curve_nid2nist(nid: c_int) -> Result<&'static CStr, BoringError> { unsafe { Ok(CStr::from_ptr(EC_curve_nid2nist(nid)?.as_ptr())) } } impl CHeapWrapper<EC_KEY> { /// The `EC_KEY_generate_key` function. #[must_use] pub fn ec_key_generate_key(&mut self) -> Result<(), BoringError> { unsafe { EC_KEY_generate_key(self.as_mut()) } } /// The `EC_KEY_parse_private_key` function. /// /// If `group` is `None`, then the group pointer argument to /// `EC_KEY_parse_private_key` will be NULL. #[must_use] pub fn ec_key_parse_private_key( cbs: &mut CStackWrapper<CBS>, group: Option<CRef<'static, EC_GROUP>>, ) -> Result<CHeapWrapper<EC_KEY>, BoringError> { unsafe { Ok(CHeapWrapper::new_from(EC_KEY_parse_private_key( cbs.as_mut(), group.map(|g| g.as_const()).unwrap_or(ptr::null()), )?)) } } /// The `EC_KEY_get0_group` function. #[must_use] #[allow(clippy::needless_lifetimes)] // to be more explicit pub fn ec_key_get0_group<'a>(&'a self) -> Result<CRef<'a, EC_GROUP>, BoringError> { // get0 doesn't increment the refcount; the lifetimes ensure that the // returned CRef can't outlive self unsafe { Ok(CRef::new(EC_KEY_get0_group(self.as_const())?)) } } /// The `EC_KEY_set_group` function. #[must_use] pub fn ec_key_set_group(&mut self, group: &CRef<'static, EC_GROUP>) -> Result<(), BoringError> { unsafe { EC_KEY_set_group(self.as_mut(), group.as_const()) } } /// The `EC_KEY_marshal_private_key` function. #[must_use] pub fn ec_key_marshal_private_key( &self, cbb: &mut CStackWrapper<CBB>, ) -> Result<(), BoringError> { unsafe { EC_KEY_marshal_private_key(cbb.as_mut(), self.as_const(), 0) } } } /// The `ECDSA_sign` function. /// /// `ecdsa_sign` returns the number of bytes written to `sig`. /// /// # Panics /// /// `ecdsa_sign` panics if `sig` is shorter than the minimum required signature /// size given by `ecdsa_size`, or if `key` doesn't have a group set. #[must_use] pub fn ecdsa_sign( digest: &[u8], sig: &mut [u8], key: &CHeapWrapper<EC_KEY>, ) -> Result<usize, BoringError> { unsafe { // If we call ECDSA_sign with sig.len() < min_size, it will invoke UB. // ECDSA_size fails if the key doesn't have a group set. let min_size = ecdsa_size(key).unwrap_abort(); assert_abort!(sig.len() >= min_size.get()); let mut sig_len: c_uint = 0; ECDSA_sign( 0, digest.as_ptr(), digest.len(), sig.as_mut_ptr(), &mut sig_len, key.as_const(), )?; // ECDSA_sign guarantees that it only needs ECDSA_size bytes for the // signature. let sig_len = sig_len.try_into().unwrap_abort(); assert_abort!(sig_len <= min_size.get()); Ok(sig_len) } } /// The `ECDSA_verify` function. #[must_use] pub fn ecdsa_verify(digest: &[u8], sig: &[u8], key: &CHeapWrapper<EC_KEY>) -> bool { unsafe { ECDSA_verify(0, digest.as_ptr(), digest.len(), sig.as_ptr(), sig.len(), key.as_const()) } } /// The `ECDSA_size` function. #[must_use] pub fn ecdsa_size(key: &CHeapWrapper<EC_KEY>) -> Result<NonZeroUsize, BoringError> { unsafe { ECDSA_size(key.as_const()) } } /// The `ED25519_keypair` function. #[must_use] pub fn ed25519_keypair() -> [u8; ED25519_PRIVATE_KEY_LEN as usize] { let mut public_unused = [0u8; ED25519_PUBLIC_KEY_LEN as usize]; let mut private = [0u8; ED25519_PRIVATE_KEY_LEN as usize]; unsafe { ED25519_keypair((&mut public_unused[..]).as_mut_ptr(), (&mut private[..]).as_mut_ptr()) }; private } /// The `ED25519_sign` function. #[must_use] pub fn ed25519_sign(message: &[u8], private_key: &[u8; 64]) -> Result<[u8; 64], BoringError> { let mut sig = [0u8; 64]; unsafe { ED25519_sign(&mut sig, message.as_ptr(), message.len(), private_key)? }; Ok(sig) } /// The `ED25519_keypair_from_seed` function. #[must_use] pub fn ed25519_keypair_from_seed(seed: &[u8; 32]) -> ([u8; 32], [u8; 64]) { let mut public = [0u8; 32]; let mut private = [0u8; 64]; unsafe { ED25519_keypair_from_seed( (&mut public[..]).as_mut_ptr(), (&mut private[..]).as_mut_ptr(), (&seed[..]).as_ptr(), ) }; (public, private) } /// The `ED25519_verify` function. #[must_use] pub fn ed25519_verify(message: &[u8], signature: &[u8; 64], public_key: &[u8; 32]) -> bool { unsafe { ED25519_verify(message.as_ptr(), message.len(), signature, public_key) } } impl CHeapWrapper<EVP_PKEY> { /// The `EVP_parse_public_key` function. #[must_use] pub fn evp_parse_public_key( cbs: &mut CStackWrapper<CBS>, ) -> Result<CHeapWrapper<EVP_PKEY>, BoringError> { unsafe { Ok(CHeapWrapper::new_from(EVP_parse_public_key(cbs.as_mut())?)) } } /// The `EVP_marshal_public_key` function. #[must_use] pub fn evp_marshal_public_key(&self, cbb: &mut CStackWrapper<CBB>) -> Result<(), BoringError> { unsafe { EVP_marshal_public_key(cbb.as_mut(), self.as_const()) } } /// The `EVP_PKEY_assign_EC_KEY` function. pub fn evp_pkey_assign_ec_key(&mut self, ec_key: CHeapWrapper<EC_KEY>) { unsafe { // NOTE: It's very important that we use 'into_mut' here so that // ec_key's refcount is not decremented. That's because // EVP_PKEY_assign_EC_KEY doesn't increment the refcount of its // argument. let key = ec_key.into_mut(); // EVP_PKEY_assign_EC_KEY only fails if key is NULL. EVP_PKEY_assign_EC_KEY(self.as_mut(), key).unwrap_abort() } } /// The `EVP_PKEY_assign_RSA` function. pub fn evp_pkey_assign_rsa(&mut self, rsa: CHeapWrapper<RSA>) { unsafe { // NOTE: It's very important that we use 'into_mut' here so that // rsa's refcount is not decremented. That's because // EVP_PKEY_assign_RSA doesn't increment the refcount of its // argument. let key = rsa.into_mut(); // EVP_PKEY_assign_RSA only fails if key is NULL. EVP_PKEY_assign_RSA(self.as_mut(), key).unwrap_abort() } } /// The `EVP_PKEY_get1_EC_KEY` function. #[must_use] pub fn evp_pkey_get1_ec_key(&mut self) -> Result<CHeapWrapper<EC_KEY>, BoringError> { // NOTE: It's important that we use get1 here, as it increments the // refcount of the EC_KEY before returning a pointer to it. unsafe { Ok(CHeapWrapper::new_from(EVP_PKEY_get1_EC_KEY(self.as_mut())?)) } } /// The `EVP_PKEY_get1_RSA` function. #[must_use] pub fn evp_pkey_get1_rsa(&mut self) -> Result<CHeapWrapper<RSA>, BoringError> { // NOTE: It's important that we use get1 here, as it increments the // refcount of the RSA key before returning a pointer to it. unsafe { Ok(CHeapWrapper::new_from(EVP_PKEY_get1_RSA(self.as_mut())?)) } } } /// The `EVP_PBE_scrypt` function. #[allow(non_snake_case)] #[must_use] pub fn evp_pbe_scrypt( password: &[u8], salt: &[u8], N: u64, r: u64, p: u64, max_mem: usize, out_key: &mut [u8], ) -> Result<(), BoringError> { unsafe { EVP_PBE_scrypt( password.as_ptr() as *const c_char, password.len(), salt.as_ptr(), salt.len(), N, r, p, max_mem, out_key.as_mut_ptr(), out_key.len(), ) } } /// The `PKCS5_PBKDF2_HMAC` function. #[cfg(feature = "kdf")] #[must_use] pub fn pkcs5_pbkdf2_hmac( password: &[u8], salt: &[u8], iterations: c_uint, digest: &CRef<'static, EVP_MD>, out_key: &mut [u8], ) -> Result<(), BoringError> { unsafe { raw::PKCS5_PBKDF2_HMAC( password.as_ptr() as *const c_char, password.len(), salt.as_ptr(), salt.len(), iterations, digest.as_const(), out_key.len(), out_key.as_mut_ptr(), ) } } impl CStackWrapper<SHA512_CTX> { /// Initializes a new `CStackWrapper<SHA512_CTX>` as a SHA-384 hash. /// /// The BoringSSL `SHA512_CTX` is used for both the SHA-512 and SHA-384 hash /// functions. The implementation of `Default` for /// `CStackWrapper<SHA512_CTX>` produces a context initialized for a SHA-512 /// hash. In order to produce a context for a SHA-384 hash, use this /// constructor instead. #[must_use] pub fn sha384_new() -> CStackWrapper<SHA512_CTX> { unsafe { let mut ctx = mem::uninitialized(); SHA384_Init(&mut ctx); CStackWrapper::new(ctx) } } } macro_rules! impl_evp_digest { (#[$doc:meta] $name:ident, $raw_name:ident) => { #[$doc] #[must_use] pub fn $name() -> CRef<'static, EVP_MD> { unsafe { CRef::new(::boringssl::raw::$raw_name()) } } }; } impl CRef<'static, EVP_MD> { impl_evp_digest!( /// The `EVP_sha1` function. evp_sha1, EVP_sha1 ); impl_evp_digest!( /// The `EVP_sha256` function. evp_sha256, EVP_sha256 ); impl_evp_digest!( /// The `EVP_sha384` function. evp_sha384, EVP_sha384 ); impl_evp_digest!( /// The `EVP_sha512` function. evp_sha512, EVP_sha512 ); } impl CStackWrapper<HMAC_CTX> { /// Initializes a new `HMAC_CTX`. /// /// `hmac_ctx_new` initializes a new `HMAC_CTX` using `HMAC_CTX_init` and /// then further initializes it with `HMAC_CTX_Init_ex`. It can only fail /// due to OOM. #[must_use] pub fn hmac_ctx_new( key: &[u8], md: &CRef<'static, EVP_MD>, ) -> Result<CStackWrapper<HMAC_CTX>, BoringError> { unsafe { let mut ctx = mem::uninitialized(); HMAC_CTX_init(&mut ctx); HMAC_Init_ex(&mut ctx, key.as_ptr() as *const c_void, key.len(), md.as_const())?; Ok(CStackWrapper::new(ctx)) } } /// The `HMAC_Update` function. pub fn hmac_update(&mut self, data: &[u8]) { unsafe { HMAC_Update(self.as_mut(), data.as_ptr(), data.len()) } } // NOTE(joshlf): We require exactly the right length (as opposed to just // long enough) so that we don't have to have hmac_final return a length. /// The `HMAC_Final` function. /// /// # Panics /// /// `hmac_final` panics if `out` is not exactly the right length (as defined /// by `HMAC_size`). pub fn hmac_final(&mut self, out: &mut [u8]) { unsafe { let size = HMAC_size(self.as_const()); assert_abort_eq!(out.len(), size); let mut size = 0; // HMAC_Final is documented to fail on allocation failure, but an // internal comment states that it's infallible. In either case, we // want to panic. Normally, for allocation failure, we'd put the // unwrap higher in the stack, but since this is supposed to be // infallible anyway, we put it here. // // TODO(joshlf): Remove this comment once HMAC_Final is documented // as being infallible. HMAC_Final(self.as_mut(), out.as_mut_ptr(), &mut size).unwrap_abort(); // Guaranteed to be the value returned by HMAC_size. assert_abort_eq!(out.len(), size as usize); } } } impl CHeapWrapper<RSA> { /// The `RSA_bits` function. #[must_use] pub fn rsa_bits(&self) -> c_uint { // RSA_bits does not mutate its argument but, for // backwards-compatibility reasons, continues to take a normal // (non-const) pointer. unsafe { RSA_bits(self.as_const() as *mut _) } } /// The `RSA_generate_key_ex` function. #[must_use] pub fn rsa_generate_key_ex( &mut self, bits: c_int, e: &CRef<BIGNUM>, ) -> Result<(), BoringError> { unsafe { // NOTE: It's very important that we use 'into_mut' here so that e's // refcount is not decremented. That's because RSA_generate_key_ex // takes ownership of e, and thus doesn't increment its refcount. RSA_generate_key_ex(self.as_mut(), bits, e.as_const(), ptr::null_mut()) } } /// The `RSA_marshal_private_key` function. #[must_use] pub fn rsa_marshal_private_key(&self, cbb: &mut CStackWrapper<CBB>) -> Result<(), BoringError> { unsafe { RSA_marshal_private_key(cbb.as_mut(), self.as_const()) } } /// The `RSA_parse_private_key` function. #[must_use] pub fn rsa_parse_private_key( cbs: &mut CStackWrapper<CBS>, ) -> Result<CHeapWrapper<RSA>, BoringError> { unsafe { Ok(CHeapWrapper::new_from(RSA_parse_private_key(cbs.as_mut())?)) } } /// The `RSA_size` function. #[must_use] pub fn rsa_size(&self) -> Result<NonZeroUsize, BoringError> { unsafe { RSA_size(self.as_const()) } } } /// The `RSA_sign` function. /// /// # Panics /// /// `rsa_sign` panics if `sig` is shorter than the minimum required signature /// size given by `rsa_size`. #[cfg(feature = "rsa-pkcs1v15")] pub fn rsa_sign( hash_nid: c_int, digest: &[u8], sig: &mut [u8], key: &CHeapWrapper<RSA>, ) -> Result<usize, BoringError> { unsafe { // If we call RSA_sign with sig.len() < min_size, it will invoke UB. let min_size = key.rsa_size().unwrap_abort(); assert_abort!(sig.len() >= min_size.get()); let mut sig_len: c_uint = 0; RSA_sign( hash_nid, digest.as_ptr(), digest.len().try_into().unwrap_abort(), sig.as_mut_ptr(), &mut sig_len, // RSA_sign does not mutate its argument but, for // backwards-compatibility reasons, continues to take a normal // (non-const) pointer. key.as_const() as *mut _, )?; // RSA_sign guarantees that it only needs RSA_size bytes for the // signature. let sig_len = sig_len.try_into().unwrap_abort(); assert_abort!(sig_len <= min_size.get()); Ok(sig_len) } } /// The `rsa_sign_pss_mgf1` function. #[must_use] pub fn rsa_sign_pss_mgf1( key: &CHeapWrapper<RSA>, sig: &mut [u8], digest: &[u8], md: &CRef<'static, EVP_MD>, mgf1_md: Option<&CRef<'static, EVP_MD>>, salt_len: c_int, ) -> Result<usize, BoringError> { unsafe { let mut sig_len: usize = 0; RSA_sign_pss_mgf1( // RSA_sign_pss_mgf1 does not mutate its argument but, for // backwards-compatibility reasons, continues to take a normal // (non-const) pointer. key.as_const() as *mut _, &mut sig_len, sig.as_mut_ptr(), sig.len(), digest.as_ptr(), digest.len(), md.as_const(), mgf1_md.map(CRef::as_const).unwrap_or(ptr::null()), salt_len, )?; // RSA_sign_pss_mgf1 guarantees that it only needs RSA_size bytes for // the signature. let rsa_size = key.rsa_size().unwrap_abort(); assert_abort!(sig_len <= rsa_size.get()); Ok(sig_len) } } /// The `RSA_verify` function. #[must_use] #[cfg(feature = "rsa-pkcs1v15")] pub fn rsa_verify(hash_nid: c_int, digest: &[u8], sig: &[u8], key: &CHeapWrapper<RSA>) -> bool { unsafe { RSA_verify( hash_nid, digest.as_ptr(), digest.len(), sig.as_ptr(), sig.len(), // RSA_verify does not mutate its argument but, for // backwards-compatibility reasons, continues to take a normal // (non-const) pointer. key.as_const() as *mut _, ) } } /// The `RSA_verify_pss_mgf1` function. #[must_use] pub fn rsa_verify_pss_mgf1( key: &CHeapWrapper<RSA>, digest: &[u8], md: &CRef<'static, EVP_MD>, mgf1_md: Option<&CRef<'static, EVP_MD>>, salt_len: c_int, sig: &[u8], ) -> bool { unsafe { RSA_verify_pss_mgf1( // RSA_verify_pss_mgf1 does not mutate its argument but, for // backwards-compatibility reasons, continues to take a normal // (non-const) pointer. key.as_const() as *mut _, digest.as_ptr(), digest.len(), md.as_const(), mgf1_md.map(CRef::as_const).unwrap_or(ptr::null()), salt_len, sig.as_ptr(), sig.len(), ) } } /// Implements `CStackWrapper` for a hash context type. /// /// The caller provides doc comments, a public method name, and a private /// function name (from the `raw` module) for an update function and a final /// function (e.g., `SHA256_Update` and `SHA256_Final`). Note that, as multiple /// impl blocks are allowed for a particular type, the same context type may be /// used multiple times. This is useful because both SHA-384 and SHA-512 use the /// `SHA512_CTX` context type. macro_rules! impl_hash { ($ctx:ident, $digest_len:ident, #[$update_doc:meta] $update:ident, $update_raw:ident, #[$final_doc:meta] $final:ident, $final_raw:ident) => { impl CStackWrapper<$ctx> { #[$update_doc] pub fn $update(&mut self, data: &[u8]) { unsafe { ::boringssl::raw::$update_raw( self.as_mut(), data.as_ptr() as *const c_void, data.len(), ) } } #[$final_doc] #[must_use] pub fn $final( &mut self, ) -> [u8; ::boringssl::ffi::$digest_len as usize] { unsafe { let mut md: [u8; ::boringssl::ffi::$digest_len as usize] = mem::uninitialized(); // SHA1_Final promises to return 1. SHA256_Final, // SHA384_Final, and SHA512_Final all document that they // only fail due to programmer error. The only input to the // function which could cause this is the context. I suspect // that the error condition is that XXX_Final is called // twice without resetting, but I'm not sure. Until we // figure it out, let's err on the side of caution and abort // here. // // TODO(joshlf): Figure out how XXX_Final can fail. ::boringssl::raw::$final_raw((&mut md[..]).as_mut_ptr(), self.as_mut()).unwrap_abort(); md } } } }; (@doc_string $s:expr) => (#[doc="The `"] #[doc=$s] #[doc="` function."]); } impl_hash!( SHA_CTX, SHA_DIGEST_LENGTH, /// The `SHA1_Update` function. sha1_update, SHA1_Update, /// The `SHA1_Final` function. sha1_final, SHA1_Final ); impl_hash!( SHA256_CTX, SHA256_DIGEST_LENGTH, /// The `SHA256_Update` function. sha256_update, SHA256_Update, /// The `SHA256_Final` function. sha256_final, SHA256_Final ); impl_hash!( SHA512_CTX, SHA384_DIGEST_LENGTH, /// The `SHA384_Update` function. sha384_update, SHA384_Update, /// The `SHA384_Final` function. sha384_final, SHA384_Final ); impl_hash!( SHA512_CTX, SHA512_DIGEST_LENGTH, /// The `SHA512_Update` function. sha512_update, SHA512_Update, /// The `SHA512_Final` function. sha512_final, SHA512_Final ); /// The `CRYPTO_memcmp` function. /// /// `crypto_memcmp` first verifies that `a.len() == b.len()` before calling /// `CRYPTO_memcmp`. #[must_use] pub fn crypto_memcmp(a: &[u8], b: &[u8]) -> bool { if a.len() != b.len() { return false; } unsafe { CRYPTO_memcmp(a.as_ptr() as *const c_void, b.as_ptr() as *const c_void, a.len()) == 0 } } /// The `RAND_bytes` function. pub fn rand_bytes(buf: &mut [u8]) { unsafe { RAND_bytes(buf.as_mut_ptr(), buf.len()) } } /// An error generated by BoringSSL. /// /// The `Debug` impl prints a stack trace. Each element of the trace corresponds /// to a function within BoringSSL which voluntarily pushed itself onto the /// stack. In this sense, it is not the same as a normal stack trace. Each /// element of the trace is of the form `[thread id]:error:[error code]:[library /// name]:OPENSSL_internal:[reason string]:[file]:[line number]:[optional string /// data]`. /// /// The `Display` impl prints the first element of the stack trace. /// /// Some BoringSSL functions do not record any error in the error stack. Errors /// generated from such functions are printed as `error calling <function name>` /// for both `Debug` and `Display` impls. pub struct BoringError { stack_trace: Vec<String>, } impl BoringError { /// Consumes the error stack. /// /// `f` is the name of the function that failed. If the error stack is empty /// (some BoringSSL functions do not push errors onto the stack when /// returning errors), the returned `BoringError` will simply note that the /// named function failed; both the `Debug` and `Display` implementations /// will return `error calling f`, where `f` is the value of the `f` /// argument. #[must_use] fn consume_stack(f: &str) -> BoringError { let stack_trace = { let trace = get_error_stack_trace(); if trace.is_empty() { vec![format!("error calling {}", f)] } else { trace } }; BoringError { stack_trace } } /// The number of frames in the stack trace. /// /// Guaranteed to be at least 1. #[must_use] pub fn stack_depth(&self) -> usize { self.stack_trace.len() } } fn get_error_stack_trace() -> Vec<String> { // Credit to agl@google.com for this implementation. unsafe extern "C" fn error_callback(s: *const c_char, s_len: usize, ctx: *mut c_void) -> c_int { let stack_trace = ctx as *mut Vec<String>; let s = ::std::slice::from_raw_parts(s as *const u8, s_len - 1); (*stack_trace).push(String::from_utf8_lossy(s).to_string()); 1 } let mut stack_trace = Vec::new(); unsafe { ERR_print_errors_cb(Some(error_callback), &mut stack_trace as *mut _ as *mut c_void) }; stack_trace } impl Display for BoringError { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { write!(f, "{}", self.stack_trace[0]) } } impl Debug for BoringError { fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { for elem in &self.stack_trace { writeln!(f, "{}", elem)?; } Ok(()) } } #[cfg(test)] mod tests { use super::*; use util::should_fail; #[test] fn test_boring_error() { let _ = CStackWrapper::cbs_with_temp_buffer(&[], |cbs| { should_fail( CHeapWrapper::evp_parse_public_key(cbs), "boringssl::EVP_parse_public_key", "public key routines:OPENSSL_internal:DECODE_ERROR", ); }); } }
35.045842
145
0.615916
e2b01ff8edf059736da194e03d3a7c066bb4ca51
4,962
use crate::conf::MEM_OFF; #[derive(Debug)] pub struct Dram { memory: Vec<u8>, } impl Dram { pub fn new(mem_size: usize) -> Dram { Dram { memory: vec![0; mem_size], } } #[inline(always)] fn set_mem(&mut self, idx: usize, data: u8) { if self.memory.len() < idx { panic!("access to invalid address"); } self.memory[idx] = data; } #[inline(always)] fn get_mem(&self, idx: usize) -> u8 { match self.memory.get(idx) { Some(data) => *data, None => panic!("access to invalid address: 0x{:016X}", idx), } } #[allow(dead_code)] pub fn print(&self) { println!("{:?}", self.memory); } pub fn prange(&self, mut begin: usize, mut end: usize) { begin -= MEM_OFF; end -= MEM_OFF; if begin % 16 != 0 { begin -= begin % 16; } if end % 16 != 0 { end += 16 - end % 16; } for i in begin..end { if i % 16 == 0 { print!("{:016X} | ", i + MEM_OFF); } print!("{:02X}", self.get_mem(i)); if (i + 1) % 2 == 0 { print!(" "); } if (i + 1) % 16 == 0 { println!(); } } } pub fn load(&mut self, data: String) { let mut data = to_byte_array(data); if self.memory.len() < data.len() { panic!("data is big"); } if data.len() % 4 != 0 { for _ in 0..data.len() % 4 { data.push(0); } } // to little endian for i in (0..data.len()).step_by(4) { self.set_mem(i + MEM_OFF, data[i + 3]); self.set_mem(i + 1 + MEM_OFF, data[i + 2]); self.set_mem(i + 2 + MEM_OFF, data[i + 1]); self.set_mem(i + 3 + MEM_OFF, data[i]); } } pub fn load_seg( &mut self, data: &Vec<u8>, seg_off: usize, seg_phys_addr: usize, seg_size: usize, ) { if self.memory.len() < seg_size { panic!("segment is big"); } for i in 0..seg_size { self.set_mem(seg_phys_addr + i - MEM_OFF, data[seg_off + i]); } } pub fn load_byte(&self, addr: u64) -> u8 { self.get_mem(addr as usize) } pub fn load_hword(&self, begin: u64) -> u16 { let mut res: u16 = 0; for (i, addr) in (begin..begin + 2).enumerate() { let mut data = self.get_mem(addr as usize) as u16; data <<= (i * 8) as u16; res |= data; } res } pub fn load_word(&self, addr: u64) -> u32 { let mut res: u32 = 0; for (i, addr) in (addr..addr + 4).enumerate() { let mut data = self.get_mem(addr as usize) as u32; data <<= (i * 8) as u32; res |= data; } res } pub fn load_dword(&self, addr: u64) -> u64 { let mut res: u64 = 0; for (i, addr) in (addr..addr + 8).enumerate() { let mut data = self.get_mem(addr as usize) as u64; data <<= (i * 8) as u64; res |= data; } res } pub fn store_byte(&mut self, addr: u64, data: u8) { self.set_mem(addr as usize, data); } pub fn store_hword(&mut self, addr: u64, data: u16) { self.set_mem(addr as usize, (data & 0xF) as u8); let addr = addr + 1; self.set_mem(addr as usize, (data >> 8) as u8); } pub fn store_word(&mut self, mut addr: u64, mut data: u32) { self.set_mem(addr as usize, (data & 0xFF) as u8); for _ in 0..3 { addr = addr + 1; data >>= 8; self.set_mem(addr as usize, (data & 0xFF) as u8); } } pub fn store_dword(&mut self, mut addr: u64, mut data: u64) { self.set_mem(addr as usize, (data & 0xFF) as u8); for _ in 0..7 { addr = addr + 1; data >>= 8; self.set_mem(addr as usize, (data & 0xFF) as u8); } } } fn to_byte_array(data: String) -> Vec<u8> { if data.len() % 2 != 0 { panic!("data length is odd"); } let mut chars = data.chars(); let mut res = Vec::new(); for _ in 0..data.len() / 2 { let hi = to_hex(chars.next().unwrap()); let lo = to_hex(chars.next().unwrap()); let byte = hi << 4 | lo; res.push(byte); } res } fn to_hex(c: char) -> u8 { match c.to_ascii_lowercase() { '0' => 0x0, '1' => 0x1, '2' => 0x2, '3' => 0x3, '4' => 0x4, '5' => 0x5, '6' => 0x6, '7' => 0x7, '8' => 0x8, '9' => 0x9, 'a' => 0xa, 'b' => 0xb, 'c' => 0xc, 'd' => 0xd, 'e' => 0xe, 'f' => 0xf, _ => panic!("Not hex: {}", c), } }
24.934673
73
0.43551
89c9bcee052fbf73427ebb581082c6b18d4b45e9
429
// Checks if the correct annotation for the sysv64 ABI is passed to // llvm. Also checks that the abi-sysv64 feature gate allows usage // of the sysv64 abi. // ignore-arm // ignore-aarch64 // ignore-riscv64 sysv64 not supported // compile-flags: -C no-prepopulate-passes #![crate_type = "lib"] // CHECK: define x86_64_sysvcc i64 @has_sysv64_abi #[no_mangle] pub extern "sysv64" fn has_sysv64_abi(a: i64) -> i64 { a * 2 }
23.833333
67
0.715618
33a8ba896f5089acc69bd89ae78eaf0288363334
186
pub mod controls; mod core; pub mod get; pub mod put; pub mod tools; pub use self::core::{MessageData, MessageStore, Settings, INITIAL}; pub use self::get::Get; pub use self::put::Put;
18.6
67
0.72043
6172b440a09ca9e5535ab10f08f03f575f186b0e
2,291
use bytes::Bytes; use std::mem; use crate::dds::{DdsVariableDetails, VarType}; /// XDR encoded length. pub fn xdr_length(len: u32) -> [u8; 8] { let len = len.to_be(); let x: [u32; 2] = [len, len]; unsafe { mem::transmute(x) } } /// Upcast 16-bit datatypes to 32-bit datatypes. Non 16-bit variables are passed through as-is. /// /// The input bytes are assumed to be in native endianness. pub fn xdr_serialize(v: &DdsVariableDetails, b: Bytes) -> Bytes { use VarType::*; // TODO: * Check performance of casting. // * Move common code to templated function over Pod's // * Use either byte-slice-cast or bytemuck. match v.vartype { UInt16 => { let b: &[u8] = &*b; let u: &[u16] = bytemuck::cast_slice(b); let mut n: Vec<u8> = Vec::with_capacity(u.len() * 4); unsafe { n.set_len(u.len() * 4); } let nn: &mut [u32] = bytemuck::cast_slice_mut(&mut n); for (s, d) in u.iter().zip(nn.iter_mut()) { if cfg!(target_endian = "big") { *d = *s as u32; } else { *d = (s.swap_bytes() as u32).swap_bytes(); } } Bytes::from(n) } Int16 => { let b: &[u8] = &*b; let u: &[i16] = bytemuck::cast_slice(b); let mut n: Vec<u8> = Vec::with_capacity(u.len() * 4); unsafe { n.set_len(u.len() * 4); } let nn: &mut [i32] = bytemuck::cast_slice_mut(&mut n); for (s, d) in u.iter().zip(nn.iter_mut()) { if cfg!(target_endian = "big") { *d = *s as i32; } else { *d = (s.swap_bytes() as i32).swap_bytes(); } } Bytes::from(n) }, Float32 | UInt32 | Int32 | Float64 | UInt64 | Int64 => { unimplemented!("need to swap to big endinaness"); }, _ => { b } } } #[cfg(test)] mod test { use super::*; #[test] fn length() { let x: u32 = 2; let b = xdr_length(x); assert_eq!(b, [0u8, 0, 0, 2, 0, 0, 0, 2]); } }
25.741573
95
0.450458
bbae2032c40b173b14273ed25e3f272e827711ee
10,136
use futures_util::stream::Stream; use http_range::HttpRange; use hyper::body::{Body, Bytes}; use std::cmp::min; use std::io::{Cursor, Error as IoError, SeekFrom, Write}; use std::mem::MaybeUninit; use std::pin::Pin; use std::task::{Context, Poll}; use std::vec; use tokio::fs::File; use tokio::io::{AsyncRead, AsyncSeek, ReadBuf}; const BUF_SIZE: usize = 8 * 1024; /// Wraps a `tokio::fs::File`, and implements a stream of `Bytes`s. pub struct FileBytesStream { file: File, buf: Box<[MaybeUninit<u8>; BUF_SIZE]>, range_remaining: u64, } impl FileBytesStream { /// Create a new stream from the given file. pub fn new(file: File) -> FileBytesStream { let buf = Box::new([MaybeUninit::uninit(); BUF_SIZE]); FileBytesStream { file, buf, range_remaining: u64::MAX, } } fn new_with_limit(file: File, range_remaining: u64) -> FileBytesStream { let buf = Box::new([MaybeUninit::uninit(); BUF_SIZE]); FileBytesStream { file, buf, range_remaining, } } } impl Stream for FileBytesStream { type Item = Result<Bytes, IoError>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { let Self { ref mut file, ref mut buf, ref mut range_remaining, } = *self; let max_read_length = min(*range_remaining, buf.len() as u64) as usize; let mut read_buf = ReadBuf::uninit(&mut buf[..max_read_length]); match Pin::new(file).poll_read(cx, &mut read_buf) { Poll::Ready(Ok(())) => { let filled = read_buf.filled(); *range_remaining -= filled.len() as u64; if filled.is_empty() { Poll::Ready(None) } else { Poll::Ready(Some(Ok(Bytes::copy_from_slice(filled)))) } } Poll::Ready(Err(e)) => Poll::Ready(Some(Err(e))), Poll::Pending => Poll::Pending, } } } impl FileBytesStream { /// Create a Hyper `Body` from this stream. pub fn into_body(self) -> Body { Body::wrap_stream(self) } } #[derive(PartialEq, Eq)] enum FileSeekState { NeedSeek, Seeking, Reading, } /// Wraps a `tokio::fs::File`, and implements a stream of `Bytes`s reading a portion of the /// file given by `range`. pub struct FileBytesStreamRange { file_stream: FileBytesStream, seek_state: FileSeekState, start_offset: u64, } impl FileBytesStreamRange { /// Create a new stream from the given file and range pub fn new(file: File, range: HttpRange) -> FileBytesStreamRange { FileBytesStreamRange { file_stream: FileBytesStream::new_with_limit(file, range.length), seek_state: FileSeekState::NeedSeek, start_offset: range.start, } } fn without_initial_range(file: File) -> FileBytesStreamRange { FileBytesStreamRange { file_stream: FileBytesStream::new_with_limit(file, 0), seek_state: FileSeekState::NeedSeek, start_offset: 0, } } } impl Stream for FileBytesStreamRange { type Item = Result<Bytes, IoError>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { let Self { ref mut file_stream, ref mut seek_state, start_offset, } = *self; if *seek_state == FileSeekState::NeedSeek { *seek_state = FileSeekState::Seeking; if let Err(e) = Pin::new(&mut file_stream.file).start_seek(SeekFrom::Start(start_offset)) { return Poll::Ready(Some(Err(e))); } } if *seek_state == FileSeekState::Seeking { match Pin::new(&mut file_stream.file).poll_complete(cx) { Poll::Ready(Ok(..)) => *seek_state = FileSeekState::Reading, Poll::Ready(Err(e)) => return Poll::Ready(Some(Err(e))), Poll::Pending => return Poll::Pending, } } Pin::new(file_stream).poll_next(cx) } } impl FileBytesStreamRange { /// Create a Hyper `Body` from this stream. pub fn into_body(self) -> Body { Body::wrap_stream(self) } } /// Wraps a `tokio::fs::File`, and implements a stream of `Bytes`s reading multiple portions of /// the file given by `ranges` using a chunked multipart/byteranges response. A boundary is /// required to separate the chunked components and therefore needs to be unlikely to be in any /// file. pub struct FileBytesStreamMultiRange { file_range: FileBytesStreamRange, range_iter: vec::IntoIter<HttpRange>, is_first_boundary: bool, completed: bool, boundary: String, content_type: String, file_length: u64, } impl FileBytesStreamMultiRange { /// Create a new stream from the given file, ranges, boundary and file length. pub fn new( file: File, ranges: Vec<HttpRange>, boundary: String, file_length: u64, ) -> FileBytesStreamMultiRange { FileBytesStreamMultiRange { file_range: FileBytesStreamRange::without_initial_range(file), range_iter: ranges.into_iter(), boundary, is_first_boundary: true, completed: false, content_type: String::new(), file_length, } } /// Set the Content-Type header in the multipart/byteranges chunks. pub fn set_content_type(&mut self, content_type: &str) { self.content_type = content_type.to_string(); } /// Computes the length of the body for the multi-range response being produced by this /// `FileBytesStreamMultiRange`. This function is required to be mutable because it temporarily /// uses pre-allocated buffers. pub fn compute_length(&mut self) -> u64 { let Self { ref mut file_range, ref range_iter, ref boundary, ref content_type, file_length, .. } = *self; let mut total_length = 0; let mut is_first = true; for range in range_iter.as_slice() { let mut read_buf = ReadBuf::uninit(&mut file_range.file_stream.buf[..]); render_multipart_header( &mut read_buf, boundary, content_type, *range, is_first, file_length, ); is_first = false; total_length += read_buf.filled().len() as u64; total_length += range.length; } let mut read_buf = ReadBuf::uninit(&mut file_range.file_stream.buf[..]); render_multipart_header_end(&mut read_buf, boundary); total_length += read_buf.filled().len() as u64; total_length } } fn render_multipart_header( read_buf: &mut ReadBuf<'_>, boundary: &str, content_type: &str, range: HttpRange, is_first: bool, file_length: u64, ) { if !is_first { read_buf.put_slice(b"\r\n"); } read_buf.put_slice(b"--"); read_buf.put_slice(boundary.as_bytes()); read_buf.put_slice(b"\r\nContent-Range: bytes "); // 64 is 20 (max length of 64 bit integer) * 3 + 4 (symbols, new line) let mut tmp_buffer = [0; 64]; let mut tmp_storage = Cursor::new(&mut tmp_buffer[..]); write!( &mut tmp_storage, "{}-{}/{}\r\n", range.start, range.start + range.length - 1, file_length, ) .expect("buffer unexpectedly too small"); let end_position = tmp_storage.position() as usize; let tmp_storage = tmp_storage.into_inner(); read_buf.put_slice(&tmp_storage[..end_position]); if !content_type.is_empty() { read_buf.put_slice(b"Content-Type: "); read_buf.put_slice(content_type.as_bytes()); read_buf.put_slice(b"\r\n"); } read_buf.put_slice(b"\r\n"); } fn render_multipart_header_end(read_buf: &mut ReadBuf<'_>, boundary: &str) { read_buf.put_slice(b"\r\n--"); read_buf.put_slice(boundary.as_bytes()); read_buf.put_slice(b"--\r\n"); } impl Stream for FileBytesStreamMultiRange { type Item = Result<Bytes, IoError>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { let Self { ref mut file_range, ref mut range_iter, ref mut is_first_boundary, ref mut completed, ref boundary, ref content_type, file_length, } = *self; if *completed { return Poll::Ready(None); } if file_range.file_stream.range_remaining == 0 { let range = match range_iter.next() { Some(r) => r, None => { *completed = true; let mut read_buf = ReadBuf::uninit(&mut file_range.file_stream.buf[..]); render_multipart_header_end(&mut read_buf, boundary); return Poll::Ready(Some(Ok(Bytes::copy_from_slice(read_buf.filled())))); } }; file_range.seek_state = FileSeekState::NeedSeek; file_range.start_offset = range.start; file_range.file_stream.range_remaining = range.length; let cur_is_first = *is_first_boundary; *is_first_boundary = false; let mut read_buf = ReadBuf::uninit(&mut file_range.file_stream.buf[..]); render_multipart_header( &mut read_buf, boundary, content_type, range, cur_is_first, file_length, ); return Poll::Ready(Some(Ok(Bytes::copy_from_slice(read_buf.filled())))); } Pin::new(file_range).poll_next(cx) } } impl FileBytesStreamMultiRange { /// Create a Hyper `Body` from this stream. pub fn into_body(self) -> Body { Body::wrap_stream(self) } }
30.715152
100
0.581788
08dce130c2a1d089dd68cefefac4c81eff1d6e89
14,316
use crate::query::{Expression, IdentExpression, Value}; use proc_macro2::Span; use syn::parse::{Parse, ParseBuffer}; use syn::{parenthesized, token, Error, Token}; pub enum MathematicalExpression { Paren(Box<Expression>), BitInverse(Box<Expression>), BitXor(Box<Expression>, Box<Expression>), Multi(Box<Expression>, Box<Expression>), Mod(Box<Expression>, Box<Expression>), Div(Box<Expression>, Box<Expression>), Add(Box<Expression>, Box<Expression>), Sub(Box<Expression>, Box<Expression>), BitLeftShift(Box<Expression>, Box<Expression>), BitRightShift(Box<Expression>, Box<Expression>), BitAnd(Box<Expression>, Box<Expression>), BitOr(Box<Expression>, Box<Expression>), GT(Box<Expression>, Box<Expression>), LT(Box<Expression>, Box<Expression>), GTE(Box<Expression>, Box<Expression>), LTE(Box<Expression>, Box<Expression>), EQ(Box<Expression>, Box<Expression>), NEQ(Box<Expression>, Box<Expression>), } #[derive(Debug)] enum BinaryOperator { BitXor(Token![^]), Multi(Token![*]), Mod(Token![%]), Div(Token![/]), Add(Token![+]), Sub(Token![-]), BitLeftShift(Token![<<]), BitRightShift(Token![>>]), BitAnd(Token![&]), BitOr(Token![|]), GT(Token![>]), LT(Token![<]), GTE(Token![>=]), LTE(Token![<=]), EQ(Token![==]), NEQ(Token![!=]), } enum UnaryOperator { BitInverse(Token![~]), } impl Parse for BinaryOperator { fn parse<'a>(input: &'a ParseBuffer<'a>) -> Result<Self, Error> { if input.peek(Token![^]) { input.parse().map(BinaryOperator::BitXor) } else if input.peek(Token![*]) { input.parse().map(BinaryOperator::Multi) } else if input.peek(Token![/]) { input.parse().map(BinaryOperator::Div) } else if input.peek(Token![%]) { input.parse().map(BinaryOperator::Mod) } else if input.peek(Token![+]) { input.parse().map(BinaryOperator::Add) } else if input.peek(Token![-]) { input.parse().map(BinaryOperator::Sub) } else if input.peek(Token![>>]) { input.parse().map(BinaryOperator::BitRightShift) } else if input.peek(Token![<<]) { input.parse().map(BinaryOperator::BitLeftShift) } else if input.peek(Token![&]) { input.parse().map(BinaryOperator::BitAnd) } else if input.peek(Token![|]) { input.parse().map(BinaryOperator::BitOr) } else if input.peek(Token![<]) { input.parse().map(BinaryOperator::LT) } else if input.peek(Token![>]) { input.parse().map(BinaryOperator::GT) } else if input.peek(Token![<=]) { input.parse().map(BinaryOperator::LTE) } else if input.peek(Token![>=]) { input.parse().map(BinaryOperator::GTE) } else if input.peek(Token![==]) { input.parse().map(BinaryOperator::EQ) } else if input.peek(Token![!=]) { input.parse().map(BinaryOperator::NEQ) } else { Err(Error::new( Span::call_site(), "Cannot parse into an binary operator", )) } } } impl Parse for UnaryOperator { fn parse<'a>(input: &'a ParseBuffer<'a>) -> Result<Self, Error> { if input.peek(Token![~]) { input.parse().map(UnaryOperator::BitInverse) } else { Err(Error::new( Span::call_site(), "Cannot parse into an Unary operator", )) } } } impl BinaryOperator { pub fn construct_expr(&self, left: Expression, right: Expression) -> MathematicalExpression { let left_box = Box::new(left); let right_box = Box::new(right); match self { BinaryOperator::BitXor(_) => MathematicalExpression::BitXor(left_box, right_box), BinaryOperator::Multi(_) => MathematicalExpression::Multi(left_box, right_box), BinaryOperator::Div(_) => MathematicalExpression::Div(left_box, right_box), BinaryOperator::Mod(_) => MathematicalExpression::Mod(left_box, right_box), BinaryOperator::Add(_) => MathematicalExpression::Add(left_box, right_box), BinaryOperator::Sub(_) => MathematicalExpression::Sub(left_box, right_box), BinaryOperator::BitLeftShift(_) => { MathematicalExpression::BitLeftShift(left_box, right_box) } BinaryOperator::BitRightShift(_) => { MathematicalExpression::BitRightShift(left_box, right_box) } BinaryOperator::BitAnd(_) => MathematicalExpression::BitAnd(left_box, right_box), BinaryOperator::BitOr(_) => MathematicalExpression::BitOr(left_box, right_box), BinaryOperator::GT(_) => MathematicalExpression::GT(left_box, right_box), BinaryOperator::LT(_) => MathematicalExpression::LT(left_box, right_box), BinaryOperator::GTE(_) => MathematicalExpression::GTE(left_box, right_box), BinaryOperator::LTE(_) => MathematicalExpression::LTE(left_box, right_box), BinaryOperator::EQ(_) => MathematicalExpression::EQ(left_box, right_box), BinaryOperator::NEQ(_) => MathematicalExpression::NEQ(left_box, right_box), } } pub fn precedence(&self) -> Precedence { match self { BinaryOperator::BitXor(_) => Precedence::BitXor, BinaryOperator::Multi(_) | BinaryOperator::Div(_) | BinaryOperator::Mod(_) => { Precedence::Term } BinaryOperator::Add(_) | BinaryOperator::Sub(_) => Precedence::Add, BinaryOperator::BitLeftShift(_) | BinaryOperator::BitRightShift(_) => { Precedence::BitShift } BinaryOperator::BitAnd(_) => Precedence::BitAnd, BinaryOperator::BitOr(_) => Precedence::BitOr, BinaryOperator::GT(_) | BinaryOperator::LT(_) | BinaryOperator::GTE(_) | BinaryOperator::LTE(_) | BinaryOperator::EQ(_) | BinaryOperator::NEQ(_) => Precedence::Comparison, } } } impl UnaryOperator { pub fn construct_expr(&self, expr: Expression) -> MathematicalExpression { let boxed_expr = Box::new(expr); match self { UnaryOperator::BitInverse(_) => MathematicalExpression::BitInverse(boxed_expr), } } pub fn precedence(&self) -> Precedence { match self { UnaryOperator::BitInverse(_) => Precedence::BitInverse, } } } #[derive(Ord, PartialOrd, Eq, PartialEq, Debug)] pub enum Precedence { None, Comparison, BitOr, BitAnd, BitShift, Add, Term, BitXor, BitInverse, Parentheses, } impl Precedence { fn peek<'a>(input: &'a ParseBuffer<'a>) -> Option<Self> { if input.peek(Token![^]) { Some(Precedence::BitXor) } else if input.peek(Token![*]) | input.peek(Token![/]) | input.peek(Token![%]) { Some(Precedence::Term) } else if input.peek(Token![+]) | input.peek(Token![-]) { Some(Precedence::Add) } else if input.peek(Token![>>]) | input.peek(Token![<<]) { Some(Precedence::BitShift) } else if input.peek(Token![&]) { Some(Precedence::BitAnd) } else if input.peek(Token![|]) { Some(Precedence::BitOr) } else if input.peek(Token![<]) | input.peek(Token![>]) | input.peek(Token![<=]) | input.peek(Token![>=]) | input.peek(Token![==]) | input.peek(Token![!=]) { Some(Precedence::Comparison) } else { None } } } impl MathematicalExpression { pub fn parse_right_as_mathematical_expr<'a>( input: &'a ParseBuffer<'a>, operator_precedence: Precedence, ) -> Result<Self, Error> { let expr = Self::parse_right_expression(input, operator_precedence)?; match expr { Expression::MathematicalExpr(mathematical_expr) => Ok(mathematical_expr), other_expr => Ok(MathematicalExpression::Paren(Box::new(other_expr))), } } pub fn parse_right_expression<'a>( input: &'a ParseBuffer<'a>, operator_precedence: Precedence, ) -> Result<Expression, Error> { let result = if input.peek(token::Paren) { Self::parse_from_parentheses(input).map(Expression::MathematicalExpr) } else if let Ok(unary_operator) = input.parse::<UnaryOperator>() { let right = MathematicalExpression::parse_right_as_mathematical_expr( input, unary_operator.precedence(), )?; Ok(Expression::MathematicalExpr( unary_operator.construct_expr(Expression::MathematicalExpr(right)), )) } else if let Ok(value) = input.parse::<Value>() { Ok(Expression::Value(value)) } else if let Ok(ident) = input.parse::<IdentExpression>() { Ok(Expression::IdentExpr(ident)) } else { Err(Error::new( Span::call_site(), "Cannot parse into expression or unary operator", )) }?; let next_binary_operator_precedence = Precedence::peek(input); match next_binary_operator_precedence { Some(next_precedence) if next_precedence > operator_precedence => { let operator = input.parse::<BinaryOperator>()?; let next_expr = Self::parse_right_as_mathematical_expr(input, operator.precedence())?; Ok(Expression::MathematicalExpr(operator.construct_expr( result, Expression::MathematicalExpr(next_expr), ))) } _ => Ok(result), } } fn parse_from_parentheses<'a>(input: &'a ParseBuffer<'a>) -> Result<Self, Error> { let content; parenthesized!(content in input); Ok(content.parse::<MathematicalExpression>()?) } } impl Parse for MathematicalExpression { fn parse<'a>(input: &'a ParseBuffer<'a>) -> Result<Self, Error> { let mut result = Self::parse_right_expression(input, Precedence::None)?; while !input.is_empty() { let operator = input.parse::<BinaryOperator>()?; result = Expression::MathematicalExpr(operator.construct_expr( result, Self::parse_right_expression(input, operator.precedence())?, )) } match result { Expression::MathematicalExpr(mathematical_expr) => Ok(mathematical_expr), other_expr => Ok(MathematicalExpression::Paren(Box::new(other_expr))), } } } #[test] fn test_mathematical_expr() { use syn::Lit; let expr: MathematicalExpression = syn::parse_quote! { 1 + @value * 10 > ~10 % (foo.bar / 3) }; if let MathematicalExpression::GT(gt_left, gt_right) = expr { if let Expression::MathematicalExpr(MathematicalExpression::Add(add_left, add_right)) = *gt_left { if let Expression::Value(Value::Lit(Lit::Int(lit))) = *add_left { assert_eq!(lit.base10_parse::<i32>().unwrap(), 1) } else { panic!("Add left value") } if let Expression::MathematicalExpr(MathematicalExpression::Multi( multi_left, multi_right, )) = *add_right { if let Expression::Value(Value::ExternalValue(ident)) = *multi_left { assert_eq!(ident.to_string(), "value".to_string()) } else { panic!("multi left") } if let Expression::MathematicalExpr(MathematicalExpression::Paren(nested)) = *multi_right { if let Expression::Value(Value::Lit(Lit::Int(lit))) = *nested { assert_eq!(lit.base10_parse::<i32>().unwrap(), 10); } else { panic!("multi right") } } else { panic!("multi right") } } } else { panic!("Add"); } if let Expression::MathematicalExpr(MathematicalExpression::Mod(mod_left, mod_right)) = *gt_right { if let Expression::MathematicalExpr(MathematicalExpression::BitInverse(inverse)) = *mod_left { if let Expression::MathematicalExpr(MathematicalExpression::Paren(nested)) = *inverse { if let Expression::Value(Value::Lit(Lit::Int(lit))) = *nested { assert_eq!(lit.base10_parse::<i32>().unwrap(), 10) } else { panic!("Inverse value"); } } else { panic!("Inverse nested"); } } else { panic!("Inverse") } if let Expression::MathematicalExpr(MathematicalExpression::Div(div_left, div_right)) = *mod_right { if let Expression::IdentExpr(ident) = *div_left { assert_eq!(ident.segments, vec!["foo".to_string(), "bar".to_string()]); } else { panic!("Ident"); } if let Expression::MathematicalExpr(MathematicalExpression::Paren( div_right_nested, )) = *div_right { if let Expression::Value(Value::Lit(Lit::Int(lit))) = *div_right_nested { assert_eq!(lit.base10_parse::<i32>().unwrap(), 3); } else { panic!("Div right nested"); } } else { panic!("Div right") } } else { panic!("Div"); } } else { panic!("Mod"); } } else { panic!("GT") } }
36.243038
99
0.545264
649c1fedda5c75cf6e7cad62dae7b7abb24a738d
6,565
//! Bindings to the Legacy/gauges.h API use crate::sys; #[doc(hidden)] pub trait SimVarF64 { fn to(self) -> f64; fn from(v: f64) -> Self; } impl SimVarF64 for f64 { fn to(self) -> f64 { self } fn from(v: f64) -> Self { v } } impl SimVarF64 for bool { fn to(self) -> f64 { if self { 1.0 } else { 0.0 } } fn from(v: f64) -> Self { v != 0.0 } } impl SimVarF64 for u8 { fn to(self) -> f64 { self as f64 } fn from(v: f64) -> Self { v as Self } } /// aircraft_varget /// get_aircraft_var_enum #[derive(Debug)] pub struct AircraftVariable { simvar: sys::ENUM, units: sys::ENUM, index: sys::SINT32, } impl AircraftVariable { pub fn from(name: &str, units: &str, index: usize) -> Result<Self, Box<dyn std::error::Error>> { let name = std::ffi::CString::new(name).unwrap(); let units = std::ffi::CString::new(units).unwrap(); let simvar = unsafe { sys::get_aircraft_var_enum(name.as_ptr()) }; if simvar == -1 { return Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, "invalid name", ))); } let units = unsafe { sys::get_units_enum(units.as_ptr()) }; if units == -1 { return Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, "invalid units", ))); } Ok(Self { simvar, units, index: index as sys::SINT32, }) } pub fn get<T: SimVarF64>(&self) -> T { let v = unsafe { sys::aircraft_varget(self.simvar, self.units, self.index) }; T::from(v) } } /// register_named_variable /// set_named_variable_typed_value /// get_named_variable_value /// set_named_variable_value #[derive(Debug)] pub struct NamedVariable(sys::ID); impl NamedVariable { pub fn from(name: &str) -> Self { Self(unsafe { let name = std::ffi::CString::new(name).unwrap(); sys::register_named_variable(name.as_ptr()) }) } pub fn get_value<T: SimVarF64>(&self) -> T { let v = unsafe { sys::get_named_variable_value(self.0) }; T::from(v) } pub fn set_value(&self, v: impl SimVarF64) { let v = v.to(); unsafe { sys::set_named_variable_value(self.0, v) } } } /// trigger_key_event pub fn trigger_key_event(event_id: sys::ID32, value: sys::UINT32) { unsafe { sys::trigger_key_event(event_id, value); } } /// get_name_of_named_variable pub fn get_name_of_named_variable(id: sys::ID) -> Option<String> { unsafe { let name_ptr = sys::get_name_of_named_variable(id); if name_ptr == std::ptr::null() { None } else { Some( std::ffi::CStr::from_ptr(name_ptr) .to_string_lossy() .into_owned(), ) } } } #[doc(hidden)] pub trait ExecuteCalculatorCodeImpl { fn execute(code: &std::ffi::CStr) -> Option<Self> where Self: Sized; } #[doc(hidden)] impl ExecuteCalculatorCodeImpl for f64 { fn execute(code: &std::ffi::CStr) -> Option<Self> { unsafe { let mut n = 0.0; if sys::execute_calculator_code( code.as_ptr(), &mut n, std::ptr::null_mut(), std::ptr::null_mut(), ) == 1 { Some(n) } else { None } } } } #[doc(hidden)] impl ExecuteCalculatorCodeImpl for i32 { fn execute(code: &std::ffi::CStr) -> Option<Self> { unsafe { let mut n = 0; if sys::execute_calculator_code( code.as_ptr(), std::ptr::null_mut(), &mut n, std::ptr::null_mut(), ) == 1 { Some(n) } else { None } } } } #[doc(hidden)] impl ExecuteCalculatorCodeImpl for String { fn execute(code: &std::ffi::CStr) -> Option<Self> { unsafe { let mut s = std::ptr::null(); if sys::execute_calculator_code( code.as_ptr(), std::ptr::null_mut(), std::ptr::null_mut(), &mut s, ) == 1 { Some(std::ffi::CStr::from_ptr(s).to_str().unwrap().to_owned()) } else { None } } } } #[doc(hidden)] impl ExecuteCalculatorCodeImpl for () { fn execute(code: &std::ffi::CStr) -> Option<Self> { unsafe { if sys::execute_calculator_code( code.as_ptr(), std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), ) == 1 { Some(()) } else { None } } } } /// execute_calculator_code pub fn execute_calculator_code<T: ExecuteCalculatorCodeImpl>(code: &str) -> Option<T> { let code = std::ffi::CString::new(code).unwrap(); ExecuteCalculatorCodeImpl::execute(code.as_c_str()) } /// Holds compiled calculator code, wraps `gauge_calculator_code_precompile`. #[derive(Debug)] pub struct CompiledCalculatorCode { p_compiled: sys::PCSTRINGZ, _p_compiled_size: sys::UINT32, } impl CompiledCalculatorCode { /// Create a new CompiledCalculatorCode instance. pub fn new(code: &str) -> Option<Self> { let mut p_compiled = std::mem::MaybeUninit::uninit(); let mut p_compiled_size = std::mem::MaybeUninit::uninit(); unsafe { let code = std::ffi::CString::new(code).unwrap(); if sys::gauge_calculator_code_precompile( p_compiled.as_mut_ptr(), p_compiled_size.as_mut_ptr(), code.as_ptr(), ) != 0 { Some(CompiledCalculatorCode { p_compiled: p_compiled.assume_init(), _p_compiled_size: p_compiled_size.assume_init(), }) } else { None } } } /// Execute this CompiledCalculatorCode instance. pub fn execute<T: ExecuteCalculatorCodeImpl>(&self) -> Option<T> { ExecuteCalculatorCodeImpl::execute(unsafe { std::ffi::CStr::from_ptr(self.p_compiled) }) } }
25.057252
100
0.506778
390ecb306366fa501713778e6567395a237ce997
16,197
#[doc = "Register `MAN` reader"] pub struct R(crate::R<MAN_SPEC>); impl core::ops::Deref for R { type Target = crate::R<MAN_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<MAN_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<MAN_SPEC>) -> Self { R(reader) } } #[doc = "Register `MAN` writer"] pub struct W(crate::W<MAN_SPEC>); impl core::ops::Deref for W { type Target = crate::W<MAN_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<MAN_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<MAN_SPEC>) -> Self { W(writer) } } #[doc = "Field `TX_PL` reader - Transmitter Preamble Length"] pub struct TX_PL_R(crate::FieldReader<u8, u8>); impl TX_PL_R { pub(crate) fn new(bits: u8) -> Self { TX_PL_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for TX_PL_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `TX_PL` writer - Transmitter Preamble Length"] pub struct TX_PL_W<'a> { w: &'a mut W, } impl<'a> TX_PL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | (value as u32 & 0x0f); self.w } } #[doc = "Transmitter Preamble Pattern\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum TX_PP_A { #[doc = "0: The preamble is composed of '1's"] ALL_ONE = 0, #[doc = "1: The preamble is composed of '0's"] ALL_ZERO = 1, #[doc = "2: The preamble is composed of '01's"] ZERO_ONE = 2, #[doc = "3: The preamble is composed of '10's"] ONE_ZERO = 3, } impl From<TX_PP_A> for u8 { #[inline(always)] fn from(variant: TX_PP_A) -> Self { variant as _ } } #[doc = "Field `TX_PP` reader - Transmitter Preamble Pattern"] pub struct TX_PP_R(crate::FieldReader<u8, TX_PP_A>); impl TX_PP_R { pub(crate) fn new(bits: u8) -> Self { TX_PP_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TX_PP_A { match self.bits { 0 => TX_PP_A::ALL_ONE, 1 => TX_PP_A::ALL_ZERO, 2 => TX_PP_A::ZERO_ONE, 3 => TX_PP_A::ONE_ZERO, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `ALL_ONE`"] #[inline(always)] pub fn is_all_one(&self) -> bool { **self == TX_PP_A::ALL_ONE } #[doc = "Checks if the value of the field is `ALL_ZERO`"] #[inline(always)] pub fn is_all_zero(&self) -> bool { **self == TX_PP_A::ALL_ZERO } #[doc = "Checks if the value of the field is `ZERO_ONE`"] #[inline(always)] pub fn is_zero_one(&self) -> bool { **self == TX_PP_A::ZERO_ONE } #[doc = "Checks if the value of the field is `ONE_ZERO`"] #[inline(always)] pub fn is_one_zero(&self) -> bool { **self == TX_PP_A::ONE_ZERO } } impl core::ops::Deref for TX_PP_R { type Target = crate::FieldReader<u8, TX_PP_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `TX_PP` writer - Transmitter Preamble Pattern"] pub struct TX_PP_W<'a> { w: &'a mut W, } impl<'a> TX_PP_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TX_PP_A) -> &'a mut W { self.bits(variant.into()) } #[doc = "The preamble is composed of '1's"] #[inline(always)] pub fn all_one(self) -> &'a mut W { self.variant(TX_PP_A::ALL_ONE) } #[doc = "The preamble is composed of '0's"] #[inline(always)] pub fn all_zero(self) -> &'a mut W { self.variant(TX_PP_A::ALL_ZERO) } #[doc = "The preamble is composed of '01's"] #[inline(always)] pub fn zero_one(self) -> &'a mut W { self.variant(TX_PP_A::ZERO_ONE) } #[doc = "The preamble is composed of '10's"] #[inline(always)] pub fn one_zero(self) -> &'a mut W { self.variant(TX_PP_A::ONE_ZERO) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 8)) | ((value as u32 & 0x03) << 8); self.w } } #[doc = "Field `TX_MPOL` reader - Transmitter Manchester Polarity"] pub struct TX_MPOL_R(crate::FieldReader<bool, bool>); impl TX_MPOL_R { pub(crate) fn new(bits: bool) -> Self { TX_MPOL_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for TX_MPOL_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `TX_MPOL` writer - Transmitter Manchester Polarity"] pub struct TX_MPOL_W<'a> { w: &'a mut W, } impl<'a> TX_MPOL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | ((value as u32 & 0x01) << 12); self.w } } #[doc = "Field `RX_PL` reader - Receiver Preamble Length"] pub struct RX_PL_R(crate::FieldReader<u8, u8>); impl RX_PL_R { pub(crate) fn new(bits: u8) -> Self { RX_PL_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for RX_PL_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `RX_PL` writer - Receiver Preamble Length"] pub struct RX_PL_W<'a> { w: &'a mut W, } impl<'a> RX_PL_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 16)) | ((value as u32 & 0x0f) << 16); self.w } } #[doc = "Receiver Preamble Pattern detected\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum RX_PP_A { #[doc = "0: The preamble is composed of '1's"] ALL_ONE = 0, #[doc = "1: The preamble is composed of '0's"] ALL_ZERO = 1, #[doc = "2: The preamble is composed of '01's"] ZERO_ONE = 2, #[doc = "3: The preamble is composed of '10's"] ONE_ZERO = 3, } impl From<RX_PP_A> for u8 { #[inline(always)] fn from(variant: RX_PP_A) -> Self { variant as _ } } #[doc = "Field `RX_PP` reader - Receiver Preamble Pattern detected"] pub struct RX_PP_R(crate::FieldReader<u8, RX_PP_A>); impl RX_PP_R { pub(crate) fn new(bits: u8) -> Self { RX_PP_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RX_PP_A { match self.bits { 0 => RX_PP_A::ALL_ONE, 1 => RX_PP_A::ALL_ZERO, 2 => RX_PP_A::ZERO_ONE, 3 => RX_PP_A::ONE_ZERO, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `ALL_ONE`"] #[inline(always)] pub fn is_all_one(&self) -> bool { **self == RX_PP_A::ALL_ONE } #[doc = "Checks if the value of the field is `ALL_ZERO`"] #[inline(always)] pub fn is_all_zero(&self) -> bool { **self == RX_PP_A::ALL_ZERO } #[doc = "Checks if the value of the field is `ZERO_ONE`"] #[inline(always)] pub fn is_zero_one(&self) -> bool { **self == RX_PP_A::ZERO_ONE } #[doc = "Checks if the value of the field is `ONE_ZERO`"] #[inline(always)] pub fn is_one_zero(&self) -> bool { **self == RX_PP_A::ONE_ZERO } } impl core::ops::Deref for RX_PP_R { type Target = crate::FieldReader<u8, RX_PP_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `RX_PP` writer - Receiver Preamble Pattern detected"] pub struct RX_PP_W<'a> { w: &'a mut W, } impl<'a> RX_PP_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RX_PP_A) -> &'a mut W { self.bits(variant.into()) } #[doc = "The preamble is composed of '1's"] #[inline(always)] pub fn all_one(self) -> &'a mut W { self.variant(RX_PP_A::ALL_ONE) } #[doc = "The preamble is composed of '0's"] #[inline(always)] pub fn all_zero(self) -> &'a mut W { self.variant(RX_PP_A::ALL_ZERO) } #[doc = "The preamble is composed of '01's"] #[inline(always)] pub fn zero_one(self) -> &'a mut W { self.variant(RX_PP_A::ZERO_ONE) } #[doc = "The preamble is composed of '10's"] #[inline(always)] pub fn one_zero(self) -> &'a mut W { self.variant(RX_PP_A::ONE_ZERO) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 24)) | ((value as u32 & 0x03) << 24); self.w } } #[doc = "Field `RX_MPOL` reader - Receiver Manchester Polarity"] pub struct RX_MPOL_R(crate::FieldReader<bool, bool>); impl RX_MPOL_R { pub(crate) fn new(bits: bool) -> Self { RX_MPOL_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for RX_MPOL_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `RX_MPOL` writer - Receiver Manchester Polarity"] pub struct RX_MPOL_W<'a> { w: &'a mut W, } impl<'a> RX_MPOL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | ((value as u32 & 0x01) << 28); self.w } } #[doc = "Field `ONE` reader - Must Be Set to 1"] pub struct ONE_R(crate::FieldReader<bool, bool>); impl ONE_R { pub(crate) fn new(bits: bool) -> Self { ONE_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for ONE_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `ONE` writer - Must Be Set to 1"] pub struct ONE_W<'a> { w: &'a mut W, } impl<'a> ONE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 29)) | ((value as u32 & 0x01) << 29); self.w } } #[doc = "Field `DRIFT` reader - Drift Compensation"] pub struct DRIFT_R(crate::FieldReader<bool, bool>); impl DRIFT_R { pub(crate) fn new(bits: bool) -> Self { DRIFT_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DRIFT_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DRIFT` writer - Drift Compensation"] pub struct DRIFT_W<'a> { w: &'a mut W, } impl<'a> DRIFT_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 30)) | ((value as u32 & 0x01) << 30); self.w } } impl R { #[doc = "Bits 0:3 - Transmitter Preamble Length"] #[inline(always)] pub fn tx_pl(&self) -> TX_PL_R { TX_PL_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 8:9 - Transmitter Preamble Pattern"] #[inline(always)] pub fn tx_pp(&self) -> TX_PP_R { TX_PP_R::new(((self.bits >> 8) & 0x03) as u8) } #[doc = "Bit 12 - Transmitter Manchester Polarity"] #[inline(always)] pub fn tx_mpol(&self) -> TX_MPOL_R { TX_MPOL_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bits 16:19 - Receiver Preamble Length"] #[inline(always)] pub fn rx_pl(&self) -> RX_PL_R { RX_PL_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 24:25 - Receiver Preamble Pattern detected"] #[inline(always)] pub fn rx_pp(&self) -> RX_PP_R { RX_PP_R::new(((self.bits >> 24) & 0x03) as u8) } #[doc = "Bit 28 - Receiver Manchester Polarity"] #[inline(always)] pub fn rx_mpol(&self) -> RX_MPOL_R { RX_MPOL_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - Must Be Set to 1"] #[inline(always)] pub fn one(&self) -> ONE_R { ONE_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - Drift Compensation"] #[inline(always)] pub fn drift(&self) -> DRIFT_R { DRIFT_R::new(((self.bits >> 30) & 0x01) != 0) } } impl W { #[doc = "Bits 0:3 - Transmitter Preamble Length"] #[inline(always)] pub fn tx_pl(&mut self) -> TX_PL_W { TX_PL_W { w: self } } #[doc = "Bits 8:9 - Transmitter Preamble Pattern"] #[inline(always)] pub fn tx_pp(&mut self) -> TX_PP_W { TX_PP_W { w: self } } #[doc = "Bit 12 - Transmitter Manchester Polarity"] #[inline(always)] pub fn tx_mpol(&mut self) -> TX_MPOL_W { TX_MPOL_W { w: self } } #[doc = "Bits 16:19 - Receiver Preamble Length"] #[inline(always)] pub fn rx_pl(&mut self) -> RX_PL_W { RX_PL_W { w: self } } #[doc = "Bits 24:25 - Receiver Preamble Pattern detected"] #[inline(always)] pub fn rx_pp(&mut self) -> RX_PP_W { RX_PP_W { w: self } } #[doc = "Bit 28 - Receiver Manchester Polarity"] #[inline(always)] pub fn rx_mpol(&mut self) -> RX_MPOL_W { RX_MPOL_W { w: self } } #[doc = "Bit 29 - Must Be Set to 1"] #[inline(always)] pub fn one(&mut self) -> ONE_W { ONE_W { w: self } } #[doc = "Bit 30 - Drift Compensation"] #[inline(always)] pub fn drift(&mut self) -> DRIFT_W { DRIFT_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 = "Manchester Encoder Decoder Register\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 [man](index.html) module"] pub struct MAN_SPEC; impl crate::RegisterSpec for MAN_SPEC { type Ux = u32; } #[doc = "`read()` method returns [man::R](R) reader structure"] impl crate::Readable for MAN_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [man::W](W) writer structure"] impl crate::Writable for MAN_SPEC { type Writer = W; } #[doc = "`reset()` method sets MAN to value 0xb001_1004"] impl crate::Resettable for MAN_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0xb001_1004 } }
29.719266
419
0.566092
f926fef065ea6c228fed4cc17a473a5ac0e7930f
1,826
// Copyright 2016 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. //! constant evaluation on the HIR and code to validate patterns/matches //! //! # Note //! //! This API is completely unstable and subject to change. #![crate_name = "rustc_const_eval"] #![unstable(feature = "rustc_private", issue = "27812")] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "https://doc.rust-lang.org/favicon.ico", html_root_url = "https://doc.rust-lang.org/nightly/")] #![feature(dotdot_in_tuple_patterns)] #![feature(rustc_private)] #![feature(staged_api)] #![feature(rustc_diagnostic_macros)] #![feature(slice_patterns)] #![feature(question_mark)] #![feature(box_patterns)] #![feature(box_syntax)] #[macro_use] extern crate syntax; #[macro_use] extern crate log; #[macro_use] extern crate rustc; extern crate rustc_back; extern crate rustc_const_math; extern crate rustc_errors; extern crate graphviz; extern crate syntax_pos; extern crate serialize as rustc_serialize; // used by deriving // NB: This module needs to be declared first so diagnostics are // registered before they are used. pub mod diagnostics; mod eval; pub mod check_match; pub use eval::*; // Build the diagnostics array at the end so that the metadata includes error use sites. __build_diagnostic_array! { librustc_const_eval, DIAGNOSTICS }
33.2
88
0.743702
898d500607f257879ee840f44c6ff901c0d72591
3,764
use std::io::Write; use log::debug; use pulldown_cmark::Event; pub(crate) trait Highlighter { /// # Highlight a Code Block /// /// Returns a list of the events to emit to the TOC to represent the block. fn hl_codeblock<'a>(&self, name: &str, block: &str) -> Vec<Event>; /// # Write any HTML header required for highlighting on this page. fn write_header(&self, out: &mut dyn Write) -> std::io::Result<()>; } pub use js_hl::HighlightJsHighlighter; #[cfg(feature = "syntect-hl")] pub use syntect_hl::SyntectHighlighter; #[cfg(feature = "syntect-hl")] mod syntect_hl { use std::io::Write; use log::debug; use pulldown_cmark::Event; use syntect::{ self, highlighting::ThemeSet, html::highlighted_html_for_string, parsing::SyntaxSet, }; use super::Highlighter; pub struct SyntectHighlighter { ss: SyntaxSet, ts: ThemeSet, } impl SyntectHighlighter { /// # Create a New Highlighter pub fn new() -> Self { let ss = SyntaxSet::load_defaults_newlines(); let ts = ThemeSet::load_defaults(); SyntectHighlighter { ss, ts } } } impl Highlighter for SyntectHighlighter { fn hl_codeblock(&self, name: &str, block: &str) -> Vec<Event> { let syntax = self .ss .find_syntax_by_extension(&name) .or_else(|| self.ss.find_syntax_by_name(&name)) .unwrap_or_else(|| self.ss.find_syntax_plain_text()); debug!("source name: {0}, syntax: {1:?}", name, syntax.name); let theme = &self.ts.themes["InspiredGitHub"]; let highlighted = highlighted_html_for_string(&block, &self.ss, &syntax, theme); vec![Event::Html(highlighted.into())] } fn write_header(&self, _out: &mut dyn Write) -> std::io::Result<()> { Ok(()) } } } mod js_hl { use std::io::Write; use pulldown_cmark::{CowStr, Event, Tag}; use super::Highlighter; pub struct HighlightJsHighlighter(); impl HighlightJsHighlighter { pub const fn new() -> Self { HighlightJsHighlighter() } } impl Highlighter for HighlightJsHighlighter { fn hl_codeblock(&self, name: &str, block: &str) -> Vec<Event> { let name: CowStr = String::from(name).into(); vec![ Event::Start(Tag::CodeBlock(name.clone())), Event::Text(String::from(block).into()), Event::End(Tag::CodeBlock(name)), ] } fn write_header(&self, out: &mut dyn Write) -> std::io::Result<()> { const HLJS_VERSION: &str = "10.5.0"; write!( out, r#" <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/{0}/styles/default.min.css"> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/{0}/highlight.min.js"></script> <script>hljs.initHighlightingOnLoad();</script>"#, HLJS_VERSION ) } } } #[cfg(feature = "syntect-hl")] lazy_static! { static ref GLOBAL_SYNTECT_HL: SyntectHighlighter = SyntectHighlighter::new(); } /// # Get the Active Highlighter /// /// Returns a reference to a shared highlighter. pub(crate) fn get_hilighter() -> &'static dyn Highlighter { static GLOBAL_JS_HL: HighlightJsHighlighter = HighlightJsHighlighter::new(); #[cfg(feature = "syntect-hl")] if std::env::var("DOCKET_FORCE_JS_HL").is_err() { debug!("Using syntect for highlighting."); return &*GLOBAL_SYNTECT_HL; } debug!("Using Javascript highlighter."); &GLOBAL_JS_HL }
30.354839
106
0.581296
33ef96d1f0dc3dd8eb0522645ef8370f3c3f7f3c
4,217
use build::mac::{parse_mac, is_path}; use syntax::ast; use syntax::ext::base::ExtCtxt; use syntax::ptr::P; /* use build::Builder; use syntax::visit; impl<'a, 'b: 'a> Builder<'a, 'b> { pub fn contains_transition<E: ContainsTransition>(&self, expr: E) -> bool { expr.contains_transition(self.is_inside_loop()) } } pub trait ContainsTransition { fn contains_transition(&self, inside_loop: bool) -> bool; } impl<'a> ContainsTransition for &'a P<ast::Block> { fn contains_transition(&self, inside_loop: bool) -> bool { (**self).contains_transition(inside_loop) } } impl ContainsTransition for ast::Block { fn contains_transition(&self, inside_loop: bool) -> bool { let mut visitor = ContainsTransitionVisitor::new(inside_loop); visit::Visitor::visit_block(&mut visitor, self); visitor.contains_transition } } impl ContainsTransition for ast::Stmt { fn contains_transition(&self, inside_loop: bool) -> bool { let mut visitor = ContainsTransitionVisitor::new(inside_loop); visit::Visitor::visit_stmt(&mut visitor, self); visitor.contains_transition } } impl<'a> ContainsTransition for &'a P<ast::Expr> { fn contains_transition(&self, inside_loop: bool) -> bool { (**self).contains_transition(inside_loop) } } impl ContainsTransition for ast::Expr { fn contains_transition(&self, inside_loop: bool) -> bool { let mut visitor = ContainsTransitionVisitor::new(inside_loop); visit::Visitor::visit_expr(&mut visitor, self); visitor.contains_transition } } impl ContainsTransition for ast::Mac { fn contains_transition(&self, _inside_loop: bool) -> bool { is_transition_path(&self.node.path) } } struct ContainsTransitionVisitor { inside_loop: bool, contains_transition: bool, } impl ContainsTransitionVisitor { fn new(inside_loop: bool) -> Self { ContainsTransitionVisitor { inside_loop: inside_loop, contains_transition: false, } } } impl visit::Visitor for ContainsTransitionVisitor { fn visit_stmt(&mut self, stmt: &ast::Stmt) { match stmt.node { StmtKind::Mac(ref mac) if is_transition_path(&(*mac).0.node.path) => { self.contains_transition = true; } _ => { visit::walk_stmt(self, stmt) } } } fn visit_expr(&mut self, expr: &ast::Expr) { match expr.node { ExprKind::Ret(Some(_)) | ExprKind::Assign(..) => { self.contains_transition = true; } ExprKind::Break(_, _) if self.inside_loop => { self.contains_transition = true; } ExprKind::Continue(_) if self.inside_loop => { self.contains_transition = true; } ExprKind::Mac(ref mac) if mac.contains_transition(self.inside_loop) => { self.contains_transition = true; } _ => { visit::walk_expr(self, expr) } } } fn visit_mac(&mut self, _mac: &ast::Mac) { } } */ pub enum Transition { Yield(P<ast::Expr>), Await(P<ast::Expr>), Suspend(P<ast::Expr>), } pub fn parse_mac_transition(cx: &ExtCtxt, mac: &ast::Mac) -> Option<Transition> { if is_yield_path(&mac.node.path) { Some(Transition::Yield(parse_mac(cx, mac))) } else if is_await_path(&mac.node.path) { Some(Transition::Await(parse_mac(cx, mac))) } else if is_suspend_path(&mac.node.path) { Some(Transition::Suspend(parse_mac(cx, mac))) } else { None } } /* fn is_transition_path(path: &ast::Path) -> bool { if path.global { return false; } is_yield_path(path) || is_await_path(path) || is_suspend_path(path) || is_moved_path(path) } */ fn is_yield_path(path: &ast::Path) -> bool { is_path(path, "yield_") } fn is_await_path(path: &ast::Path) -> bool { is_path(path, "await") } fn is_suspend_path(path: &ast::Path) -> bool { is_path(path, "suspend") } /* fn is_moved_path(path: &ast::Path) -> bool { is_path(path, "moved") } */
25.871166
84
0.606118
87eb3f6224004ecc653545e4ba3ff03f567e68df
333
// run-pass // Test that unsafe impl for Sync/Send can be provided for extern types. #![feature(extern_types)] extern "C" { type A; } unsafe impl Sync for A {} unsafe impl Send for A {} fn assert_sync<T: ?Sized + Sync>() {} fn assert_send<T: ?Sized + Send>() {} fn main() { assert_sync::<A>(); assert_send::<A>(); }
16.65
72
0.618619
18a0e527970667dec465185a73cdf2c0d36f3dba
7,056
#[derive(Debug, PartialEq)] #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] enum Enum { First, Second, Third, } #[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))] pub struct WidgetGallery { enabled: bool, boolean: bool, radio: Enum, scalar: f32, string: String, color: egui::Color32, } impl Default for WidgetGallery { fn default() -> Self { Self { enabled: true, boolean: false, radio: Enum::First, scalar: 42.0, string: Default::default(), color: egui::Color32::LIGHT_BLUE.linear_multiply(0.5), } } } impl super::Demo for WidgetGallery { fn name(&self) -> &'static str { "🗄 Widget Gallery" } fn show(&mut self, ctx: &egui::CtxRef, open: &mut bool) { egui::Window::new(self.name()) .open(open) .resizable(false) .show(ctx, |ui| { use super::View; self.ui(ui); }); } } impl super::View for WidgetGallery { fn ui(&mut self, ui: &mut egui::Ui) { self.gallery(ui); ui.separator(); ui.vertical_centered(|ui| { ui.checkbox(&mut self.enabled, "Interactive") .on_hover_text("Convenient way to inspect how the widgets look when disabled."); }); ui.separator(); ui.vertical_centered(|ui| { let tooltip_text = "The full egui documentation.\nYou can also click the different widgets names in the left column."; ui.hyperlink("https://docs.rs/egui/").on_hover_text(tooltip_text); ui.add(crate::__egui_github_link_file!( "Source code of the widget gallery" )); }); } } impl WidgetGallery { fn gallery(&mut self, ui: &mut egui::Ui) { egui::Grid::new("my_grid") .striped(true) .spacing([40.0, 4.0]) .show(ui, |ui| { self.gallery_grid_contents(ui); }); } fn gallery_grid_contents(&mut self, ui: &mut egui::Ui) { let Self { enabled, boolean, radio, scalar, string, color, } = self; ui.set_enabled(*enabled); ui.add(doc_link_label("Label", "label,heading")); ui.label("Welcome to the widget gallery!"); ui.end_row(); ui.add(doc_link_label("Hyperlink", "Hyperlink")); use egui::special_emojis::GITHUB; ui.hyperlink_to( format!("{} egui home page", GITHUB), "https://github.com/emilk/egui", ); ui.end_row(); ui.add(doc_link_label("TextEdit", "TextEdit,text_edit")); ui.add(egui::TextEdit::singleline(string).hint_text("Write something here")); ui.end_row(); ui.add(doc_link_label("Button", "button")); if ui.button("Click me!").clicked() { *boolean = !*boolean; } ui.end_row(); ui.add(doc_link_label("Checkbox", "checkbox")); ui.checkbox(boolean, "Checkbox"); ui.end_row(); ui.add(doc_link_label("RadioButton", "radio")); ui.horizontal(|ui| { ui.radio_value(radio, Enum::First, "First"); ui.radio_value(radio, Enum::Second, "Second"); ui.radio_value(radio, Enum::Third, "Third"); }); ui.end_row(); ui.add(doc_link_label( "SelectableLabel", "selectable_value,SelectableLabel", )); ui.horizontal(|ui| { ui.selectable_value(radio, Enum::First, "First"); ui.selectable_value(radio, Enum::Second, "Second"); ui.selectable_value(radio, Enum::Third, "Third"); }); ui.end_row(); ui.add(doc_link_label("Combo box", "combo_box")); egui::combo_box_with_label(ui, "Take your pick", format!("{:?}", radio), |ui| { ui.selectable_value(radio, Enum::First, "First"); ui.selectable_value(radio, Enum::Second, "Second"); ui.selectable_value(radio, Enum::Third, "Third"); }); ui.end_row(); ui.add(doc_link_label("Slider", "Slider")); ui.add(egui::Slider::f32(scalar, 0.0..=360.0).suffix("°")); ui.end_row(); ui.add(doc_link_label("DragValue", "DragValue")); ui.add(egui::DragValue::f32(scalar).speed(1.0)); ui.end_row(); ui.add(doc_link_label("Color picker", "color_edit")); ui.color_edit_button_srgba(color); ui.end_row(); ui.add(doc_link_label("Image", "Image")); ui.image(egui::TextureId::Egui, [24.0, 16.0]) .on_hover_text("The egui font texture was the convenient choice to show here."); ui.end_row(); ui.add(doc_link_label("ImageButton", "ImageButton")); if ui .add(egui::ImageButton::new(egui::TextureId::Egui, [24.0, 16.0])) .on_hover_text("The egui font texture was the convenient choice to show here.") .clicked() { *boolean = !*boolean; } ui.end_row(); ui.add(doc_link_label("Separator", "separator")); ui.separator(); ui.end_row(); ui.add(doc_link_label("CollapsingHeader", "collapsing")); ui.collapsing("Click to see what is hidden!", |ui| { ui.horizontal_wrapped_for_text(egui::TextStyle::Body, |ui| { ui.label( "Not much, as it turns out - but here is a gold star for you for checking:", ); ui.colored_label(egui::Color32::GOLD, "☆"); }); }); ui.end_row(); ui.add(doc_link_label("Plot", "plot")); ui.add(example_plot()); ui.end_row(); ui.hyperlink_to( "Custom widget:", super::toggle_switch::url_to_file_source_code(), ); ui.add(super::toggle_switch::toggle(boolean)).on_hover_text( "It's easy to create your own widgets!\n\ This toggle switch is just 15 lines of code.", ); ui.end_row(); } } fn example_plot() -> egui::plot::Plot { let n = 512; let curve = egui::plot::Curve::from_values_iter((0..=n).map(|i| { use std::f64::consts::TAU; let x = egui::remap(i as f64, 0.0..=(n as f64), -TAU..=TAU); egui::plot::Value::new(x, x.sin()) })); egui::plot::Plot::default() .curve(curve) .height(32.0) .data_aspect(1.0) } fn doc_link_label<'a>(title: &'a str, search_term: &'a str) -> impl egui::Widget + 'a { let label = format!("{}:", title); let url = format!("https://docs.rs/egui?search={}", search_term); move |ui: &mut egui::Ui| { ui.hyperlink_to(label, url).on_hover_ui(|ui| { ui.horizontal_wrapped(|ui| { ui.label("Search egui docs for"); ui.code(search_term); }); }) } }
30.812227
130
0.536706
645ce8bb150626cd42b891f39b35ea671ad8cd61
57,960
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// <p>Gets Suite Definition Configuration.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct SuiteDefinitionConfiguration { /// <p>Gets Suite Definition Configuration name.</p> pub suite_definition_name: std::option::Option<std::string::String>, /// <p>Gets the devices configured.</p> pub devices: std::option::Option<std::vec::Vec<crate::model::DeviceUnderTest>>, /// <p>Gets the tests intended for qualification in a suite.</p> pub intended_for_qualification: bool, /// <p>Gets test suite root group.</p> pub root_group: std::option::Option<std::string::String>, /// <p>Gets the device permission ARN.</p> pub device_permission_role_arn: std::option::Option<std::string::String>, } impl SuiteDefinitionConfiguration { /// <p>Gets Suite Definition Configuration name.</p> pub fn suite_definition_name(&self) -> std::option::Option<&str> { self.suite_definition_name.as_deref() } /// <p>Gets the devices configured.</p> pub fn devices(&self) -> std::option::Option<&[crate::model::DeviceUnderTest]> { self.devices.as_deref() } /// <p>Gets the tests intended for qualification in a suite.</p> pub fn intended_for_qualification(&self) -> bool { self.intended_for_qualification } /// <p>Gets test suite root group.</p> pub fn root_group(&self) -> std::option::Option<&str> { self.root_group.as_deref() } /// <p>Gets the device permission ARN.</p> pub fn device_permission_role_arn(&self) -> std::option::Option<&str> { self.device_permission_role_arn.as_deref() } } impl std::fmt::Debug for SuiteDefinitionConfiguration { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("SuiteDefinitionConfiguration"); formatter.field("suite_definition_name", &self.suite_definition_name); formatter.field("devices", &self.devices); formatter.field( "intended_for_qualification", &self.intended_for_qualification, ); formatter.field("root_group", &self.root_group); formatter.field( "device_permission_role_arn", &self.device_permission_role_arn, ); formatter.finish() } } /// See [`SuiteDefinitionConfiguration`](crate::model::SuiteDefinitionConfiguration) pub mod suite_definition_configuration { /// A builder for [`SuiteDefinitionConfiguration`](crate::model::SuiteDefinitionConfiguration) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) suite_definition_name: std::option::Option<std::string::String>, pub(crate) devices: std::option::Option<std::vec::Vec<crate::model::DeviceUnderTest>>, pub(crate) intended_for_qualification: std::option::Option<bool>, pub(crate) root_group: std::option::Option<std::string::String>, pub(crate) device_permission_role_arn: std::option::Option<std::string::String>, } impl Builder { /// <p>Gets Suite Definition Configuration name.</p> pub fn suite_definition_name(mut self, input: impl Into<std::string::String>) -> Self { self.suite_definition_name = Some(input.into()); self } /// <p>Gets Suite Definition Configuration name.</p> pub fn set_suite_definition_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.suite_definition_name = input; self } /// Appends an item to `devices`. /// /// To override the contents of this collection use [`set_devices`](Self::set_devices). /// /// <p>Gets the devices configured.</p> pub fn devices(mut self, input: impl Into<crate::model::DeviceUnderTest>) -> Self { let mut v = self.devices.unwrap_or_default(); v.push(input.into()); self.devices = Some(v); self } /// <p>Gets the devices configured.</p> pub fn set_devices( mut self, input: std::option::Option<std::vec::Vec<crate::model::DeviceUnderTest>>, ) -> Self { self.devices = input; self } /// <p>Gets the tests intended for qualification in a suite.</p> pub fn intended_for_qualification(mut self, input: bool) -> Self { self.intended_for_qualification = Some(input); self } /// <p>Gets the tests intended for qualification in a suite.</p> pub fn set_intended_for_qualification(mut self, input: std::option::Option<bool>) -> Self { self.intended_for_qualification = input; self } /// <p>Gets test suite root group.</p> pub fn root_group(mut self, input: impl Into<std::string::String>) -> Self { self.root_group = Some(input.into()); self } /// <p>Gets test suite root group.</p> pub fn set_root_group(mut self, input: std::option::Option<std::string::String>) -> Self { self.root_group = input; self } /// <p>Gets the device permission ARN.</p> pub fn device_permission_role_arn(mut self, input: impl Into<std::string::String>) -> Self { self.device_permission_role_arn = Some(input.into()); self } /// <p>Gets the device permission ARN.</p> pub fn set_device_permission_role_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.device_permission_role_arn = input; self } /// Consumes the builder and constructs a [`SuiteDefinitionConfiguration`](crate::model::SuiteDefinitionConfiguration) pub fn build(self) -> crate::model::SuiteDefinitionConfiguration { crate::model::SuiteDefinitionConfiguration { suite_definition_name: self.suite_definition_name, devices: self.devices, intended_for_qualification: self.intended_for_qualification.unwrap_or_default(), root_group: self.root_group, device_permission_role_arn: self.device_permission_role_arn, } } } } impl SuiteDefinitionConfiguration { /// Creates a new builder-style object to manufacture [`SuiteDefinitionConfiguration`](crate::model::SuiteDefinitionConfiguration) pub fn builder() -> crate::model::suite_definition_configuration::Builder { crate::model::suite_definition_configuration::Builder::default() } } /// <p>Information of a test device. A thing ARN or a certificate ARN is required.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeviceUnderTest { /// <p>Lists devices thing ARN.</p> pub thing_arn: std::option::Option<std::string::String>, /// <p>Lists devices certificate ARN.</p> pub certificate_arn: std::option::Option<std::string::String>, } impl DeviceUnderTest { /// <p>Lists devices thing ARN.</p> pub fn thing_arn(&self) -> std::option::Option<&str> { self.thing_arn.as_deref() } /// <p>Lists devices certificate ARN.</p> pub fn certificate_arn(&self) -> std::option::Option<&str> { self.certificate_arn.as_deref() } } impl std::fmt::Debug for DeviceUnderTest { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeviceUnderTest"); formatter.field("thing_arn", &self.thing_arn); formatter.field("certificate_arn", &self.certificate_arn); formatter.finish() } } /// See [`DeviceUnderTest`](crate::model::DeviceUnderTest) pub mod device_under_test { /// A builder for [`DeviceUnderTest`](crate::model::DeviceUnderTest) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) thing_arn: std::option::Option<std::string::String>, pub(crate) certificate_arn: std::option::Option<std::string::String>, } impl Builder { /// <p>Lists devices thing ARN.</p> pub fn thing_arn(mut self, input: impl Into<std::string::String>) -> Self { self.thing_arn = Some(input.into()); self } /// <p>Lists devices thing ARN.</p> pub fn set_thing_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.thing_arn = input; self } /// <p>Lists devices certificate ARN.</p> pub fn certificate_arn(mut self, input: impl Into<std::string::String>) -> Self { self.certificate_arn = Some(input.into()); self } /// <p>Lists devices certificate ARN.</p> pub fn set_certificate_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.certificate_arn = input; self } /// Consumes the builder and constructs a [`DeviceUnderTest`](crate::model::DeviceUnderTest) pub fn build(self) -> crate::model::DeviceUnderTest { crate::model::DeviceUnderTest { thing_arn: self.thing_arn, certificate_arn: self.certificate_arn, } } } } impl DeviceUnderTest { /// Creates a new builder-style object to manufacture [`DeviceUnderTest`](crate::model::DeviceUnderTest) pub fn builder() -> crate::model::device_under_test::Builder { crate::model::device_under_test::Builder::default() } } /// <p>Gets suite run configuration.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct SuiteRunConfiguration { /// <p>Gets the primary device for suite run.</p> pub primary_device: std::option::Option<crate::model::DeviceUnderTest>, /// <p>Gets test case list.</p> pub selected_test_list: std::option::Option<std::vec::Vec<std::string::String>>, /// <p>TRUE if multiple test suites run in parallel.</p> pub parallel_run: bool, } impl SuiteRunConfiguration { /// <p>Gets the primary device for suite run.</p> pub fn primary_device(&self) -> std::option::Option<&crate::model::DeviceUnderTest> { self.primary_device.as_ref() } /// <p>Gets test case list.</p> pub fn selected_test_list(&self) -> std::option::Option<&[std::string::String]> { self.selected_test_list.as_deref() } /// <p>TRUE if multiple test suites run in parallel.</p> pub fn parallel_run(&self) -> bool { self.parallel_run } } impl std::fmt::Debug for SuiteRunConfiguration { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("SuiteRunConfiguration"); formatter.field("primary_device", &self.primary_device); formatter.field("selected_test_list", &self.selected_test_list); formatter.field("parallel_run", &self.parallel_run); formatter.finish() } } /// See [`SuiteRunConfiguration`](crate::model::SuiteRunConfiguration) pub mod suite_run_configuration { /// A builder for [`SuiteRunConfiguration`](crate::model::SuiteRunConfiguration) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) primary_device: std::option::Option<crate::model::DeviceUnderTest>, pub(crate) selected_test_list: std::option::Option<std::vec::Vec<std::string::String>>, pub(crate) parallel_run: std::option::Option<bool>, } impl Builder { /// <p>Gets the primary device for suite run.</p> pub fn primary_device(mut self, input: crate::model::DeviceUnderTest) -> Self { self.primary_device = Some(input); self } /// <p>Gets the primary device for suite run.</p> pub fn set_primary_device( mut self, input: std::option::Option<crate::model::DeviceUnderTest>, ) -> Self { self.primary_device = input; self } /// Appends an item to `selected_test_list`. /// /// To override the contents of this collection use [`set_selected_test_list`](Self::set_selected_test_list). /// /// <p>Gets test case list.</p> pub fn selected_test_list(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.selected_test_list.unwrap_or_default(); v.push(input.into()); self.selected_test_list = Some(v); self } /// <p>Gets test case list.</p> pub fn set_selected_test_list( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.selected_test_list = input; self } /// <p>TRUE if multiple test suites run in parallel.</p> pub fn parallel_run(mut self, input: bool) -> Self { self.parallel_run = Some(input); self } /// <p>TRUE if multiple test suites run in parallel.</p> pub fn set_parallel_run(mut self, input: std::option::Option<bool>) -> Self { self.parallel_run = input; self } /// Consumes the builder and constructs a [`SuiteRunConfiguration`](crate::model::SuiteRunConfiguration) pub fn build(self) -> crate::model::SuiteRunConfiguration { crate::model::SuiteRunConfiguration { primary_device: self.primary_device, selected_test_list: self.selected_test_list, parallel_run: self.parallel_run.unwrap_or_default(), } } } } impl SuiteRunConfiguration { /// Creates a new builder-style object to manufacture [`SuiteRunConfiguration`](crate::model::SuiteRunConfiguration) pub fn builder() -> crate::model::suite_run_configuration::Builder { crate::model::suite_run_configuration::Builder::default() } } /// <p>Information about the suite run.</p> /// <p>Requires permission to access the <a href="https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiot.html#awsiot-actions-as-permissions">SuiteRunInformation</a> action.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct SuiteRunInformation { /// <p>Suite definition ID of the suite run.</p> pub suite_definition_id: std::option::Option<std::string::String>, /// <p>Suite definition version of the suite run.</p> pub suite_definition_version: std::option::Option<std::string::String>, /// <p>Suite definition name of the suite run.</p> pub suite_definition_name: std::option::Option<std::string::String>, /// <p>Suite run ID of the suite run.</p> pub suite_run_id: std::option::Option<std::string::String>, /// <p>Date (in Unix epoch time) when the suite run was created.</p> pub created_at: std::option::Option<aws_smithy_types::DateTime>, /// <p>Date (in Unix epoch time) when the suite run was started.</p> pub started_at: std::option::Option<aws_smithy_types::DateTime>, /// <p>Date (in Unix epoch time) when the suite run ended.</p> pub end_at: std::option::Option<aws_smithy_types::DateTime>, /// <p>Status of the suite run.</p> pub status: std::option::Option<crate::model::SuiteRunStatus>, /// <p>Number of test cases that passed in the suite run.</p> pub passed: i32, /// <p>Number of test cases that failed in the suite run.</p> pub failed: i32, } impl SuiteRunInformation { /// <p>Suite definition ID of the suite run.</p> pub fn suite_definition_id(&self) -> std::option::Option<&str> { self.suite_definition_id.as_deref() } /// <p>Suite definition version of the suite run.</p> pub fn suite_definition_version(&self) -> std::option::Option<&str> { self.suite_definition_version.as_deref() } /// <p>Suite definition name of the suite run.</p> pub fn suite_definition_name(&self) -> std::option::Option<&str> { self.suite_definition_name.as_deref() } /// <p>Suite run ID of the suite run.</p> pub fn suite_run_id(&self) -> std::option::Option<&str> { self.suite_run_id.as_deref() } /// <p>Date (in Unix epoch time) when the suite run was created.</p> pub fn created_at(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.created_at.as_ref() } /// <p>Date (in Unix epoch time) when the suite run was started.</p> pub fn started_at(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.started_at.as_ref() } /// <p>Date (in Unix epoch time) when the suite run ended.</p> pub fn end_at(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.end_at.as_ref() } /// <p>Status of the suite run.</p> pub fn status(&self) -> std::option::Option<&crate::model::SuiteRunStatus> { self.status.as_ref() } /// <p>Number of test cases that passed in the suite run.</p> pub fn passed(&self) -> i32 { self.passed } /// <p>Number of test cases that failed in the suite run.</p> pub fn failed(&self) -> i32 { self.failed } } impl std::fmt::Debug for SuiteRunInformation { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("SuiteRunInformation"); formatter.field("suite_definition_id", &self.suite_definition_id); formatter.field("suite_definition_version", &self.suite_definition_version); formatter.field("suite_definition_name", &self.suite_definition_name); formatter.field("suite_run_id", &self.suite_run_id); formatter.field("created_at", &self.created_at); formatter.field("started_at", &self.started_at); formatter.field("end_at", &self.end_at); formatter.field("status", &self.status); formatter.field("passed", &self.passed); formatter.field("failed", &self.failed); formatter.finish() } } /// See [`SuiteRunInformation`](crate::model::SuiteRunInformation) pub mod suite_run_information { /// A builder for [`SuiteRunInformation`](crate::model::SuiteRunInformation) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) suite_definition_id: std::option::Option<std::string::String>, pub(crate) suite_definition_version: std::option::Option<std::string::String>, pub(crate) suite_definition_name: std::option::Option<std::string::String>, pub(crate) suite_run_id: std::option::Option<std::string::String>, pub(crate) created_at: std::option::Option<aws_smithy_types::DateTime>, pub(crate) started_at: std::option::Option<aws_smithy_types::DateTime>, pub(crate) end_at: std::option::Option<aws_smithy_types::DateTime>, pub(crate) status: std::option::Option<crate::model::SuiteRunStatus>, pub(crate) passed: std::option::Option<i32>, pub(crate) failed: std::option::Option<i32>, } impl Builder { /// <p>Suite definition ID of the suite run.</p> pub fn suite_definition_id(mut self, input: impl Into<std::string::String>) -> Self { self.suite_definition_id = Some(input.into()); self } /// <p>Suite definition ID of the suite run.</p> pub fn set_suite_definition_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.suite_definition_id = input; self } /// <p>Suite definition version of the suite run.</p> pub fn suite_definition_version(mut self, input: impl Into<std::string::String>) -> Self { self.suite_definition_version = Some(input.into()); self } /// <p>Suite definition version of the suite run.</p> pub fn set_suite_definition_version( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.suite_definition_version = input; self } /// <p>Suite definition name of the suite run.</p> pub fn suite_definition_name(mut self, input: impl Into<std::string::String>) -> Self { self.suite_definition_name = Some(input.into()); self } /// <p>Suite definition name of the suite run.</p> pub fn set_suite_definition_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.suite_definition_name = input; self } /// <p>Suite run ID of the suite run.</p> pub fn suite_run_id(mut self, input: impl Into<std::string::String>) -> Self { self.suite_run_id = Some(input.into()); self } /// <p>Suite run ID of the suite run.</p> pub fn set_suite_run_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.suite_run_id = input; self } /// <p>Date (in Unix epoch time) when the suite run was created.</p> pub fn created_at(mut self, input: aws_smithy_types::DateTime) -> Self { self.created_at = Some(input); self } /// <p>Date (in Unix epoch time) when the suite run was created.</p> pub fn set_created_at( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.created_at = input; self } /// <p>Date (in Unix epoch time) when the suite run was started.</p> pub fn started_at(mut self, input: aws_smithy_types::DateTime) -> Self { self.started_at = Some(input); self } /// <p>Date (in Unix epoch time) when the suite run was started.</p> pub fn set_started_at( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.started_at = input; self } /// <p>Date (in Unix epoch time) when the suite run ended.</p> pub fn end_at(mut self, input: aws_smithy_types::DateTime) -> Self { self.end_at = Some(input); self } /// <p>Date (in Unix epoch time) when the suite run ended.</p> pub fn set_end_at( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.end_at = input; self } /// <p>Status of the suite run.</p> pub fn status(mut self, input: crate::model::SuiteRunStatus) -> Self { self.status = Some(input); self } /// <p>Status of the suite run.</p> pub fn set_status( mut self, input: std::option::Option<crate::model::SuiteRunStatus>, ) -> Self { self.status = input; self } /// <p>Number of test cases that passed in the suite run.</p> pub fn passed(mut self, input: i32) -> Self { self.passed = Some(input); self } /// <p>Number of test cases that passed in the suite run.</p> pub fn set_passed(mut self, input: std::option::Option<i32>) -> Self { self.passed = input; self } /// <p>Number of test cases that failed in the suite run.</p> pub fn failed(mut self, input: i32) -> Self { self.failed = Some(input); self } /// <p>Number of test cases that failed in the suite run.</p> pub fn set_failed(mut self, input: std::option::Option<i32>) -> Self { self.failed = input; self } /// Consumes the builder and constructs a [`SuiteRunInformation`](crate::model::SuiteRunInformation) pub fn build(self) -> crate::model::SuiteRunInformation { crate::model::SuiteRunInformation { suite_definition_id: self.suite_definition_id, suite_definition_version: self.suite_definition_version, suite_definition_name: self.suite_definition_name, suite_run_id: self.suite_run_id, created_at: self.created_at, started_at: self.started_at, end_at: self.end_at, status: self.status, passed: self.passed.unwrap_or_default(), failed: self.failed.unwrap_or_default(), } } } } impl SuiteRunInformation { /// Creates a new builder-style object to manufacture [`SuiteRunInformation`](crate::model::SuiteRunInformation) pub fn builder() -> crate::model::suite_run_information::Builder { crate::model::suite_run_information::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum SuiteRunStatus { #[allow(missing_docs)] // documentation missing in model Canceled, #[allow(missing_docs)] // documentation missing in model Error, #[allow(missing_docs)] // documentation missing in model Fail, #[allow(missing_docs)] // documentation missing in model Pass, #[allow(missing_docs)] // documentation missing in model PassWithWarnings, #[allow(missing_docs)] // documentation missing in model Pending, #[allow(missing_docs)] // documentation missing in model Running, #[allow(missing_docs)] // documentation missing in model Stopped, #[allow(missing_docs)] // documentation missing in model Stopping, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for SuiteRunStatus { fn from(s: &str) -> Self { match s { "CANCELED" => SuiteRunStatus::Canceled, "ERROR" => SuiteRunStatus::Error, "FAIL" => SuiteRunStatus::Fail, "PASS" => SuiteRunStatus::Pass, "PASS_WITH_WARNINGS" => SuiteRunStatus::PassWithWarnings, "PENDING" => SuiteRunStatus::Pending, "RUNNING" => SuiteRunStatus::Running, "STOPPED" => SuiteRunStatus::Stopped, "STOPPING" => SuiteRunStatus::Stopping, other => SuiteRunStatus::Unknown(other.to_owned()), } } } impl std::str::FromStr for SuiteRunStatus { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(SuiteRunStatus::from(s)) } } impl SuiteRunStatus { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { SuiteRunStatus::Canceled => "CANCELED", SuiteRunStatus::Error => "ERROR", SuiteRunStatus::Fail => "FAIL", SuiteRunStatus::Pass => "PASS", SuiteRunStatus::PassWithWarnings => "PASS_WITH_WARNINGS", SuiteRunStatus::Pending => "PENDING", SuiteRunStatus::Running => "RUNNING", SuiteRunStatus::Stopped => "STOPPED", SuiteRunStatus::Stopping => "STOPPING", SuiteRunStatus::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &[ "CANCELED", "ERROR", "FAIL", "PASS", "PASS_WITH_WARNINGS", "PENDING", "RUNNING", "STOPPED", "STOPPING", ] } } impl AsRef<str> for SuiteRunStatus { fn as_ref(&self) -> &str { self.as_str() } } /// <p>Information about the suite definition.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct SuiteDefinitionInformation { /// <p>Suite definition ID of the test suite.</p> pub suite_definition_id: std::option::Option<std::string::String>, /// <p>Suite name of the test suite.</p> pub suite_definition_name: std::option::Option<std::string::String>, /// <p>Specifies the devices that are under test for the test suite.</p> pub default_devices: std::option::Option<std::vec::Vec<crate::model::DeviceUnderTest>>, /// <p>Specifies if the test suite is intended for qualification.</p> pub intended_for_qualification: bool, /// <p>Date (in Unix epoch time) when the test suite was created.</p> pub created_at: std::option::Option<aws_smithy_types::DateTime>, } impl SuiteDefinitionInformation { /// <p>Suite definition ID of the test suite.</p> pub fn suite_definition_id(&self) -> std::option::Option<&str> { self.suite_definition_id.as_deref() } /// <p>Suite name of the test suite.</p> pub fn suite_definition_name(&self) -> std::option::Option<&str> { self.suite_definition_name.as_deref() } /// <p>Specifies the devices that are under test for the test suite.</p> pub fn default_devices(&self) -> std::option::Option<&[crate::model::DeviceUnderTest]> { self.default_devices.as_deref() } /// <p>Specifies if the test suite is intended for qualification.</p> pub fn intended_for_qualification(&self) -> bool { self.intended_for_qualification } /// <p>Date (in Unix epoch time) when the test suite was created.</p> pub fn created_at(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.created_at.as_ref() } } impl std::fmt::Debug for SuiteDefinitionInformation { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("SuiteDefinitionInformation"); formatter.field("suite_definition_id", &self.suite_definition_id); formatter.field("suite_definition_name", &self.suite_definition_name); formatter.field("default_devices", &self.default_devices); formatter.field( "intended_for_qualification", &self.intended_for_qualification, ); formatter.field("created_at", &self.created_at); formatter.finish() } } /// See [`SuiteDefinitionInformation`](crate::model::SuiteDefinitionInformation) pub mod suite_definition_information { /// A builder for [`SuiteDefinitionInformation`](crate::model::SuiteDefinitionInformation) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) suite_definition_id: std::option::Option<std::string::String>, pub(crate) suite_definition_name: std::option::Option<std::string::String>, pub(crate) default_devices: std::option::Option<std::vec::Vec<crate::model::DeviceUnderTest>>, pub(crate) intended_for_qualification: std::option::Option<bool>, pub(crate) created_at: std::option::Option<aws_smithy_types::DateTime>, } impl Builder { /// <p>Suite definition ID of the test suite.</p> pub fn suite_definition_id(mut self, input: impl Into<std::string::String>) -> Self { self.suite_definition_id = Some(input.into()); self } /// <p>Suite definition ID of the test suite.</p> pub fn set_suite_definition_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.suite_definition_id = input; self } /// <p>Suite name of the test suite.</p> pub fn suite_definition_name(mut self, input: impl Into<std::string::String>) -> Self { self.suite_definition_name = Some(input.into()); self } /// <p>Suite name of the test suite.</p> pub fn set_suite_definition_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.suite_definition_name = input; self } /// Appends an item to `default_devices`. /// /// To override the contents of this collection use [`set_default_devices`](Self::set_default_devices). /// /// <p>Specifies the devices that are under test for the test suite.</p> pub fn default_devices(mut self, input: impl Into<crate::model::DeviceUnderTest>) -> Self { let mut v = self.default_devices.unwrap_or_default(); v.push(input.into()); self.default_devices = Some(v); self } /// <p>Specifies the devices that are under test for the test suite.</p> pub fn set_default_devices( mut self, input: std::option::Option<std::vec::Vec<crate::model::DeviceUnderTest>>, ) -> Self { self.default_devices = input; self } /// <p>Specifies if the test suite is intended for qualification.</p> pub fn intended_for_qualification(mut self, input: bool) -> Self { self.intended_for_qualification = Some(input); self } /// <p>Specifies if the test suite is intended for qualification.</p> pub fn set_intended_for_qualification(mut self, input: std::option::Option<bool>) -> Self { self.intended_for_qualification = input; self } /// <p>Date (in Unix epoch time) when the test suite was created.</p> pub fn created_at(mut self, input: aws_smithy_types::DateTime) -> Self { self.created_at = Some(input); self } /// <p>Date (in Unix epoch time) when the test suite was created.</p> pub fn set_created_at( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.created_at = input; self } /// Consumes the builder and constructs a [`SuiteDefinitionInformation`](crate::model::SuiteDefinitionInformation) pub fn build(self) -> crate::model::SuiteDefinitionInformation { crate::model::SuiteDefinitionInformation { suite_definition_id: self.suite_definition_id, suite_definition_name: self.suite_definition_name, default_devices: self.default_devices, intended_for_qualification: self.intended_for_qualification.unwrap_or_default(), created_at: self.created_at, } } } } impl SuiteDefinitionInformation { /// Creates a new builder-style object to manufacture [`SuiteDefinitionInformation`](crate::model::SuiteDefinitionInformation) pub fn builder() -> crate::model::suite_definition_information::Builder { crate::model::suite_definition_information::Builder::default() } } /// <p>Show each group result.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct TestResult { /// <p>Show each group of test results.</p> pub groups: std::option::Option<std::vec::Vec<crate::model::GroupResult>>, } impl TestResult { /// <p>Show each group of test results.</p> pub fn groups(&self) -> std::option::Option<&[crate::model::GroupResult]> { self.groups.as_deref() } } impl std::fmt::Debug for TestResult { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("TestResult"); formatter.field("groups", &self.groups); formatter.finish() } } /// See [`TestResult`](crate::model::TestResult) pub mod test_result { /// A builder for [`TestResult`](crate::model::TestResult) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) groups: std::option::Option<std::vec::Vec<crate::model::GroupResult>>, } impl Builder { /// Appends an item to `groups`. /// /// To override the contents of this collection use [`set_groups`](Self::set_groups). /// /// <p>Show each group of test results.</p> pub fn groups(mut self, input: impl Into<crate::model::GroupResult>) -> Self { let mut v = self.groups.unwrap_or_default(); v.push(input.into()); self.groups = Some(v); self } /// <p>Show each group of test results.</p> pub fn set_groups( mut self, input: std::option::Option<std::vec::Vec<crate::model::GroupResult>>, ) -> Self { self.groups = input; self } /// Consumes the builder and constructs a [`TestResult`](crate::model::TestResult) pub fn build(self) -> crate::model::TestResult { crate::model::TestResult { groups: self.groups, } } } } impl TestResult { /// Creates a new builder-style object to manufacture [`TestResult`](crate::model::TestResult) pub fn builder() -> crate::model::test_result::Builder { crate::model::test_result::Builder::default() } } /// <p>Show Group Result.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct GroupResult { /// <p>Group result ID.</p> pub group_id: std::option::Option<std::string::String>, /// <p>Group Result Name.</p> pub group_name: std::option::Option<std::string::String>, /// <p>Tests under Group Result.</p> pub tests: std::option::Option<std::vec::Vec<crate::model::TestCaseRun>>, } impl GroupResult { /// <p>Group result ID.</p> pub fn group_id(&self) -> std::option::Option<&str> { self.group_id.as_deref() } /// <p>Group Result Name.</p> pub fn group_name(&self) -> std::option::Option<&str> { self.group_name.as_deref() } /// <p>Tests under Group Result.</p> pub fn tests(&self) -> std::option::Option<&[crate::model::TestCaseRun]> { self.tests.as_deref() } } impl std::fmt::Debug for GroupResult { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("GroupResult"); formatter.field("group_id", &self.group_id); formatter.field("group_name", &self.group_name); formatter.field("tests", &self.tests); formatter.finish() } } /// See [`GroupResult`](crate::model::GroupResult) pub mod group_result { /// A builder for [`GroupResult`](crate::model::GroupResult) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) group_id: std::option::Option<std::string::String>, pub(crate) group_name: std::option::Option<std::string::String>, pub(crate) tests: std::option::Option<std::vec::Vec<crate::model::TestCaseRun>>, } impl Builder { /// <p>Group result ID.</p> pub fn group_id(mut self, input: impl Into<std::string::String>) -> Self { self.group_id = Some(input.into()); self } /// <p>Group result ID.</p> pub fn set_group_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.group_id = input; self } /// <p>Group Result Name.</p> pub fn group_name(mut self, input: impl Into<std::string::String>) -> Self { self.group_name = Some(input.into()); self } /// <p>Group Result Name.</p> pub fn set_group_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.group_name = input; self } /// Appends an item to `tests`. /// /// To override the contents of this collection use [`set_tests`](Self::set_tests). /// /// <p>Tests under Group Result.</p> pub fn tests(mut self, input: impl Into<crate::model::TestCaseRun>) -> Self { let mut v = self.tests.unwrap_or_default(); v.push(input.into()); self.tests = Some(v); self } /// <p>Tests under Group Result.</p> pub fn set_tests( mut self, input: std::option::Option<std::vec::Vec<crate::model::TestCaseRun>>, ) -> Self { self.tests = input; self } /// Consumes the builder and constructs a [`GroupResult`](crate::model::GroupResult) pub fn build(self) -> crate::model::GroupResult { crate::model::GroupResult { group_id: self.group_id, group_name: self.group_name, tests: self.tests, } } } } impl GroupResult { /// Creates a new builder-style object to manufacture [`GroupResult`](crate::model::GroupResult) pub fn builder() -> crate::model::group_result::Builder { crate::model::group_result::Builder::default() } } /// <p>Provides the test case run.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct TestCaseRun { /// <p>Provides the test case run ID.</p> pub test_case_run_id: std::option::Option<std::string::String>, /// <p>Provides the test case run definition ID.</p> pub test_case_definition_id: std::option::Option<std::string::String>, /// <p>Provides the test case run definition name.</p> pub test_case_definition_name: std::option::Option<std::string::String>, /// <p>Provides the test case run status. Status is one of the following:</p> /// <ul> /// <li> /// <p> /// <code>PASS</code>: Test passed.</p> /// </li> /// <li> /// <p> /// <code>FAIL</code>: Test failed.</p> /// </li> /// <li> /// <p> /// <code>PENDING</code>: Test has not started running but is scheduled.</p> /// </li> /// <li> /// <p> /// <code>RUNNING</code>: Test is running.</p> /// </li> /// <li> /// <p> /// <code>STOPPING</code>: Test is performing cleanup steps. You will see this status only if you stop a suite run.</p> /// </li> /// <li> /// <p> /// <code>STOPPED</code> Test is stopped. You will see this status only if you stop a suite run.</p> /// </li> /// <li> /// <p> /// <code>PASS_WITH_WARNINGS</code>: Test passed with warnings.</p> /// </li> /// <li> /// <p> /// <code>ERORR</code>: Test faced an error when running due to an internal issue.</p> /// </li> /// </ul> pub status: std::option::Option<crate::model::Status>, /// <p>Provides test case run start time.</p> pub start_time: std::option::Option<aws_smithy_types::DateTime>, /// <p>Provides test case run end time.</p> pub end_time: std::option::Option<aws_smithy_types::DateTime>, /// <p>Provides test case run log URL.</p> pub log_url: std::option::Option<std::string::String>, /// <p>Provides test case run warnings.</p> pub warnings: std::option::Option<std::string::String>, /// <p>Provides test case run failure result.</p> pub failure: std::option::Option<std::string::String>, } impl TestCaseRun { /// <p>Provides the test case run ID.</p> pub fn test_case_run_id(&self) -> std::option::Option<&str> { self.test_case_run_id.as_deref() } /// <p>Provides the test case run definition ID.</p> pub fn test_case_definition_id(&self) -> std::option::Option<&str> { self.test_case_definition_id.as_deref() } /// <p>Provides the test case run definition name.</p> pub fn test_case_definition_name(&self) -> std::option::Option<&str> { self.test_case_definition_name.as_deref() } /// <p>Provides the test case run status. Status is one of the following:</p> /// <ul> /// <li> /// <p> /// <code>PASS</code>: Test passed.</p> /// </li> /// <li> /// <p> /// <code>FAIL</code>: Test failed.</p> /// </li> /// <li> /// <p> /// <code>PENDING</code>: Test has not started running but is scheduled.</p> /// </li> /// <li> /// <p> /// <code>RUNNING</code>: Test is running.</p> /// </li> /// <li> /// <p> /// <code>STOPPING</code>: Test is performing cleanup steps. You will see this status only if you stop a suite run.</p> /// </li> /// <li> /// <p> /// <code>STOPPED</code> Test is stopped. You will see this status only if you stop a suite run.</p> /// </li> /// <li> /// <p> /// <code>PASS_WITH_WARNINGS</code>: Test passed with warnings.</p> /// </li> /// <li> /// <p> /// <code>ERORR</code>: Test faced an error when running due to an internal issue.</p> /// </li> /// </ul> pub fn status(&self) -> std::option::Option<&crate::model::Status> { self.status.as_ref() } /// <p>Provides test case run start time.</p> pub fn start_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.start_time.as_ref() } /// <p>Provides test case run end time.</p> pub fn end_time(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.end_time.as_ref() } /// <p>Provides test case run log URL.</p> pub fn log_url(&self) -> std::option::Option<&str> { self.log_url.as_deref() } /// <p>Provides test case run warnings.</p> pub fn warnings(&self) -> std::option::Option<&str> { self.warnings.as_deref() } /// <p>Provides test case run failure result.</p> pub fn failure(&self) -> std::option::Option<&str> { self.failure.as_deref() } } impl std::fmt::Debug for TestCaseRun { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("TestCaseRun"); formatter.field("test_case_run_id", &self.test_case_run_id); formatter.field("test_case_definition_id", &self.test_case_definition_id); formatter.field("test_case_definition_name", &self.test_case_definition_name); formatter.field("status", &self.status); formatter.field("start_time", &self.start_time); formatter.field("end_time", &self.end_time); formatter.field("log_url", &self.log_url); formatter.field("warnings", &self.warnings); formatter.field("failure", &self.failure); formatter.finish() } } /// See [`TestCaseRun`](crate::model::TestCaseRun) pub mod test_case_run { /// A builder for [`TestCaseRun`](crate::model::TestCaseRun) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) test_case_run_id: std::option::Option<std::string::String>, pub(crate) test_case_definition_id: std::option::Option<std::string::String>, pub(crate) test_case_definition_name: std::option::Option<std::string::String>, pub(crate) status: std::option::Option<crate::model::Status>, pub(crate) start_time: std::option::Option<aws_smithy_types::DateTime>, pub(crate) end_time: std::option::Option<aws_smithy_types::DateTime>, pub(crate) log_url: std::option::Option<std::string::String>, pub(crate) warnings: std::option::Option<std::string::String>, pub(crate) failure: std::option::Option<std::string::String>, } impl Builder { /// <p>Provides the test case run ID.</p> pub fn test_case_run_id(mut self, input: impl Into<std::string::String>) -> Self { self.test_case_run_id = Some(input.into()); self } /// <p>Provides the test case run ID.</p> pub fn set_test_case_run_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.test_case_run_id = input; self } /// <p>Provides the test case run definition ID.</p> pub fn test_case_definition_id(mut self, input: impl Into<std::string::String>) -> Self { self.test_case_definition_id = Some(input.into()); self } /// <p>Provides the test case run definition ID.</p> pub fn set_test_case_definition_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.test_case_definition_id = input; self } /// <p>Provides the test case run definition name.</p> pub fn test_case_definition_name(mut self, input: impl Into<std::string::String>) -> Self { self.test_case_definition_name = Some(input.into()); self } /// <p>Provides the test case run definition name.</p> pub fn set_test_case_definition_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.test_case_definition_name = input; self } /// <p>Provides the test case run status. Status is one of the following:</p> /// <ul> /// <li> /// <p> /// <code>PASS</code>: Test passed.</p> /// </li> /// <li> /// <p> /// <code>FAIL</code>: Test failed.</p> /// </li> /// <li> /// <p> /// <code>PENDING</code>: Test has not started running but is scheduled.</p> /// </li> /// <li> /// <p> /// <code>RUNNING</code>: Test is running.</p> /// </li> /// <li> /// <p> /// <code>STOPPING</code>: Test is performing cleanup steps. You will see this status only if you stop a suite run.</p> /// </li> /// <li> /// <p> /// <code>STOPPED</code> Test is stopped. You will see this status only if you stop a suite run.</p> /// </li> /// <li> /// <p> /// <code>PASS_WITH_WARNINGS</code>: Test passed with warnings.</p> /// </li> /// <li> /// <p> /// <code>ERORR</code>: Test faced an error when running due to an internal issue.</p> /// </li> /// </ul> pub fn status(mut self, input: crate::model::Status) -> Self { self.status = Some(input); self } /// <p>Provides the test case run status. Status is one of the following:</p> /// <ul> /// <li> /// <p> /// <code>PASS</code>: Test passed.</p> /// </li> /// <li> /// <p> /// <code>FAIL</code>: Test failed.</p> /// </li> /// <li> /// <p> /// <code>PENDING</code>: Test has not started running but is scheduled.</p> /// </li> /// <li> /// <p> /// <code>RUNNING</code>: Test is running.</p> /// </li> /// <li> /// <p> /// <code>STOPPING</code>: Test is performing cleanup steps. You will see this status only if you stop a suite run.</p> /// </li> /// <li> /// <p> /// <code>STOPPED</code> Test is stopped. You will see this status only if you stop a suite run.</p> /// </li> /// <li> /// <p> /// <code>PASS_WITH_WARNINGS</code>: Test passed with warnings.</p> /// </li> /// <li> /// <p> /// <code>ERORR</code>: Test faced an error when running due to an internal issue.</p> /// </li> /// </ul> pub fn set_status(mut self, input: std::option::Option<crate::model::Status>) -> Self { self.status = input; self } /// <p>Provides test case run start time.</p> pub fn start_time(mut self, input: aws_smithy_types::DateTime) -> Self { self.start_time = Some(input); self } /// <p>Provides test case run start time.</p> pub fn set_start_time( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.start_time = input; self } /// <p>Provides test case run end time.</p> pub fn end_time(mut self, input: aws_smithy_types::DateTime) -> Self { self.end_time = Some(input); self } /// <p>Provides test case run end time.</p> pub fn set_end_time( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.end_time = input; self } /// <p>Provides test case run log URL.</p> pub fn log_url(mut self, input: impl Into<std::string::String>) -> Self { self.log_url = Some(input.into()); self } /// <p>Provides test case run log URL.</p> pub fn set_log_url(mut self, input: std::option::Option<std::string::String>) -> Self { self.log_url = input; self } /// <p>Provides test case run warnings.</p> pub fn warnings(mut self, input: impl Into<std::string::String>) -> Self { self.warnings = Some(input.into()); self } /// <p>Provides test case run warnings.</p> pub fn set_warnings(mut self, input: std::option::Option<std::string::String>) -> Self { self.warnings = input; self } /// <p>Provides test case run failure result.</p> pub fn failure(mut self, input: impl Into<std::string::String>) -> Self { self.failure = Some(input.into()); self } /// <p>Provides test case run failure result.</p> pub fn set_failure(mut self, input: std::option::Option<std::string::String>) -> Self { self.failure = input; self } /// Consumes the builder and constructs a [`TestCaseRun`](crate::model::TestCaseRun) pub fn build(self) -> crate::model::TestCaseRun { crate::model::TestCaseRun { test_case_run_id: self.test_case_run_id, test_case_definition_id: self.test_case_definition_id, test_case_definition_name: self.test_case_definition_name, status: self.status, start_time: self.start_time, end_time: self.end_time, log_url: self.log_url, warnings: self.warnings, failure: self.failure, } } } } impl TestCaseRun { /// Creates a new builder-style object to manufacture [`TestCaseRun`](crate::model::TestCaseRun) pub fn builder() -> crate::model::test_case_run::Builder { crate::model::test_case_run::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum Status { #[allow(missing_docs)] // documentation missing in model Canceled, #[allow(missing_docs)] // documentation missing in model Error, #[allow(missing_docs)] // documentation missing in model Fail, #[allow(missing_docs)] // documentation missing in model Pass, #[allow(missing_docs)] // documentation missing in model PassWithWarnings, #[allow(missing_docs)] // documentation missing in model Pending, #[allow(missing_docs)] // documentation missing in model Running, #[allow(missing_docs)] // documentation missing in model Stopped, #[allow(missing_docs)] // documentation missing in model Stopping, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for Status { fn from(s: &str) -> Self { match s { "CANCELED" => Status::Canceled, "ERROR" => Status::Error, "FAIL" => Status::Fail, "PASS" => Status::Pass, "PASS_WITH_WARNINGS" => Status::PassWithWarnings, "PENDING" => Status::Pending, "RUNNING" => Status::Running, "STOPPED" => Status::Stopped, "STOPPING" => Status::Stopping, other => Status::Unknown(other.to_owned()), } } } impl std::str::FromStr for Status { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(Status::from(s)) } } impl Status { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { Status::Canceled => "CANCELED", Status::Error => "ERROR", Status::Fail => "FAIL", Status::Pass => "PASS", Status::PassWithWarnings => "PASS_WITH_WARNINGS", Status::Pending => "PENDING", Status::Running => "RUNNING", Status::Stopped => "STOPPED", Status::Stopping => "STOPPING", Status::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &[ "CANCELED", "ERROR", "FAIL", "PASS", "PASS_WITH_WARNINGS", "PENDING", "RUNNING", "STOPPED", "STOPPING", ] } } impl AsRef<str> for Status { fn as_ref(&self) -> &str { self.as_str() } }
40.305981
200
0.591132
7550345d7e787355cb346ee63817a52611352d75
5,089
use libc::FILE; use std::ffi::c_void; use std::ffi::CString; use std::os::raw::c_char; use std::os::raw::c_double; use std::os::raw::c_float; use std::os::raw::c_int; use std::os::raw::c_long; #[repr(C)] pub struct TinyTiffFile { file: *mut FILE, last_ifd_offset_field: u32, last_start_pos: c_long, last_ifd_data_address: u32, last_if_count: u16, last_header: *mut u8, last_header_size: c_int, pos: u32, width: u32, height: u32, bits_per_sample: u16, description_offset: u32, description_size_offset: u32, frames: u64, byte_order: u8, } #[link(name = "tinytiff")] extern "C" { fn TinyTIFFWriter_open( filename: *const c_char, bits_per_sample: u16, width: u32, height: u32, ) -> *mut TinyTiffFile; fn TinyTIFFWriter_getMaxDescriptionTextSize(tiff: *mut TinyTiffFile) -> c_int; fn TinyTIFFWriter_close(tiff: *mut TinyTiffFile, image_description: *const c_char); fn TinyTIFFWriter_writeImageVoid(tiff: *mut TinyTiffFile, image_data: *mut c_void); fn TinyTIFFWriter_writeImageFloat(tiff: *mut TinyTiffFile, image_data: *mut c_float); fn TinyTIFFWriter_writeImageDouble(tiff: *mut TinyTiffFile, image_data: *mut c_double); } /// create a new tiff file pub fn open( filename: &str, bits_per_sample: u16, width: u32, height: u32, ) -> Result<*mut TinyTiffFile, String> { let cfilename = CString::new(filename).unwrap(); let pntr = cfilename.as_ptr(); let tiff = unsafe { TinyTIFFWriter_open(pntr, bits_per_sample, width, height) }; match tiff.is_null() { false => Ok(tiff), true => Err(format!("Could not open file: {}", String::from(filename))), } } /// get max size for image description pub fn max_description_text_size(tiff: *mut TinyTiffFile) -> u32 { let size = unsafe { TinyTIFFWriter_getMaxDescriptionTextSize(tiff) }; size as u32 } /// close the tiff and write image description to first frame pub fn close(tiff: *mut TinyTiffFile, image_description: &str) { let image_description = CString::new(image_description).unwrap(); let image_description = image_description.as_ptr(); unsafe { TinyTIFFWriter_close(tiff, image_description) }; } /// writes row-major image data to a tiff file pub fn write_image_void<T>(tiff: *mut TinyTiffFile, buffer: &Vec<T>) { let pntr = buffer.as_ptr() as *mut c_void; unsafe { TinyTIFFWriter_writeImageVoid(tiff, pntr) }; } /// writes row-major image data to a tiff file pub fn write_image_float<T>(tiff: *mut TinyTiffFile, buffer: &Vec<T>) { let pntr = buffer.as_ptr() as *mut c_float; unsafe { TinyTIFFWriter_writeImageFloat(tiff, pntr) }; } /// writes row-major image data to a tiff file pub fn write_image_double<T>(tiff: *mut TinyTiffFile, buffer: &Vec<T>) { let pntr = buffer.as_ptr() as *mut c_double; unsafe { TinyTIFFWriter_writeImageDouble(tiff, pntr) }; } #[cfg(test)] mod tests { use super::*; //#[test] //fn can_open() { //let _tiff = open("./tests/test_data/cell2.tif", 8, 100, 100).unwrap(); //} #[test] #[should_panic] fn open_bad_file_panics() { let _tiff = open("./does/not/exist.tif", 8, 100, 100).unwrap(); } //#[test] //fn can_max_description_text_size() { //let tiff = open("./tests/test_data/cell2.tif", 8, 100, 100).unwrap(); //let size = max_description_text_size(tiff); //assert_ne!(size, 0); //} #[test] fn can_write_image_void8_and_close() { let bits: u16 = 8; let width: u32 = 100; let height: u32 = 100; let size = width * height; let buffer: Vec<u8> = vec![42u8; size as usize]; let tiff = open("./tests/test_data/test8.tif", bits, width, height).unwrap(); write_image_void(tiff, &buffer); close(tiff, "test 8bit"); } #[test] fn can_write_image_void16_and_close() { let bits: u16 = 16; let width: u32 = 100; let height: u32 = 100; let size = width * height; let buffer: Vec<u16> = vec![42u16; size as usize]; let tiff = open("./tests/test_data/test16.tif", bits, width, height).unwrap(); write_image_void(tiff, &buffer); close(tiff, "test 16bit"); } #[test] fn can_write_image_float32_and_close() { let bits: u16 = 32; let width: u32 = 100; let height: u32 = 100; let size = width * height; let buffer: Vec<f32> = vec![42f32; size as usize]; let tiff = open("./tests/test_data/test32.tif", bits, width, height).unwrap(); write_image_float(tiff, &buffer); close(tiff, "test 32bit"); } #[test] fn can_write_image_double64_and_close() { let bits: u16 = 64; let width: u32 = 100; let height: u32 = 100; let size = width * height; let buffer: Vec<f64> = vec![42f64; size as usize]; let tiff = open("./tests/test_data/test64.tif", bits, width, height).unwrap(); write_image_double(tiff, &buffer); close(tiff, "test 64bit"); } }
31.608696
91
0.635488
0314f109a7c8129a7184b936f8900300ca03d86d
547
// 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. fn main() { return.is_failure //~ ERROR no field `is_failure` on type `!` }
39.071429
68
0.727605
e846109b0ece962e9a47df7e6d729885bb5afa8e
2,951
//! Holds enums that don't clearly belong to any specific moudle use synthizer_sys::*; mod transmutable { /// Marker trait so that we can internally make sure that it's safe to /// transmute enums in generic contexts. Guarantees that the enum came from /// us, and is backed by an i32. pub unsafe trait I32TransmutableEnum { /// Work around no from/into impls on enums with repr(i32). fn as_i32(&self) -> i32; // And work around transmuting the other way. unsafe fn from_i32(val: i32) -> Self; } } pub(crate) use transmutable::*; macro_rules! impl_transmutable { ($t: ty) => { unsafe impl I32TransmutableEnum for $t { fn as_i32(&self) -> i32 { *self as i32 } unsafe fn from_i32(val: i32) -> Self { std::mem::transmute(val) } } }; } #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] #[repr(i32)] pub enum PannerStrategy { Delegate = SYZ_PANNER_STRATEGY_DELEGATE as i32, Hrtf = SYZ_PANNER_STRATEGY_HRTF as i32, Stereo = SYZ_PANNER_STRATEGY_STEREO as i32, } impl_transmutable!(PannerStrategy); #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] #[repr(i32)] pub enum DistanceModel { None = SYZ_DISTANCE_MODEL_NONE as i32, Linear = SYZ_DISTANCE_MODEL_LINEAR as i32, Exponential = SYZ_DISTANCE_MODEL_EXPONENTIAL as i32, Inverse = SYZ_DISTANCE_MODEL_INVERSE as i32, } impl_transmutable!(DistanceModel); #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Hash)] #[repr(i32)] pub enum NoiseType { Uniform = SYZ_NOISE_TYPE_UNIFORM as i32, Vm = SYZ_NOISE_TYPE_VM as i32, FilteredBrown = SYZ_NOISE_TYPE_FILTERED_BROWN as i32, } impl_transmutable!(NoiseType); #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)] #[repr(i32)] pub enum ObjectType { AutomationBatch = SYZ_OTYPE_AUTOMATION_BATCH as i32, Context = SYZ_OTYPE_CONTEXT as i32, Buffer = SYZ_OTYPE_BUFFER as i32, BufferGenerator = SYZ_OTYPE_BUFFER_GENERATOR as i32, FastSineBankGenerator = SYZ_OTYPE_FAST_SINE_BANK_GENERATOR as i32, StreamingGenerator = SYZ_OTYPE_STREAMING_GENERATOR as i32, NoiseGenerator = SYZ_OTYPE_NOISE_GENERATOR as i32, DirectSource = SYZ_OTYPE_DIRECT_SOURCE as i32, AngularPannedSource = SYZ_OTYPE_ANGULAR_PANNED_SOURCE as i32, ScalarPannedSource = SYZ_OTYPE_SCALAR_PANNED_SOURCE as i32, Source3D = SYZ_OTYPE_SOURCE_3D as i32, GlobalEcho = SYZ_OTYPE_GLOBAL_ECHO as i32, GlobalFdnReverb = SYZ_OTYPE_GLOBAL_FDN_REVERB as i32, StreamHandle = SYZ_OTYPE_STREAM_HANDLE as i32, } impl_transmutable!(ObjectType); #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)] #[repr(i32)] pub enum InterpolationType { None = SYZ_INTERPOLATION_TYPE_NONE as i32, Linear = SYZ_INTERPOLATION_TYPE_LINEAR as i32, } impl_transmutable!(InterpolationType);
32.076087
80
0.709251
2359b8292f89e8c31d28e41a4077241ed950d5a8
11,976
extern crate x264_sys as ffi; use std::mem; use ffi::x264::*; use std::ptr::null; use std::os::raw::c_int; use std::ffi::CString; pub struct Picture { pic: x264_picture_t, plane_size: [usize; 3], native: bool, } struct ColorspaceScale { w: [usize; 3], h: [usize; 3], } fn scale_from_csp(csp: u32) -> ColorspaceScale { if csp == X264_CSP_I420 { ColorspaceScale { w: [256 * 1, 256 / 2, 256 / 2], h: [256 * 1, 256 / 2, 256 / 2], } } else if csp == X264_CSP_YV12 { ColorspaceScale { w: [256 * 1, 256 / 2, 256 / 2], h: [256 * 1, 256 / 2, 256 / 2], } } else if csp == X264_CSP_NV12 { ColorspaceScale { w: [256 * 1, 256 * 1, 0], h: [256 * 1, 256 / 2, 0], } } else if csp == X264_CSP_NV21 { ColorspaceScale { w: [256 * 1, 256 * 1, 0], h: [256 * 1, 256 / 2, 0], } } else if csp == X264_CSP_I422 { ColorspaceScale { w: [256 * 1, 256 / 2, 256 / 2], h: [256 * 1, 256 * 1, 256 * 1], } } else if csp == X264_CSP_YV16 { ColorspaceScale { w: [256 * 1, 256 / 2, 256 / 2], h: [256 * 1, 256 * 1, 256 * 1], } } else if csp == X264_CSP_NV16 { ColorspaceScale { w: [256 * 1, 256 * 1, 0], h: [256 * 1, 256 * 1, 0], } /* } else if csp == X264_CSP_YUYV { ColorspaceScale { w: [256 * 2, 0, 0], h: [256 * 1, 0, 0], } } else if csp == X264_CSP_UYVY { ColorspaceScale { w: [256 * 2, 0, 0], h: [256 * 1, 0, 0], } */ } else if csp == X264_CSP_I444 { ColorspaceScale { w: [256 * 1, 256 * 1, 256 * 1], h: [256 * 1, 256 * 1, 256 * 1], } } else if csp == X264_CSP_YV24 { ColorspaceScale { w: [256 * 1, 256 * 1, 256 * 1], h: [256 * 1, 256 * 1, 256 * 1], } } else if csp == X264_CSP_BGR { ColorspaceScale { w: [256 * 3, 0, 0], h: [256 * 1, 0, 0], } } else if csp == X264_CSP_BGRA { ColorspaceScale { w: [256 * 4, 0, 0], h: [256 * 1, 0, 0], } } else if csp == X264_CSP_RGB { ColorspaceScale { w: [256 * 3, 0, 0], h: [256 * 1, 0, 0], } } else { unreachable!() } } impl Picture { /* pub fn new() -> Picture { let mut pic = unsafe { mem::uninitialized() }; unsafe { x264_picture_init(&mut pic as *mut x264_picture_t) }; Picture { pic: pic } } */ pub fn from_param(param: &Param) -> Result<Picture, &'static str> { let mut pic: mem::MaybeUninit<x264_picture_t> = mem::MaybeUninit::uninit(); let ret = unsafe { x264_picture_alloc(pic.as_mut_ptr(), param.par.i_csp, param.par.i_width, param.par.i_height) }; if ret < 0 { Err("Allocation Failure") } else { let pic = unsafe{ pic.assume_init() }; let scale = scale_from_csp(param.par.i_csp as u32 & X264_CSP_MASK as u32); let bytes = 1 + (param.par.i_csp as u32 & X264_CSP_HIGH_DEPTH as u32); let mut plane_size = [0; 3]; for i in 0..pic.img.i_plane as usize { plane_size[i] = param.par.i_width as usize * scale.w[i] / 256 * bytes as usize * param.par.i_height as usize * scale.h[i] / 256; } Ok(Picture { pic: pic, plane_size: plane_size, native: true, }) } } pub fn as_slice<'a>(&'a self, plane: usize) -> Result<&'a [u8], &'static str> { if plane > self.pic.img.i_plane as usize { Err("Invalid Argument") } else { let size = self.plane_size[plane]; Ok(unsafe { std::slice::from_raw_parts(self.pic.img.plane[plane], size) }) } } pub fn as_mut_slice<'a>(&'a mut self, plane: usize) -> Result<&'a mut [u8], &'static str> { if plane > self.pic.img.i_plane as usize { Err("Invalid Argument") } else { let size = self.plane_size[plane]; Ok(unsafe { std::slice::from_raw_parts_mut(self.pic.img.plane[plane], size) }) } } pub fn set_timestamp(mut self, pts: i64) -> Picture { self.pic.i_pts = pts; self } } impl Drop for Picture { fn drop(&mut self) { if self.native { unsafe { x264_picture_clean(&mut self.pic as *mut x264_picture_t) }; } } } // TODO: Provide a builder API instead? pub struct Param { par: x264_param_t, } impl Param { pub fn new() -> Param { let mut par: mem::MaybeUninit<x264_param_t> = mem::MaybeUninit::uninit(); let par = unsafe { x264_param_default(par.as_mut_ptr()); par.assume_init() }; Param { par: par } } pub fn default_preset<'a, 'b, Oa, Ob>(preset: Oa, tune: Ob) -> Result<Param, &'static str> where Oa: Into<Option<&'a str>>, Ob: Into<Option<&'b str>> { let mut par: mem::MaybeUninit<x264_param_t> = mem::MaybeUninit::uninit(); let t = tune.into().map_or_else(|| None, |v| Some(CString::new(v).unwrap())); let p = preset.into().map_or_else(|| None, |v| Some(CString::new(v).unwrap())); let c_tune = t.as_ref().map_or_else(|| null(), |v| v.as_ptr() as *const i8); let c_preset = p.as_ref().map_or_else(|| null(), |v| v.as_ptr() as *const i8); match unsafe { x264_param_default_preset(par.as_mut_ptr(), c_preset, c_tune) } { -1 => Err("Invalid Argument"), 0 => Ok(Param { par: unsafe{ par.assume_init() } }), _ => Err("Unexpected"), } } pub fn apply_profile(mut self, profile: &str) -> Result<Param, &'static str> { let p = CString::new(profile).unwrap(); match unsafe { x264_param_apply_profile(&mut self.par, p.as_ptr() as *const i8) } { -1 => Err("Invalid Argument"), 0 => Ok(self), _ => Err("Unexpected"), } } pub fn param_parse<'a>(mut self, name: &str, value: &str) -> Result<Param, &'static str> { let n = CString::new(name).unwrap(); let v = CString::new(value).unwrap(); match unsafe { x264_param_parse(&mut self.par, n.as_ptr() as *const i8, v.as_ptr() as *const i8) } { -1 => Err("Invalid Argument"), 0 => Ok(self), _ => Err("Unexpected"), } } pub fn set_dimension(mut self, height: usize, width: usize) -> Param { self.par.i_height = height as c_int; self.par.i_width = width as c_int; self } } // TODO: Expose a NAL abstraction pub struct NalData { vec: Vec<u8>, } impl NalData { /* * x264 functions return x264_nal_t arrays that are valid only until another * function of that kind is called. * * Always copy the data over. * * TODO: Consider using Bytes as backing store. */ fn from_nals(c_nals: *mut x264_nal_t, nb_nal: usize) -> NalData { let mut data = NalData { vec: Vec::new() }; for i in 0..nb_nal { let nal = unsafe { Box::from_raw(c_nals.offset(i as isize)) }; let payload = unsafe { std::slice::from_raw_parts(nal.p_payload, nal.i_payload as usize) }; data.vec.extend_from_slice(payload); mem::forget(payload); mem::forget(nal); } data } pub fn as_bytes(&self) -> &[u8] { self.vec.as_slice() } } pub struct Encoder { enc: *mut x264_t, } impl Encoder { pub fn open(par: &mut Param) -> Result<Encoder, &'static str> { let enc = unsafe { x264_encoder_open(&mut par.par as *mut x264_param_t) }; if enc.is_null() { Err("Out of Memory") } else { Ok(Encoder { enc: enc }) } } pub fn get_headers(&mut self) -> Result<NalData, &'static str> { let mut nb_nal: c_int = 0; let mut c_nals: mem::MaybeUninit<*mut x264_nal_t> = mem::MaybeUninit::uninit(); let bytes = unsafe { x264_encoder_headers(self.enc, c_nals.as_mut_ptr(), &mut nb_nal as *mut c_int) }; if bytes < 0 { Err("Encoding Headers Failed") } else { let c_nals = unsafe{ c_nals.assume_init() }; Ok(NalData::from_nals(c_nals, nb_nal as usize)) } } pub fn encode<'a, P>(&mut self, pic: P) -> Result<Option<(NalData, i64, i64)>, &'static str> where P: Into<Option<&'a Picture>> { let mut pic_out: mem::MaybeUninit<x264_picture_t> = mem::MaybeUninit::uninit(); let mut c_nals : mem::MaybeUninit<*mut x264_nal_t> = mem::MaybeUninit::uninit(); let mut nb_nal: c_int = 0; let c_pic = pic.into().map_or_else(|| null(), |v| &v.pic as *const x264_picture_t); let ret = unsafe { x264_encoder_encode(self.enc, c_nals.as_mut_ptr(), &mut nb_nal as *mut c_int, c_pic as *mut x264_picture_t, pic_out.as_mut_ptr()) }; if ret < 0 { Err("Error encoding") } else { let pic_out = unsafe { pic_out.assume_init() }; let c_nals = unsafe { c_nals.assume_init() }; if nb_nal > 0 { let data = NalData::from_nals(c_nals, nb_nal as usize); Ok(Some((data, pic_out.i_pts, pic_out.i_dts))) } else { Ok(None) } } } pub fn delayed_frames(&self) -> bool { unsafe { x264_encoder_delayed_frames(self.enc) != 0 } } } impl Drop for Encoder { fn drop(&mut self) { unsafe { x264_encoder_close(self.enc) }; } } #[cfg(test)] mod tests { use super::*; #[test] fn test_open() { let mut par = Param::new().set_dimension(640, 480); let mut enc = Encoder::open(&mut par).unwrap(); let headers = enc.get_headers().unwrap(); println!("Headers len {}", headers.as_bytes().len()); } #[test] fn test_picture() { let par = Param::new().set_dimension(640, 480); { let mut pic = Picture::from_param(&par).unwrap(); { let p = pic.as_mut_slice(0).unwrap(); p[0] = 1; } let p = pic.as_slice(0).unwrap(); assert_eq!(p[0], 1); } } #[test] fn test_encode() { let mut par = Param::new().set_dimension(640, 480); let mut enc = Encoder::open(&mut par).unwrap(); let mut pic = Picture::from_param(&par).unwrap(); let headers = enc.get_headers().unwrap(); println!("Headers len {}", headers.as_bytes().len()); for pts in 0..5 { pic = pic.set_timestamp(pts as i64); let ret = enc.encode(&pic).unwrap(); match ret { Some((_, pts, dts)) => println!("Frame pts {}, dts {}", pts, dts), _ => (), } } while enc.delayed_frames() { let ret = enc.encode(None).unwrap(); match ret { Some((_, pts, dts)) => println!("Frame pts {}, dts {}", pts, dts), _ => (), } } } }
29.643564
96
0.483717
0e4e3f42a1a8d8e75fea9226d80a1f12f4524ee8
16,905
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. use deno_core::error::null_opbuf; use deno_core::error::resource_unavailable; use deno_core::error::AnyError; use deno_core::error::{bad_resource_id, not_supported}; use deno_core::AsyncMutFuture; use deno_core::AsyncRefCell; use deno_core::CancelHandle; use deno_core::CancelTryFuture; use deno_core::JsRuntime; use deno_core::OpState; use deno_core::RcRef; use deno_core::Resource; use deno_core::ResourceId; use deno_core::ZeroCopyBuf; use std::borrow::Cow; use std::cell::RefCell; use std::io::Read; use std::io::Write; use std::rc::Rc; use tokio::io::split; use tokio::io::AsyncRead; use tokio::io::AsyncReadExt; use tokio::io::AsyncWrite; use tokio::io::AsyncWriteExt; use tokio::io::ReadHalf; use tokio::io::WriteHalf; use tokio::net::tcp; use tokio::net::TcpStream; use tokio::process; use tokio_rustls as tls; #[cfg(unix)] use std::os::unix::io::FromRawFd; #[cfg(unix)] use tokio::net::unix; #[cfg(windows)] use std::os::windows::io::FromRawHandle; lazy_static::lazy_static! { /// Due to portability issues on Windows handle to stdout is created from raw /// file descriptor. The caveat of that approach is fact that when this /// handle is dropped underlying file descriptor is closed - that is highly /// not desirable in case of stdout. That's why we store this global handle /// that is then cloned when obtaining stdio for process. In turn when /// resource table is dropped storing reference to that handle, the handle /// itself won't be closed (so Deno.core.print) will still work. // TODO(ry) It should be possible to close stdout. static ref STDIN_HANDLE: Option<std::fs::File> = { #[cfg(not(windows))] let stdin = unsafe { Some(std::fs::File::from_raw_fd(0)) }; #[cfg(windows)] let stdin = unsafe { let handle = winapi::um::processenv::GetStdHandle( winapi::um::winbase::STD_INPUT_HANDLE, ); if handle.is_null() { return None; } Some(std::fs::File::from_raw_handle(handle)) }; stdin }; static ref STDOUT_HANDLE: Option<std::fs::File> = { #[cfg(not(windows))] let stdout = unsafe { Some(std::fs::File::from_raw_fd(1)) }; #[cfg(windows)] let stdout = unsafe { let handle = winapi::um::processenv::GetStdHandle( winapi::um::winbase::STD_OUTPUT_HANDLE, ); if handle.is_null() { return None; } Some(std::fs::File::from_raw_handle(handle)) }; stdout }; static ref STDERR_HANDLE: Option<std::fs::File> = { #[cfg(not(windows))] let stderr = unsafe { Some(std::fs::File::from_raw_fd(2)) }; #[cfg(windows)] let stderr = unsafe { let handle = winapi::um::processenv::GetStdHandle( winapi::um::winbase::STD_ERROR_HANDLE, ); if handle.is_null() { return None; } Some(std::fs::File::from_raw_handle(handle)) }; stderr }; } pub fn init(rt: &mut JsRuntime) { super::reg_async(rt, "op_read_async", op_read_async); super::reg_async(rt, "op_write_async", op_write_async); super::reg_sync(rt, "op_read_sync", op_read_sync); super::reg_sync(rt, "op_write_sync", op_write_sync); super::reg_async(rt, "op_shutdown", op_shutdown); } pub fn get_stdio() -> ( Option<StdFileResource>, Option<StdFileResource>, Option<StdFileResource>, ) { let stdin = get_stdio_stream(&STDIN_HANDLE, "stdin"); let stdout = get_stdio_stream(&STDOUT_HANDLE, "stdout"); let stderr = get_stdio_stream(&STDERR_HANDLE, "stderr"); (stdin, stdout, stderr) } fn get_stdio_stream( handle: &Option<std::fs::File>, name: &str, ) -> Option<StdFileResource> { match handle { None => None, Some(file_handle) => match file_handle.try_clone() { Ok(clone) => { let tokio_file = tokio::fs::File::from_std(clone); Some(StdFileResource::stdio(tokio_file, name)) } Err(_e) => None, }, } } #[cfg(unix)] use nix::sys::termios; #[derive(Default)] pub struct TtyMetadata { #[cfg(unix)] pub mode: Option<termios::Termios>, } #[derive(Default)] pub struct FileMetadata { pub tty: TtyMetadata, } #[derive(Debug)] pub struct WriteOnlyResource<S> { stream: AsyncRefCell<S>, } impl<S: 'static> From<S> for WriteOnlyResource<S> { fn from(stream: S) -> Self { Self { stream: stream.into(), } } } impl<S> WriteOnlyResource<S> where S: AsyncWrite + Unpin + 'static, { pub fn borrow_mut(self: &Rc<Self>) -> AsyncMutFuture<S> { RcRef::map(self, |r| &r.stream).borrow_mut() } async fn write(self: &Rc<Self>, buf: &[u8]) -> Result<usize, AnyError> { let mut stream = self.borrow_mut().await; let nwritten = stream.write(buf).await?; Ok(nwritten) } async fn shutdown(self: &Rc<Self>) -> Result<(), AnyError> { let mut stream = self.borrow_mut().await; stream.shutdown().await?; Ok(()) } } #[derive(Debug)] pub struct ReadOnlyResource<S> { stream: AsyncRefCell<S>, cancel_handle: CancelHandle, } impl<S: 'static> From<S> for ReadOnlyResource<S> { fn from(stream: S) -> Self { Self { stream: stream.into(), cancel_handle: Default::default(), } } } impl<S> ReadOnlyResource<S> where S: AsyncRead + Unpin + 'static, { pub fn borrow_mut(self: &Rc<Self>) -> AsyncMutFuture<S> { RcRef::map(self, |r| &r.stream).borrow_mut() } pub fn cancel_handle(self: &Rc<Self>) -> RcRef<CancelHandle> { RcRef::map(self, |r| &r.cancel_handle) } pub fn cancel_read_ops(&self) { self.cancel_handle.cancel() } async fn read(self: &Rc<Self>, buf: &mut [u8]) -> Result<usize, AnyError> { let mut rd = self.borrow_mut().await; let nread = rd.read(buf).try_or_cancel(self.cancel_handle()).await?; Ok(nread) } } /// A full duplex resource has a read and write ends that are completely /// independent, like TCP/Unix sockets and TLS streams. #[derive(Debug)] pub struct FullDuplexResource<R, W> { rd: AsyncRefCell<R>, wr: AsyncRefCell<W>, // When a full-duplex resource is closed, all pending 'read' ops are // canceled, while 'write' ops are allowed to complete. Therefore only // 'read' futures should be attached to this cancel handle. cancel_handle: CancelHandle, } impl<R, W> FullDuplexResource<R, W> where R: AsyncRead + Unpin + 'static, W: AsyncWrite + Unpin + 'static, { pub fn new((rd, wr): (R, W)) -> Self { Self { rd: rd.into(), wr: wr.into(), cancel_handle: Default::default(), } } pub fn into_inner(self) -> (R, W) { (self.rd.into_inner(), self.wr.into_inner()) } pub fn rd_borrow_mut(self: &Rc<Self>) -> AsyncMutFuture<R> { RcRef::map(self, |r| &r.rd).borrow_mut() } pub fn wr_borrow_mut(self: &Rc<Self>) -> AsyncMutFuture<W> { RcRef::map(self, |r| &r.wr).borrow_mut() } pub fn cancel_handle(self: &Rc<Self>) -> RcRef<CancelHandle> { RcRef::map(self, |r| &r.cancel_handle) } pub fn cancel_read_ops(&self) { self.cancel_handle.cancel() } async fn read(self: &Rc<Self>, buf: &mut [u8]) -> Result<usize, AnyError> { let mut rd = self.rd_borrow_mut().await; let nread = rd.read(buf).try_or_cancel(self.cancel_handle()).await?; Ok(nread) } async fn write(self: &Rc<Self>, buf: &[u8]) -> Result<usize, AnyError> { let mut wr = self.wr_borrow_mut().await; let nwritten = wr.write(buf).await?; Ok(nwritten) } async fn shutdown(self: &Rc<Self>) -> Result<(), AnyError> { let mut wr = self.wr_borrow_mut().await; wr.shutdown().await?; Ok(()) } } pub type FullDuplexSplitResource<S> = FullDuplexResource<ReadHalf<S>, WriteHalf<S>>; impl<S> From<S> for FullDuplexSplitResource<S> where S: AsyncRead + AsyncWrite + 'static, { fn from(stream: S) -> Self { Self::new(split(stream)) } } pub type ChildStdinResource = WriteOnlyResource<process::ChildStdin>; impl Resource for ChildStdinResource { fn name(&self) -> Cow<str> { "childStdin".into() } } pub type ChildStdoutResource = ReadOnlyResource<process::ChildStdout>; impl Resource for ChildStdoutResource { fn name(&self) -> Cow<str> { "childStdout".into() } fn close(self: Rc<Self>) { self.cancel_read_ops(); } } pub type ChildStderrResource = ReadOnlyResource<process::ChildStderr>; impl Resource for ChildStderrResource { fn name(&self) -> Cow<str> { "childStderr".into() } fn close(self: Rc<Self>) { self.cancel_read_ops(); } } pub type TcpStreamResource = FullDuplexResource<tcp::OwnedReadHalf, tcp::OwnedWriteHalf>; impl Resource for TcpStreamResource { fn name(&self) -> Cow<str> { "tcpStream".into() } fn close(self: Rc<Self>) { self.cancel_read_ops(); } } pub type TlsClientStreamResource = FullDuplexSplitResource<tls::client::TlsStream<TcpStream>>; impl Resource for TlsClientStreamResource { fn name(&self) -> Cow<str> { "tlsClientStream".into() } fn close(self: Rc<Self>) { self.cancel_read_ops(); } } pub type TlsServerStreamResource = FullDuplexSplitResource<tls::server::TlsStream<TcpStream>>; impl Resource for TlsServerStreamResource { fn name(&self) -> Cow<str> { "tlsServerStream".into() } fn close(self: Rc<Self>) { self.cancel_read_ops(); } } #[cfg(unix)] pub type UnixStreamResource = FullDuplexResource<unix::OwnedReadHalf, unix::OwnedWriteHalf>; #[cfg(not(unix))] struct UnixStreamResource; #[cfg(not(unix))] impl UnixStreamResource { async fn read(self: &Rc<Self>, _buf: &mut [u8]) -> Result<usize, AnyError> { unreachable!() } async fn write(self: &Rc<Self>, _buf: &[u8]) -> Result<usize, AnyError> { unreachable!() } async fn shutdown(self: &Rc<Self>) -> Result<(), AnyError> { unreachable!() } fn cancel_read_ops(&self) { unreachable!() } } impl Resource for UnixStreamResource { fn name(&self) -> Cow<str> { "unixStream".into() } fn close(self: Rc<Self>) { self.cancel_read_ops(); } } #[derive(Debug, Default)] pub struct StdFileResource { pub fs_file: Option<AsyncRefCell<(Option<tokio::fs::File>, Option<FileMetadata>)>>, cancel: CancelHandle, name: String, } impl StdFileResource { pub fn stdio(fs_file: tokio::fs::File, name: &str) -> Self { Self { fs_file: Some(AsyncRefCell::new(( Some(fs_file), Some(FileMetadata::default()), ))), name: name.to_string(), ..Default::default() } } pub fn fs_file(fs_file: tokio::fs::File) -> Self { Self { fs_file: Some(AsyncRefCell::new(( Some(fs_file), Some(FileMetadata::default()), ))), name: "fsFile".to_string(), ..Default::default() } } async fn read(self: &Rc<Self>, buf: &mut [u8]) -> Result<usize, AnyError> { if self.fs_file.is_some() { let mut fs_file = RcRef::map(&*self, |r| r.fs_file.as_ref().unwrap()) .borrow_mut() .await; let nwritten = fs_file.0.as_mut().unwrap().read(buf).await?; return Ok(nwritten); } else { Err(resource_unavailable()) } } async fn write(self: &Rc<Self>, buf: &[u8]) -> Result<usize, AnyError> { if self.fs_file.is_some() { let mut fs_file = RcRef::map(&*self, |r| r.fs_file.as_ref().unwrap()) .borrow_mut() .await; let nwritten = fs_file.0.as_mut().unwrap().write(buf).await?; fs_file.0.as_mut().unwrap().flush().await?; return Ok(nwritten); } else { Err(resource_unavailable()) } } pub fn with<F, R>( state: &mut OpState, rid: ResourceId, mut f: F, ) -> Result<R, AnyError> where F: FnMut(Result<&mut std::fs::File, ()>) -> Result<R, AnyError>, { // First we look up the rid in the resource table. let resource = state .resource_table .get::<StdFileResource>(rid) .ok_or_else(bad_resource_id)?; // Sync write only works for FsFile. It doesn't make sense to do this // for non-blocking sockets. So we error out if not FsFile. if resource.fs_file.is_none() { return f(Err(())); } // The object in the resource table is a tokio::fs::File - but in // order to do a blocking write on it, we must turn it into a // std::fs::File. Hopefully this code compiles down to nothing. let fs_file_resource = RcRef::map(&resource, |r| r.fs_file.as_ref().unwrap()).try_borrow_mut(); if let Some(mut fs_file) = fs_file_resource { let tokio_file = fs_file.0.take().unwrap(); match tokio_file.try_into_std() { Ok(mut std_file) => { let result = f(Ok(&mut std_file)); // Turn the std_file handle back into a tokio file, put it back // in the resource table. let tokio_file = tokio::fs::File::from_std(std_file); fs_file.0 = Some(tokio_file); // return the result. result } Err(tokio_file) => { // This function will return an error containing the file if // some operation is in-flight. fs_file.0 = Some(tokio_file); Err(resource_unavailable()) } } } else { Err(resource_unavailable()) } } } impl Resource for StdFileResource { fn name(&self) -> Cow<str> { self.name.as_str().into() } fn close(self: Rc<Self>) { // TODO: do not cancel file I/O when file is writable. self.cancel.cancel() } } fn op_read_sync( state: &mut OpState, rid: ResourceId, buf: Option<ZeroCopyBuf>, ) -> Result<u32, AnyError> { let mut buf = buf.ok_or_else(null_opbuf)?; StdFileResource::with(state, rid, move |r| match r { Ok(std_file) => std_file .read(&mut buf) .map(|n: usize| n as u32) .map_err(AnyError::from), Err(_) => Err(not_supported()), }) } async fn op_read_async( state: Rc<RefCell<OpState>>, rid: ResourceId, buf: Option<ZeroCopyBuf>, ) -> Result<u32, AnyError> { let buf = &mut buf.ok_or_else(null_opbuf)?; let resource = state .borrow() .resource_table .get_any(rid) .ok_or_else(bad_resource_id)?; let nread = if let Some(s) = resource.downcast_rc::<ChildStdoutResource>() { s.read(buf).await? } else if let Some(s) = resource.downcast_rc::<ChildStderrResource>() { s.read(buf).await? } else if let Some(s) = resource.downcast_rc::<TcpStreamResource>() { s.read(buf).await? } else if let Some(s) = resource.downcast_rc::<TlsClientStreamResource>() { s.read(buf).await? } else if let Some(s) = resource.downcast_rc::<TlsServerStreamResource>() { s.read(buf).await? } else if let Some(s) = resource.downcast_rc::<UnixStreamResource>() { s.read(buf).await? } else if let Some(s) = resource.downcast_rc::<StdFileResource>() { s.read(buf).await? } else { return Err(not_supported()); }; Ok(nread as u32) } fn op_write_sync( state: &mut OpState, rid: ResourceId, buf: Option<ZeroCopyBuf>, ) -> Result<u32, AnyError> { let buf = buf.ok_or_else(null_opbuf)?; StdFileResource::with(state, rid, move |r| match r { Ok(std_file) => std_file .write(&buf) .map(|nwritten: usize| nwritten as u32) .map_err(AnyError::from), Err(_) => Err(not_supported()), }) } async fn op_write_async( state: Rc<RefCell<OpState>>, rid: ResourceId, buf: Option<ZeroCopyBuf>, ) -> Result<u32, AnyError> { let buf = &buf.ok_or_else(null_opbuf)?; let resource = state .borrow() .resource_table .get_any(rid) .ok_or_else(bad_resource_id)?; let nwritten = if let Some(s) = resource.downcast_rc::<ChildStdinResource>() { s.write(buf).await? } else if let Some(s) = resource.downcast_rc::<TcpStreamResource>() { s.write(buf).await? } else if let Some(s) = resource.downcast_rc::<TlsClientStreamResource>() { s.write(buf).await? } else if let Some(s) = resource.downcast_rc::<TlsServerStreamResource>() { s.write(buf).await? } else if let Some(s) = resource.downcast_rc::<UnixStreamResource>() { s.write(buf).await? } else if let Some(s) = resource.downcast_rc::<StdFileResource>() { s.write(buf).await? } else { return Err(not_supported()); }; Ok(nwritten as u32) } async fn op_shutdown( state: Rc<RefCell<OpState>>, rid: ResourceId, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<(), AnyError> { let resource = state .borrow() .resource_table .get_any(rid) .ok_or_else(bad_resource_id)?; if let Some(s) = resource.downcast_rc::<ChildStdinResource>() { s.shutdown().await?; } else if let Some(s) = resource.downcast_rc::<TcpStreamResource>() { s.shutdown().await?; } else if let Some(s) = resource.downcast_rc::<TlsClientStreamResource>() { s.shutdown().await?; } else if let Some(s) = resource.downcast_rc::<TlsServerStreamResource>() { s.shutdown().await?; } else if let Some(s) = resource.downcast_rc::<UnixStreamResource>() { s.shutdown().await?; } else { return Err(not_supported()); } Ok(()) }
26.622047
80
0.642295
ab88faa66905be80526eef761a86e141886e1b25
4,237
use std::{convert::Infallible, fmt}; mod option; pub use option::{OptionPatch, OptionPatchError}; pub trait Patchable { type Patch: Clone; type Error: fmt::Display; /// Takes a value and produces a patches which when applied to the original object results in /// makes it equal to the taken value fn produce(&self, other: &Self) -> Option<Self::Patch>; /// Takes a patch and applies it to the current object. /// Returns an error if the patch cannot be applied to the current object. /// An example of invalid patch would be a patch which alters the value of a variant of the /// enum for a enum which is not at that value. fn apply(&mut self, patch: Self::Patch) -> Result<(), Self::Error>; } pub trait MapPatchable: Patchable + Sized { fn map_produce(&self, f: impl FnOnce(Self) -> Self) -> Option<Self::Patch>; } impl<T: Patchable + Clone> MapPatchable for T { fn map_produce(&self, f: impl FnOnce(Self) -> Self) -> Option<Self::Patch> { let clone = self.clone(); let clone = f(clone); self.produce(&clone) } } impl<T: Patchable> Patchable for Box<T> { type Patch = T::Patch; type Error = T::Error; fn produce(&self, other: &Self) -> Option<Self::Patch> { (**self).produce(other) } fn apply(&mut self, patch: Self::Patch) -> Result<(), Self::Error> { (**self).apply(patch) } } macro_rules! impl_patchable_primitive { ($x:ty) => { impl Patchable for $x { type Patch = Self; type Error = Infallible; //Make ! once it is stableized fn produce(&self, other: &Self) -> Option<Self::Patch> { if *self != *other { Some(other.clone()) } else { None } } fn apply(&mut self, patch: Self::Patch) -> Result<(), Self::Error> { *self = patch; Ok(()) } } }; } macro_rules! impl_patchable_primitives{ ($x:ty) => { impl_patchable_primitive!($x); }; ($first:ty, $($rest:ty),+) => { impl_patchable_primitive!($first); impl_patchable_primitives!($($rest),*); }; } impl_patchable_primitives!( u8, i8, u16, i16, u32, i32, f32, u64, i64, f64, usize, isize, String, bool, (), char ); #[derive(Clone)] enum TestPatch { Foo(u32), Bar(OptionPatch<u16>), Baz(i16), } enum TestPatchError { Foo(Infallible), Bar(OptionPatchError<u16>), Baz(Infallible), } impl fmt::Display for TestPatchError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { TestPatchError::Foo(ref x) => write!(fmt, "within `foo` => {}", x), TestPatchError::Bar(ref x) => write!(fmt, "within `bar` => {}", x), TestPatchError::Baz(ref x) => write!(fmt, "within `baz` => {}", x), } } } #[derive(Clone)] struct Test { foo: u32, bar: Option<u16>, baz: i16, } impl Patchable for Test { type Patch = Vec<TestPatch>; type Error = TestPatchError; fn produce(&self, other: &Self) -> Option<Self::Patch> { let mut patch = Vec::new(); if let Some(x) = self.foo.produce(&other.foo) { patch.push(TestPatch::Foo(x)); } if let Some(x) = self.bar.produce(&other.bar) { patch.push(TestPatch::Bar(x)); } if let Some(x) = self.baz.produce(&other.baz) { patch.push(TestPatch::Baz(x)); } if patch.len() == 0 { None } else { Some(patch) } } fn apply(&mut self, patch: Self::Patch) -> Result<(), Self::Error> { for v in patch { match v { TestPatch::Foo(x) => { self.foo.apply(x).map_err(TestPatchError::Foo)?; } TestPatch::Bar(x) => { self.bar.apply(x).map_err(TestPatchError::Bar)?; } TestPatch::Baz(x) => { self.baz.apply(x).map_err(TestPatchError::Baz)?; } } } Ok(()) } }
25.524096
97
0.523012
ffab7dc2e41355c6a7d6fd08c5eca57a3108dd1d
1,142
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass // Test that a type which is contravariant with respect to its region // parameter compiles successfully when used in a contravariant way. // // Note: see compile-fail/variance-regions-*.rs for the tests that check that the // variance inference works in the first place. // pretty-expanded FIXME #23616 struct Contravariant<'a> { f: &'a isize } fn use_<'a>(c: Contravariant<'a>) { let x = 3; // 'b winds up being inferred to this call. // Contravariant<'a> <: Contravariant<'call> is true // if 'call <= 'a, which is true, so no error. collapse(&x, c); fn collapse<'b>(x: &'b isize, c: Contravariant<'b>) { } } pub fn main() {}
31.722222
81
0.691769
3ae6e7fca6907858de19b20124d88c6d4ee9dabe
4,527
mod additive_map_diff; mod deploy_item_builder; pub mod exec_with_return; mod execute_request_builder; mod step_request_builder; mod upgrade_request_builder; pub mod utils; mod wasm_test_builder; use lazy_static::lazy_static; use num_traits::identities::Zero; use engine_core::engine_state::{ genesis::{GenesisAccount, GenesisConfig}, CONV_RATE, }; use engine_shared::{motes::Motes, test_utils}; use engine_wasm_prep::wasm_costs::WasmCosts; use types::{account::PublicKey, ProtocolVersion, U512}; use super::{DEFAULT_ACCOUNT_ADDR, DEFAULT_ACCOUNT_INITIAL_BALANCE}; pub use additive_map_diff::AdditiveMapDiff; pub use deploy_item_builder::DeployItemBuilder; pub use execute_request_builder::ExecuteRequestBuilder; pub use step_request_builder::StepRequestBuilder; pub use upgrade_request_builder::UpgradeRequestBuilder; pub use wasm_test_builder::{ InMemoryWasmTestBuilder, LmdbWasmTestBuilder, WasmTestBuilder, WasmTestResult, }; pub const MINT_INSTALL_CONTRACT: &str = "hdac_mint_install.wasm"; pub const POS_INSTALL_CONTRACT: &str = "pop_install.wasm"; pub const CASPER_MINT_INSTALL_CONTRACT: &str = "mint_install.wasm"; pub const CASPER_POS_INSTALL_CONTRACT: &str = "pos_install.wasm"; pub const STANDARD_PAYMENT_INSTALL_CONTRACT: &str = "standard_payment_install.wasm"; pub const STANDARD_PAYMENT_CONTRACT: &str = "standard_payment.wasm"; pub const DEFAULT_CHAIN_NAME: &str = "gerald"; pub const DEFAULT_GENESIS_TIMESTAMP: u64 = 0; pub const DEFAULT_BLOCK_TIME: u64 = 0; pub const MOCKED_ACCOUNT_ADDRESS: PublicKey = PublicKey::ed25519_from([48u8; 32]); pub const DEFAULT_ACCOUNT_KEY: PublicKey = DEFAULT_ACCOUNT_ADDR; lazy_static! { pub static ref DEFAULT_ACCOUNTS: Vec<GenesisAccount> = { let mut ret = Vec::new(); let genesis_account = GenesisAccount::new( DEFAULT_ACCOUNT_KEY, Motes::new(DEFAULT_ACCOUNT_INITIAL_BALANCE.into()), Motes::zero(), ); ret.push(genesis_account); ret }; pub static ref DEFAULT_STATE_INFOS: Vec<String> = Vec::new(); pub static ref DEFAULT_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::V1_0_0; pub static ref DEFAULT_PAYMENT: U512 = U512::from(10_000_000) * CONV_RATE; pub static ref DEFAULT_WASM_COSTS: WasmCosts = test_utils::wasm_costs_mock(); pub static ref DEFAULT_GENESIS_CONFIG: GenesisConfig = { let mint_installer_bytes; let pos_installer_bytes; let standard_payment_installer_bytes; if cfg!(feature = "use-system-contracts") { mint_installer_bytes = utils::read_wasm_file_bytes(MINT_INSTALL_CONTRACT); pos_installer_bytes = utils::read_wasm_file_bytes(POS_INSTALL_CONTRACT); standard_payment_installer_bytes = utils::read_wasm_file_bytes(STANDARD_PAYMENT_INSTALL_CONTRACT); } else { mint_installer_bytes = Vec::new(); pos_installer_bytes = Vec::new(); standard_payment_installer_bytes = Vec::new(); }; GenesisConfig::new( DEFAULT_CHAIN_NAME.to_string(), DEFAULT_GENESIS_TIMESTAMP, *DEFAULT_PROTOCOL_VERSION, mint_installer_bytes, pos_installer_bytes, standard_payment_installer_bytes, DEFAULT_ACCOUNTS.clone(), DEFAULT_STATE_INFOS.clone(), *DEFAULT_WASM_COSTS, ) }; pub static ref DEFAULT_CASPER_GENESIS_CONFIG: GenesisConfig = { let mint_installer_bytes; let pos_installer_bytes; let standard_payment_installer_bytes; if cfg!(feature = "use-system-contracts") { mint_installer_bytes = utils::read_wasm_file_bytes(CASPER_MINT_INSTALL_CONTRACT); pos_installer_bytes = utils::read_wasm_file_bytes(CASPER_POS_INSTALL_CONTRACT); standard_payment_installer_bytes = utils::read_wasm_file_bytes(STANDARD_PAYMENT_INSTALL_CONTRACT); } else { mint_installer_bytes = Vec::new(); pos_installer_bytes = Vec::new(); standard_payment_installer_bytes = Vec::new(); }; GenesisConfig::new( DEFAULT_CHAIN_NAME.to_string(), DEFAULT_GENESIS_TIMESTAMP, *DEFAULT_PROTOCOL_VERSION, mint_installer_bytes, pos_installer_bytes, standard_payment_installer_bytes, DEFAULT_ACCOUNTS.clone(), DEFAULT_STATE_INFOS.clone(), *DEFAULT_WASM_COSTS, ) }; }
39.025862
93
0.706649
6183369df4ede8b7a3774fcc0bab28c24b3c5dc8
16,132
use crate::{client, frame, proto, server}; use crate::codec::RecvError; use crate::frame::{Reason, StreamId}; use crate::frame::DEFAULT_INITIAL_WINDOW_SIZE; use crate::proto::*; use bytes::{Bytes, IntoBuf}; use futures::{Stream, try_ready}; use tokio_io::{AsyncRead, AsyncWrite}; use std::marker::PhantomData; use std::io; use std::time::Duration; /// An H2 connection #[derive(Debug)] pub(crate) struct Connection<T, P, B: IntoBuf = Bytes> where P: Peer, { /// Tracks the connection level state transitions. state: State, /// An error to report back once complete. /// /// This exists separately from State in order to support /// graceful shutdown. error: Option<Reason>, /// Read / write frame values codec: Codec<T, Prioritized<B::Buf>>, /// Pending GOAWAY frames to write. go_away: GoAway, /// Ping/pong handler ping_pong: PingPong, /// Connection settings settings: Settings, /// Stream state handler streams: Streams<B::Buf, P>, /// Client or server _phantom: PhantomData<P>, } #[derive(Debug, Clone)] pub(crate) struct Config { pub next_stream_id: StreamId, pub initial_max_send_streams: usize, pub reset_stream_duration: Duration, pub reset_stream_max: usize, pub settings: frame::Settings, } #[derive(Debug)] enum State { /// Currently open in a sane state Open, /// The codec must be flushed Closing(Reason), /// In a closed state Closed(Reason), } impl<T, P, B> Connection<T, P, B> where T: AsyncRead + AsyncWrite, P: Peer, B: IntoBuf, { pub fn new( codec: Codec<T, Prioritized<B::Buf>>, config: Config, ) -> Connection<T, P, B> { let streams = Streams::new(streams::Config { local_init_window_sz: config.settings .initial_window_size() .unwrap_or(DEFAULT_INITIAL_WINDOW_SIZE), initial_max_send_streams: config.initial_max_send_streams, local_next_stream_id: config.next_stream_id, local_push_enabled: config.settings.is_push_enabled(), local_reset_duration: config.reset_stream_duration, local_reset_max: config.reset_stream_max, remote_init_window_sz: DEFAULT_INITIAL_WINDOW_SIZE, remote_max_initiated: config.settings .max_concurrent_streams() .map(|max| max as usize), }); Connection { state: State::Open, error: None, codec: codec, go_away: GoAway::new(), ping_pong: PingPong::new(), settings: Settings::new(), streams: streams, _phantom: PhantomData, } } pub fn set_target_window_size(&mut self, size: WindowSize) { self.streams.set_target_connection_window_size(size); } /// Returns `Ready` when the connection is ready to receive a frame. /// /// Returns `RecvError` as this may raise errors that are caused by delayed /// processing of received frames. fn poll_ready(&mut self) -> Poll<(), RecvError> { // The order of these calls don't really matter too much try_ready!(self.ping_pong.send_pending_pong(&mut self.codec)); try_ready!(self.ping_pong.send_pending_ping(&mut self.codec)); try_ready!( self.settings .send_pending_ack(&mut self.codec, &mut self.streams) ); try_ready!(self.streams.send_pending_refusal(&mut self.codec)); Ok(().into()) } /// Send any pending GOAWAY frames. /// /// This will return `Some(reason)` if the connection should be closed /// afterwards. If this is a graceful shutdown, this returns `None`. fn poll_go_away(&mut self) -> Poll<Option<Reason>, io::Error> { self.go_away.send_pending_go_away(&mut self.codec) } fn go_away(&mut self, id: StreamId, e: Reason) { let frame = frame::GoAway::new(id, e); self.streams.send_go_away(id); self.go_away.go_away(frame); } fn go_away_now(&mut self, e: Reason) { let last_processed_id = self.streams.last_processed_id(); let frame = frame::GoAway::new(last_processed_id, e); self.go_away.go_away_now(frame); } pub fn go_away_from_user(&mut self, e: Reason) { let last_processed_id = self.streams.last_processed_id(); let frame = frame::GoAway::new(last_processed_id, e); self.go_away.go_away_from_user(frame); // Notify all streams of reason we're abruptly closing. self.streams.recv_err(&proto::Error::Proto(e)); } fn take_error(&mut self, ours: Reason) -> Poll<(), proto::Error> { let reason = if let Some(theirs) = self.error.take() { match (ours, theirs) { // If either side reported an error, return that // to the user. (Reason::NO_ERROR, err) | (err, Reason::NO_ERROR) => err, // If both sides reported an error, give their // error back to th user. We assume our error // was a consequence of their error, and less // important. (_, theirs) => theirs, } } else { ours }; if reason == Reason::NO_ERROR { Ok(().into()) } else { Err(proto::Error::Proto(reason)) } } /// Closes the connection by transitioning to a GOAWAY state /// iff there are no streams or references pub fn maybe_close_connection_if_no_streams(&mut self) { // If we poll() and realize that there are no streams or references // then we can close the connection by transitioning to GOAWAY if !self.streams.has_streams_or_other_references() { self.go_away_now(Reason::NO_ERROR); } } pub(crate) fn take_user_pings(&mut self) -> Option<UserPings> { self.ping_pong.take_user_pings() } /// Advances the internal state of the connection. pub fn poll(&mut self) -> Poll<(), proto::Error> { use crate::codec::RecvError::*; loop { // TODO: probably clean up this glob of code match self.state { // When open, continue to poll a frame State::Open => { match self.poll2() { // The connection has shutdown normally Ok(Async::Ready(())) => self.state = State::Closing(Reason::NO_ERROR), // The connection is not ready to make progress Ok(Async::NotReady) => { // Ensure all window updates have been sent. // // This will also handle flushing `self.codec` try_ready!(self.streams.poll_complete(&mut self.codec)); if self.error.is_some() || self.go_away.should_close_on_idle() { if !self.streams.has_streams() { self.go_away_now(Reason::NO_ERROR); continue; } } return Ok(Async::NotReady); }, // Attempting to read a frame resulted in a connection level // error. This is handled by setting a GOAWAY frame followed by // terminating the connection. Err(Connection(e)) => { log::debug!("Connection::poll; connection error={:?}", e); // We may have already sent a GOAWAY for this error, // if so, don't send another, just flush and close up. if let Some(reason) = self.go_away.going_away_reason() { if reason == e { log::trace!(" -> already going away"); self.state = State::Closing(e); continue; } } // Reset all active streams self.streams.recv_err(&e.into()); self.go_away_now(e); }, // Attempting to read a frame resulted in a stream level error. // This is handled by resetting the frame then trying to read // another frame. Err(Stream { id, reason, }) => { log::trace!("stream error; id={:?}; reason={:?}", id, reason); self.streams.send_reset(id, reason); }, // Attempting to read a frame resulted in an I/O error. All // active streams must be reset. // // TODO: Are I/O errors recoverable? Err(Io(e)) => { log::debug!("Connection::poll; IO error={:?}", e); let e = e.into(); // Reset all active streams self.streams.recv_err(&e); // Return the error return Err(e); }, } } State::Closing(reason) => { log::trace!("connection closing after flush"); // Flush/shutdown the codec try_ready!(self.codec.shutdown()); // Transition the state to error self.state = State::Closed(reason); }, State::Closed(reason) => return self.take_error(reason), } } } fn poll2(&mut self) -> Poll<(), RecvError> { use crate::frame::Frame::*; // This happens outside of the loop to prevent needing to do a clock // check and then comparison of the queue possibly multiple times a // second (and thus, the clock wouldn't have changed enough to matter). self.clear_expired_reset_streams(); loop { // First, ensure that the `Connection` is able to receive a frame // // The order here matters: // - poll_go_away may buffer a graceful shutdown GOAWAY frame // - If it has, we've also added a PING to be sent in poll_ready if let Some(reason) = try_ready!(self.poll_go_away()) { if self.go_away.should_close_now() { if self.go_away.is_user_initiated() { // A user initiated abrupt shutdown shouldn't return // the same error back to the user. return Ok(Async::Ready(())); } else { return Err(RecvError::Connection(reason)); } } // Only NO_ERROR should be waiting for idle debug_assert_eq!(reason, Reason::NO_ERROR, "graceful GOAWAY should be NO_ERROR"); } try_ready!(self.poll_ready()); match try_ready!(self.codec.poll()) { Some(Headers(frame)) => { log::trace!("recv HEADERS; frame={:?}", frame); self.streams.recv_headers(frame)?; }, Some(Data(frame)) => { log::trace!("recv DATA; frame={:?}", frame); self.streams.recv_data(frame)?; }, Some(Reset(frame)) => { log::trace!("recv RST_STREAM; frame={:?}", frame); self.streams.recv_reset(frame)?; }, Some(PushPromise(frame)) => { log::trace!("recv PUSH_PROMISE; frame={:?}", frame); self.streams.recv_push_promise(frame)?; }, Some(Settings(frame)) => { log::trace!("recv SETTINGS; frame={:?}", frame); self.settings.recv_settings(frame); }, Some(GoAway(frame)) => { log::trace!("recv GOAWAY; frame={:?}", frame); // This should prevent starting new streams, // but should allow continuing to process current streams // until they are all EOS. Once they are, State should // transition to GoAway. self.streams.recv_go_away(&frame)?; self.error = Some(frame.reason()); }, Some(Ping(frame)) => { log::trace!("recv PING; frame={:?}", frame); let status = self.ping_pong.recv_ping(frame); if status.is_shutdown() { assert!( self.go_away.is_going_away(), "received unexpected shutdown ping" ); let last_processed_id = self.streams.last_processed_id(); self.go_away(last_processed_id, Reason::NO_ERROR); } }, Some(WindowUpdate(frame)) => { log::trace!("recv WINDOW_UPDATE; frame={:?}", frame); self.streams.recv_window_update(frame)?; }, Some(Priority(frame)) => { log::trace!("recv PRIORITY; frame={:?}", frame); // TODO: handle }, None => { log::trace!("codec closed"); self.streams.recv_eof(false) .ok().expect("mutex poisoned"); return Ok(Async::Ready(())); }, } } } fn clear_expired_reset_streams(&mut self) { self.streams.clear_expired_reset_streams(); } } impl<T, B> Connection<T, client::Peer, B> where T: AsyncRead + AsyncWrite, B: IntoBuf, { pub(crate) fn streams(&self) -> &Streams<B::Buf, client::Peer> { &self.streams } } impl<T, B> Connection<T, server::Peer, B> where T: AsyncRead + AsyncWrite, B: IntoBuf, { pub fn next_incoming(&mut self) -> Option<StreamRef<B::Buf>> { self.streams.next_incoming() } // Graceful shutdown only makes sense for server peers. pub fn go_away_gracefully(&mut self) { if self.go_away.is_going_away() { // No reason to start a new one. return; } // According to http://httpwg.org/specs/rfc7540.html#GOAWAY: // // > A server that is attempting to gracefully shut down a connection // > SHOULD send an initial GOAWAY frame with the last stream // > identifier set to 2^31-1 and a NO_ERROR code. This signals to the // > client that a shutdown is imminent and that initiating further // > requests is prohibited. After allowing time for any in-flight // > stream creation (at least one round-trip time), the server can // > send another GOAWAY frame with an updated last stream identifier. // > This ensures that a connection can be cleanly shut down without // > losing requests. self.go_away(StreamId::MAX, Reason::NO_ERROR); // We take the advice of waiting 1 RTT literally, and wait // for a pong before proceeding. self.ping_pong.ping_shutdown(); } } impl<T, P, B> Drop for Connection<T, P, B> where P: Peer, B: IntoBuf, { fn drop(&mut self) { // Ignore errors as this indicates that the mutex is poisoned. let _ = self.streams.recv_eof(true); } }
37.429234
97
0.514071
14e9ca342d79fa9e0f69889ee33e56ec1dec1a07
12,163
use crate::config::{ModuleConfig, SegmentConfig}; use crate::segment::Segment; use ansi_term::{ANSIString, ANSIStrings, Style}; use std::fmt; // List of all modules // Keep these ordered alphabetically. // Default ordering is handled in configs/mod.rs pub const ALL_MODULES: &[&str] = &[ "aws", #[cfg(feature = "battery")] "battery", "character", "cmd_duration", "conda", "directory", "dotnet", "elixir", "env_var", "git_branch", "git_state", "git_status", "golang", "hostname", "java", "jobs", "kubernetes", "line_break", "memory_usage", "nix_shell", "nodejs", "package", "python", "ruby", "rust", "time", "username", ]; /// A module is a collection of segments showing data for a single integration /// (e.g. The git module shows the current git branch and status) pub struct Module<'a> { /// The module's configuration map if available pub config: Option<&'a toml::Value>, /// The module's name, to be used in configuration and logging. _name: String, /// The styling to be inherited by all segments contained within this /// module. style: Style, /// The prefix used to separate the current module from the previous one. prefix: Affix, /// The collection of segments that compose this module. segments: Vec<Segment>, /// The suffix used to separate the current module from the next one. suffix: Affix, } impl<'a> Module<'a> { /// Creates a module with no segments. pub fn new(name: &str, config: Option<&'a toml::Value>) -> Module<'a> { Module { config, _name: name.to_string(), style: Style::default(), prefix: Affix::default_prefix(name), segments: Vec::new(), suffix: Affix::default_suffix(name), } } /// Get a reference to a newly created segment in the module #[deprecated( since = "0.20.0", note = "please use `module.create_segment()` instead" )] pub fn new_segment(&mut self, name: &str, value: &str) -> &mut Segment { let mut segment = Segment::new(name); let segment_config_mock = SegmentConfig { value, style: None }; if let Some(toml::Value::Table(module_config)) = self.config { if let Some(symbol) = module_config.get(name) { let segment_config = segment_config_mock.load_config(&symbol); segment.set_style(segment_config.style.unwrap_or(self.style)); segment.set_value(segment_config.value); self.segments.push(segment); return self.segments.last_mut().unwrap(); } } segment.set_style(segment_config_mock.style.unwrap_or(self.style)); segment.set_value(segment_config_mock.value); self.segments.push(segment); self.segments.last_mut().unwrap() } /// Get a reference to a newly created segment in the module pub fn create_segment(&mut self, name: &str, segment_config: &SegmentConfig) -> &mut Segment { let mut segment = Segment::new(name); segment.set_style(segment_config.style.unwrap_or(self.style)); segment.set_value(segment_config.value); self.segments.push(segment); self.segments.last_mut().unwrap() } /// Should config exists, get a reference to a newly created segment in the module #[deprecated( since = "0.20.0", note = "please use `module.create_segment()` instead" )] pub fn new_segment_if_config_exists(&mut self, name: &str) -> Option<&mut Segment> { // Use the provided value unless overwritten by config if let Some(value) = self.config_value_str(name) { let mut segment = Segment::new(name); segment.set_style(self.style); segment.set_value(value); self.segments.push(segment); Some(self.segments.last_mut().unwrap()) } else { None } } /// Get module's name pub fn get_name(&self) -> &String { &self._name } /// Whether a module has non-empty segments pub fn is_empty(&self) -> bool { self.segments.iter().all(|segment| segment.is_empty()) } /// Get the module's prefix pub fn get_prefix(&mut self) -> &mut Affix { &mut self.prefix } /// Get the module's suffix pub fn get_suffix(&mut self) -> &mut Affix { &mut self.suffix } /// Sets the style of the segment. /// /// Accepts either `Color` or `Style`. pub fn set_style<T>(&mut self, style: T) -> &mut Module<'a> where T: Into<Style>, { self.style = style.into(); self } /// Returns a vector of colored ANSIString elements to be later used with /// `ANSIStrings()` to optimize ANSI codes pub fn ansi_strings(&self) -> Vec<ANSIString> { let shell = std::env::var("STARSHIP_SHELL").unwrap_or_default(); let ansi_strings = self .segments .iter() .map(Segment::ansi_string) .collect::<Vec<ANSIString>>(); let mut ansi_strings = match shell.as_str() { "bash" => ansi_strings_modified(ansi_strings, shell), "zsh" => ansi_strings_modified(ansi_strings, shell), _ => ansi_strings, }; ansi_strings.insert(0, self.prefix.ansi_string()); ansi_strings.push(self.suffix.ansi_string()); ansi_strings } pub fn to_string_without_prefix(&self) -> String { ANSIStrings(&self.ansi_strings()[1..]).to_string() } /// Get a module's config value as a string #[deprecated( since = "0.20.0", note = "please use <RootModuleConfig>::try_load(module.config) instead" )] pub fn config_value_str(&self, key: &str) -> Option<&str> { <&str>::from_config(self.config?.as_table()?.get(key)?) } /// Get a module's config value as an int #[deprecated( since = "0.20.0", note = "please use <RootModuleConfig>::try_load(module.config) instead" )] pub fn config_value_i64(&self, key: &str) -> Option<i64> { <i64>::from_config(self.config?.as_table()?.get(key)?) } /// Get a module's config value as a bool #[deprecated( since = "0.20.0", note = "please use <RootModuleConfig>::try_load(module.config) instead" )] pub fn config_value_bool(&self, key: &str) -> Option<bool> { <bool>::from_config(self.config?.as_table()?.get(key)?) } /// Get a module's config value as a style #[deprecated( since = "0.20.0", note = "please use <RootModuleConfig>::try_load(module.config) instead" )] pub fn config_value_style(&self, key: &str) -> Option<Style> { <Style>::from_config(self.config?.as_table()?.get(key)?) } pub(crate) fn config(&mut self) { let module_prefix = self .config_value_str("module_prefix") .map(ToOwned::to_owned); let module_prefix_style = self.config_value_style("module_prefix_style"); let module_suffix = self .config_value_str("module_suffix") .map(ToOwned::to_owned); let module_suffix_style = self.config_value_style("module_suffix_style"); if let Some(prefix) = module_prefix { self.get_prefix().set_value(prefix); } if let Some(prefix_style) = module_prefix_style { self.get_prefix().set_style(prefix_style); } if let Some(suffix) = module_suffix { self.get_suffix().set_value(suffix); } if let Some(suffix_style) = module_suffix_style { self.get_suffix().set_style(suffix_style); } } } impl<'a> fmt::Display for Module<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ansi_strings = self.ansi_strings(); write!(f, "{}", ANSIStrings(&ansi_strings)) } } /// Many shells cannot deal with raw unprintable characters (like ANSI escape /// sequences) and miscompute the cursor position as a result, leading to /// strange visual bugs. Here, we wrap these characters in shell-specific escape /// codes to indicate to the shell that they are zero-length. fn ansi_strings_modified(ansi_strings: Vec<ANSIString>, shell: String) -> Vec<ANSIString> { const ESCAPE_BEGIN: char = '\u{1b}'; const MAYBE_ESCAPE_END: char = 'm'; ansi_strings .iter() .map(|ansi| { let mut escaped = false; let final_string: String = ansi .to_string() .chars() .map(|x| match x { ESCAPE_BEGIN => { escaped = true; match shell.as_str() { "bash" => String::from("\u{5c}\u{5b}\u{1b}"), // => \[ESC "zsh" => String::from("\u{25}\u{7b}\u{1b}"), // => %{ESC _ => x.to_string(), } } MAYBE_ESCAPE_END => { if escaped { escaped = false; match shell.as_str() { "bash" => String::from("m\u{5c}\u{5d}"), // => m\] "zsh" => String::from("m\u{25}\u{7d}"), // => m%} _ => x.to_string(), } } else { x.to_string() } } _ => x.to_string(), }) .collect(); ANSIString::from(final_string) }) .collect::<Vec<ANSIString>>() } /// Module affixes are to be used for the prefix or suffix of a module. pub struct Affix { /// The affix's name, to be used in configuration and logging. _name: String, /// The affix's style. style: Style, /// The string value of the affix. value: String, } impl Affix { pub fn default_prefix(name: &str) -> Self { Self { _name: format!("{}_prefix", name), style: Style::default(), value: "via ".to_string(), } } pub fn default_suffix(name: &str) -> Self { Self { _name: format!("{}_suffix", name), style: Style::default(), value: " ".to_string(), } } /// Sets the style of the module. /// /// Accepts either `Color` or `Style`. pub fn set_style<T>(&mut self, style: T) -> &mut Self where T: Into<Style>, { self.style = style.into(); self } /// Sets the value of the module. pub fn set_value<T>(&mut self, value: T) -> &mut Self where T: Into<String>, { self.value = value.into(); self } /// Generates the colored ANSIString output. pub fn ansi_string(&self) -> ANSIString { self.style.paint(&self.value) } } impl fmt::Display for Affix { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.ansi_string()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_module_is_empty_with_no_segments() { let name = "unit_test"; let module = Module { config: None, _name: name.to_string(), style: Style::default(), prefix: Affix::default_prefix(name), segments: Vec::new(), suffix: Affix::default_suffix(name), }; assert!(module.is_empty()); } #[test] fn test_module_is_empty_with_all_empty_segments() { let name = "unit_test"; let module = Module { config: None, _name: name.to_string(), style: Style::default(), prefix: Affix::default_prefix(name), segments: vec![Segment::new("test_segment")], suffix: Affix::default_suffix(name), }; assert!(module.is_empty()); } }
30.870558
98
0.555208
22d2c63a54b355acbb085e48b59141747daefa37
273
extern crate unrar_sys as native; extern crate regex; extern crate num; #[macro_use] extern crate lazy_static; #[macro_use] extern crate enum_primitive; #[macro_use] extern crate bitflags; extern crate widestring; pub use archive::Archive; pub mod error; pub mod archive;
18.2
33
0.791209
01e3ff7d66e4ee0ae757375f067d67e6db3775bd
5,518
/* Syntax to validate: * Order of items: description, instance resolvers * Optional Generics/lifetimes * Custom name vs. default name * Optional commas between items * Optional trailing commas on instance resolvers * */ use std::marker::PhantomData; use crate::{ ast::InputValue, graphql_object, schema::model::RootNode, types::scalars::{EmptyMutation, EmptySubscription}, value::{DefaultScalarValue, Object, Value}, GraphQLUnion, }; struct Concrete; #[graphql_object] impl Concrete { fn simple() -> i32 { 123 } } #[derive(GraphQLUnion)] #[graphql(name = "ACustomNamedUnion", scalar = DefaultScalarValue)] enum CustomName { Concrete(Concrete), } #[derive(GraphQLUnion)] #[graphql(on Concrete = WithLifetime::resolve, scalar = DefaultScalarValue)] enum WithLifetime<'a> { #[graphql(ignore)] Int(PhantomData<&'a i32>), } impl<'a> WithLifetime<'a> { fn resolve(&self, _: &()) -> Option<&Concrete> { if matches!(self, Self::Int(_)) { Some(&Concrete) } else { None } } } #[derive(GraphQLUnion)] #[graphql(on Concrete = WithGenerics::resolve, scalar = DefaultScalarValue)] enum WithGenerics<T> { #[graphql(ignore)] Generic(T), } impl<T> WithGenerics<T> { fn resolve(&self, _: &()) -> Option<&Concrete> { if matches!(self, Self::Generic(_)) { Some(&Concrete) } else { None } } } #[derive(GraphQLUnion)] #[graphql(description = "A description", scalar = DefaultScalarValue)] enum DescriptionFirst { Concrete(Concrete), } struct Root; // FIXME: make async work #[crate::graphql_object(noasync)] impl<'a> Root { fn custom_name() -> CustomName { CustomName::Concrete(Concrete) } fn with_lifetime() -> WithLifetime<'a> { WithLifetime::Int(PhantomData) } fn with_generics() -> WithGenerics<i32> { WithGenerics::Generic(123) } fn description_first() -> DescriptionFirst { DescriptionFirst::Concrete(Concrete) } } async fn run_type_info_query<F>(type_name: &str, f: F) where F: Fn(&Object<DefaultScalarValue>, &Vec<Value<DefaultScalarValue>>) -> (), { let doc = r#" query ($typeName: String!) { __type(name: $typeName) { name description possibleTypes { name } } } "#; let schema = RootNode::new( Root {}, EmptyMutation::<()>::new(), EmptySubscription::<()>::new(), ); let vars = vec![("typeName".to_owned(), InputValue::scalar(type_name))] .into_iter() .collect(); let (result, errs) = crate::execute(doc, None, &schema, &vars, &()) .await .expect("Execution failed"); assert_eq!(errs, []); println!("Result: {:#?}", result); let type_info = result .as_object_value() .expect("Result is not an object") .get_field_value("__type") .expect("__type field missing") .as_object_value() .expect("__type field not an object value"); let possible_types = type_info .get_field_value("possibleTypes") .expect("possibleTypes field missing") .as_list_value() .expect("possibleTypes field not a list value"); f(type_info, possible_types); } #[tokio::test] async fn introspect_custom_name() { run_type_info_query("ACustomNamedUnion", |union, possible_types| { assert_eq!( union.get_field_value("name"), Some(&Value::scalar("ACustomNamedUnion")) ); assert_eq!(union.get_field_value("description"), Some(&Value::null())); assert!(possible_types.contains(&Value::object( vec![("name", Value::scalar("Concrete"))] .into_iter() .collect(), ))); }) .await; } #[tokio::test] async fn introspect_with_lifetime() { run_type_info_query("WithLifetime", |union, possible_types| { assert_eq!( union.get_field_value("name"), Some(&Value::scalar("WithLifetime")) ); assert_eq!(union.get_field_value("description"), Some(&Value::null())); assert!(possible_types.contains(&Value::object( vec![("name", Value::scalar("Concrete"))] .into_iter() .collect(), ))); }) .await; } #[tokio::test] async fn introspect_with_generics() { run_type_info_query("WithGenerics", |union, possible_types| { assert_eq!( union.get_field_value("name"), Some(&Value::scalar("WithGenerics")) ); assert_eq!(union.get_field_value("description"), Some(&Value::null())); assert!(possible_types.contains(&Value::object( vec![("name", Value::scalar("Concrete"))] .into_iter() .collect(), ))); }) .await; } #[tokio::test] async fn introspect_description_first() { run_type_info_query("DescriptionFirst", |union, possible_types| { assert_eq!( union.get_field_value("name"), Some(&Value::scalar("DescriptionFirst")) ); assert_eq!( union.get_field_value("description"), Some(&Value::scalar("A description")) ); assert!(possible_types.contains(&Value::object( vec![("name", Value::scalar("Concrete"))] .into_iter() .collect(), ))); }) .await; }
24.968326
79
0.580826
4a68035e051a05ded2b4acc89be95b6ec4a3fb2e
2,727
#[doc = "Register `PRODTEST[%s]` reader"] pub struct R(crate::R<PRODTEST_SPEC>); impl core::ops::Deref for R { type Target = crate::R<PRODTEST_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<PRODTEST_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<PRODTEST_SPEC>) -> Self { R(reader) } } #[doc = "Production test signature n\n\nValue on reset: 4294967295"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u32)] pub enum PRODTEST_A { #[doc = "3141677471: Production tests done"] DONE = 3141677471, #[doc = "4294967295: Production tests not done"] NOTDONE = 4294967295, } impl From<PRODTEST_A> for u32 { #[inline(always)] fn from(variant: PRODTEST_A) -> Self { variant as _ } } #[doc = "Field `PRODTEST` reader - Production test signature n"] pub struct PRODTEST_R(crate::FieldReader<u32, PRODTEST_A>); impl PRODTEST_R { pub(crate) fn new(bits: u32) -> Self { PRODTEST_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<PRODTEST_A> { match self.bits { 3141677471 => Some(PRODTEST_A::DONE), 4294967295 => Some(PRODTEST_A::NOTDONE), _ => None, } } #[doc = "Checks if the value of the field is `DONE`"] #[inline(always)] pub fn is_done(&self) -> bool { **self == PRODTEST_A::DONE } #[doc = "Checks if the value of the field is `NOTDONE`"] #[inline(always)] pub fn is_not_done(&self) -> bool { **self == PRODTEST_A::NOTDONE } } impl core::ops::Deref for PRODTEST_R { type Target = crate::FieldReader<u32, PRODTEST_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:31 - Production test signature n"] #[inline(always)] pub fn prodtest(&self) -> PRODTEST_R { PRODTEST_R::new((self.bits & 0xffff_ffff) as u32) } } #[doc = "Description collection\\[n\\]: Production test signature n\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [prodtest](index.html) module"] pub struct PRODTEST_SPEC; impl crate::RegisterSpec for PRODTEST_SPEC { type Ux = u32; } #[doc = "`read()` method returns [prodtest::R](R) reader structure"] impl crate::Readable for PRODTEST_SPEC { type Reader = R; } #[doc = "`reset()` method sets PRODTEST[%s] to value 0xffff_ffff"] impl crate::Resettable for PRODTEST_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0xffff_ffff } }
30.988636
269
0.621562
64ecf1c52afdb8bca3e6ddf0edec651745498622
673
//! Demonstrates basic assembling for a full program. #![crate_type="rlib"] fn exit() -> ! { #[direct_asm::assemble] unsafe extern "C" fn exit_raw() -> ! { "xor %rdi, %rdi"; "mov %rax, 60"; // Argument setup in edi "syscall" } unsafe { exit_raw() } } fn write(fd: usize, buf: &[u8]) { #[direct_asm::assemble] unsafe extern "C" fn write_raw(fd: usize, buf: *const u8, len: usize) -> isize { "mov %rax, 1"; "syscall"; "ret" } unsafe { write_raw(fd, buf.as_ptr(), buf.len()); } } #[no_mangle] pub fn main() { write(1, "Hello!\n".as_bytes()); exit(); }
19.228571
84
0.506686
fc962879c8f4a908b819d60d24128df25aaf3830
8,510
// Copyright (c) The nextest Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 //! Metadata management. use crate::{ config::{NextestJunitConfig, NextestProfile}, errors::WriteEventError, list::TestInstance, reporter::TestEvent, runner::{ExecuteStatus, ExecutionDescription, ExecutionResult}, }; use camino::Utf8Path; use chrono::{DateTime, FixedOffset, Utc}; use debug_ignore::DebugIgnore; use quick_junit::{NonSuccessKind, Report, TestCase, TestCaseStatus, TestRerun, TestSuite}; use std::{borrow::Cow, collections::HashMap, fs::File, time::SystemTime}; #[derive(Clone, Debug)] #[allow(dead_code)] pub(crate) struct EventAggregator<'cfg> { store_dir: &'cfg Utf8Path, // TODO: log information in a JSONable report (converting that to XML later) instead of directly // writing it to XML junit: Option<MetadataJunit<'cfg>>, } impl<'cfg> EventAggregator<'cfg> { pub(crate) fn new(profile: &'cfg NextestProfile<'cfg>) -> Self { Self { store_dir: profile.store_dir(), junit: profile.junit().map(MetadataJunit::new), } } pub(crate) fn write_event(&mut self, event: TestEvent<'cfg>) -> Result<(), WriteEventError> { if let Some(junit) = &mut self.junit { junit.write_event(event)?; } Ok(()) } } #[derive(Clone, Debug)] struct MetadataJunit<'cfg> { config: NextestJunitConfig<'cfg>, test_suites: DebugIgnore<HashMap<&'cfg str, TestSuite>>, } impl<'cfg> MetadataJunit<'cfg> { fn new(config: NextestJunitConfig<'cfg>) -> Self { Self { config, test_suites: DebugIgnore(HashMap::new()), } } pub(crate) fn write_event(&mut self, event: TestEvent<'cfg>) -> Result<(), WriteEventError> { match event { TestEvent::RunStarted { .. } => {} TestEvent::TestStarted { .. } => {} TestEvent::TestSlow { .. } => {} TestEvent::TestRetry { .. } => { // Retries are recorded in TestFinished. } TestEvent::TestFinished { test_instance, run_statuses, .. } => { fn kind_ty(run_status: &ExecuteStatus) -> (NonSuccessKind, Cow<'static, str>) { match run_status.result { ExecutionResult::Fail { signal: Some(sig) } => ( NonSuccessKind::Failure, format!("test failure due to signal {}", sig).into(), ), ExecutionResult::Fail { signal: None } => { (NonSuccessKind::Failure, "test failure".into()) } ExecutionResult::Timeout => { (NonSuccessKind::Failure, "test timeout".into()) } ExecutionResult::ExecFail => { (NonSuccessKind::Error, "execution failure".into()) } ExecutionResult::Pass => unreachable!("this is a failure status"), } } let testsuite = self.testsuite_for(test_instance); let (mut testcase_status, main_status, reruns) = match run_statuses.describe() { ExecutionDescription::Success { single_status } => { (TestCaseStatus::success(), single_status, &[][..]) } ExecutionDescription::Flaky { last_status, prior_statuses, } => (TestCaseStatus::success(), last_status, prior_statuses), ExecutionDescription::Failure { first_status, retries, .. } => { let (kind, ty) = kind_ty(first_status); let mut testcase_status = TestCaseStatus::non_success(kind); testcase_status.set_type(ty); (testcase_status, first_status, retries) } }; for rerun in reruns { let (kind, ty) = kind_ty(rerun); let mut test_rerun = TestRerun::new(kind); test_rerun .set_timestamp(to_datetime(rerun.start_time)) .set_time(rerun.time_taken) .set_type(ty) .set_system_out_lossy(rerun.stdout()) .set_system_err_lossy(rerun.stderr()); // TODO: also publish time? it won't be standard JUnit (but maybe that's ok?) testcase_status.add_rerun(test_rerun); } // TODO: set message/description on testcase_status? let mut testcase = TestCase::new(test_instance.name, testcase_status); testcase .set_classname(&test_instance.bin_info.binary_id) .set_timestamp(to_datetime(main_status.start_time)) .set_time(main_status.time_taken); // TODO: also provide stdout and stderr for passing tests? // TODO: allure seems to want the output to be in a format where text files are // written out to disk: // https://github.com/allure-framework/allure2/blob/master/plugins/junit-xml-plugin/src/main/java/io/qameta/allure/junitxml/JunitXmlPlugin.java#L192-L196 // we may have to update this format to handle that. if !main_status.result.is_success() { // TODO: use the Arc wrapper, don't clone the system out and system err bytes testcase .set_system_out_lossy(main_status.stdout()) .set_system_err_lossy(main_status.stderr()); } testsuite.add_test_case(testcase); } TestEvent::TestSkipped { .. } => { // TODO: report skipped tests? causes issues if we want to aggregate runs across // skipped and non-skipped tests. Probably needs to be made configurable. // let testsuite = self.testsuite_for(test_instance); // // let mut testcase_status = TestcaseStatus::skipped(); // testcase_status.set_message(format!("Skipped: {}", reason)); // let testcase = Testcase::new(test_instance.name, testcase_status); // // testsuite.add_testcase(testcase); } TestEvent::RunBeginCancel { .. } => {} TestEvent::RunFinished { start_time, elapsed, .. } => { // Write out the report to the given file. let mut report = Report::new(self.config.report_name()); report .set_timestamp(to_datetime(start_time)) .set_time(elapsed) .add_test_suites(self.test_suites.drain().map(|(_, testsuite)| testsuite)); let junit_path = self.config.path(); let junit_dir = junit_path.parent().expect("junit path must have a parent"); std::fs::create_dir_all(junit_dir).map_err(|error| WriteEventError::Fs { file: junit_dir.to_path_buf(), error, })?; let f = File::create(junit_path).map_err(|error| WriteEventError::Fs { file: junit_path.to_path_buf(), error, })?; report .serialize(f) .map_err(|error| WriteEventError::Junit { file: junit_path.to_path_buf(), error, })?; } } Ok(()) } fn testsuite_for(&mut self, test_instance: TestInstance<'cfg>) -> &mut TestSuite { self.test_suites .entry(&test_instance.bin_info.binary_id) .or_insert_with(|| TestSuite::new(&test_instance.bin_info.binary_id)) } } fn to_datetime(system_time: SystemTime) -> DateTime<FixedOffset> { // Serialize using UTC. let datetime = DateTime::<Utc>::from(system_time); datetime.into() }
41.111111
169
0.518801
18a156f4a1c5ff6ecc73413b93961de345542452
2,326
use std::sync::{ atomic::{AtomicU64, Ordering}, Arc, }; #[derive(Clone)] pub struct ScoreCounter { score: Arc<AtomicU64>, count: Arc<AtomicU64>, } impl ScoreCounter { pub fn inc_by(&self, score: i64) { self.score.fetch_add(score as u64, Ordering::SeqCst); self.count.fetch_add(1, Ordering::SeqCst); } pub fn score(&self) -> u64 { self.score.load(Ordering::SeqCst) } pub fn avg(&self) -> u64 { self.score() / self.count.load(Ordering::SeqCst) } } impl Default for ScoreCounter { fn default() -> Self { Self { score: Arc::new(AtomicU64::new(1)), count: Arc::new(AtomicU64::new(0)), } } } pub trait Score<Entry>: Sync + Send { fn execute(&self, entry: Entry) -> i64; } #[derive(Clone)] pub struct InverseScore { k: i64, } impl InverseScore { pub fn new(x: u32, y: u32) -> Self { assert!(y < 100); Self { k: (x * y) as i64 } } } impl Score<u32> for InverseScore { fn execute(&self, time: u32) -> i64 { self.k / (time as i64) } } pub enum HandleState { Future, Succ, Fail, } pub struct BlockBroadcastEntry { new: bool, state: HandleState, } impl BlockBroadcastEntry { pub fn new(new: bool, state: HandleState) -> Self { Self { new, state } } } #[derive(Clone)] pub struct LinearScore { base: i64, } impl LinearScore { pub fn new(base: i64) -> Self { assert!(base > 0); Self { base } } pub fn linear(&self) -> i64 { self.base } pub fn percentage(&self, percent: usize) -> i64 { assert!(percent <= 100); self.base * (percent as i64) / 100 } } impl Score<BlockBroadcastEntry> for LinearScore { fn execute(&self, entry: BlockBroadcastEntry) -> i64 { match entry.state { HandleState::Future => { if entry.new { self.percentage(50) } else { self.percentage(5) } } HandleState::Succ => { if entry.new { self.linear() } else { self.percentage(10) } } HandleState::Fail => -self.base, } } }
19.880342
61
0.512468
119a207f7c5f9f63fc80e728e9c077498b8b5d4c
2,576
use crate::*; test_case!(unique, async move { use {executor::ValidateError, prelude::Value}; run!( r#" CREATE TABLE TestA ( id INTEGER UNIQUE, num INT )"# ); run!( r#" CREATE TABLE TestB ( id INTEGER UNIQUE, num INT UNIQUE )"# ); run!( r#" CREATE TABLE TestC ( id INTEGER NULL UNIQUE, num INT )"# ); run!("INSERT INTO TestA VALUES (1, 1)"); run!("INSERT INTO TestA VALUES (2, 1), (3, 1)"); run!("INSERT INTO TestB VALUES (1, 1)"); run!("INSERT INTO TestB VALUES (2, 2), (3, 3)"); run!("INSERT INTO TestC VALUES (NULL, 1)"); run!("INSERT INTO TestC VALUES (2, 2), (NULL, 3)"); run!("UPDATE TestC SET id = 1 WHERE num = 1"); run!("UPDATE TestC SET id = NULL WHERE num = 1"); let error_cases = vec![ ( ValidateError::DuplicateEntryOnUniqueField(Value::I64(2), "id".to_owned()).into(), "INSERT INTO TestA VALUES (2, 2)", ), ( ValidateError::DuplicateEntryOnUniqueField(Value::I64(4), "id".to_owned()).into(), "INSERT INTO TestA VALUES (4, 4), (4, 5)", ), ( ValidateError::DuplicateEntryOnUniqueField(Value::I64(2), "id".to_owned()).into(), "UPDATE TestA SET id = 2 WHERE id = 1", ), ( ValidateError::DuplicateEntryOnUniqueField(Value::I64(1), "id".to_owned()).into(), "INSERT INTO TestB VALUES (1, 3)", ), ( ValidateError::DuplicateEntryOnUniqueField(Value::I64(2), "num".to_owned()).into(), "INSERT INTO TestB VALUES (4, 2)", ), ( ValidateError::DuplicateEntryOnUniqueField(Value::I64(5), "num".to_owned()).into(), "INSERT INTO TestB VALUES (5, 5), (6, 5)", ), ( ValidateError::DuplicateEntryOnUniqueField(Value::I64(2), "num".to_owned()).into(), "UPDATE TestB SET num = 2 WHERE id = 1", ), ( ValidateError::DuplicateEntryOnUniqueField(Value::I64(2), "id".to_owned()).into(), "INSERT INTO TestC VALUES (2, 4)", ), ( ValidateError::DuplicateEntryOnUniqueField(Value::I64(3), "id".to_owned()).into(), "INSERT INTO TestC VALUES (NULL, 5), (3, 5), (3, 6)", ), ( ValidateError::DuplicateEntryOnUniqueField(Value::I64(1), "id".to_owned()).into(), "UPDATE TestC SET id = 1", ), ]; for (error, sql) in error_cases { test!(Err(error), sql); } });
29.272727
95
0.527562
21366531e8103ca62ede68ae85f5a5b9d9877874
24,685
use crate::syntax::discriminant::DiscriminantSet; use crate::syntax::file::{Item, ItemForeignMod}; use crate::syntax::report::Errors; use crate::syntax::Atom::*; use crate::syntax::{ attrs, error, Api, Doc, Enum, ExternFn, ExternType, Impl, Include, IncludeKind, Lang, Namespace, Pair, Receiver, Ref, ResolvableName, Signature, Slice, Struct, Ty1, Type, TypeAlias, Var, Variant, }; use proc_macro2::{Delimiter, Group, TokenStream, TokenTree}; use quote::{format_ident, quote, quote_spanned}; use syn::parse::{ParseStream, Parser}; use syn::punctuated::Punctuated; use syn::{ Abi, Attribute, Error, Fields, FnArg, ForeignItem, ForeignItemFn, ForeignItemType, GenericArgument, Ident, ItemEnum, ItemImpl, ItemStruct, LitStr, Pat, PathArguments, Result, ReturnType, Token, Type as RustType, TypeBareFn, TypePath, TypeReference, TypeSlice, }; pub mod kw { syn::custom_keyword!(Result); } pub fn parse_items( cx: &mut Errors, items: Vec<Item>, trusted: bool, namespace: &Namespace, ) -> Vec<Api> { let mut apis = Vec::new(); for item in items { match item { Item::Struct(item) => match parse_struct(cx, item, namespace.clone()) { Ok(strct) => apis.push(strct), Err(err) => cx.push(err), }, Item::Enum(item) => match parse_enum(cx, item, namespace.clone()) { Ok(enm) => apis.push(enm), Err(err) => cx.push(err), }, Item::ForeignMod(foreign_mod) => { parse_foreign_mod(cx, foreign_mod, &mut apis, trusted, namespace) } Item::Impl(item) => match parse_impl(item, namespace) { Ok(imp) => apis.push(imp), Err(err) => cx.push(err), }, Item::Use(item) => cx.error(item, error::USE_NOT_ALLOWED), Item::Other(item) => cx.error(item, "unsupported item"), } } apis } fn parse_struct(cx: &mut Errors, item: ItemStruct, mut namespace: Namespace) -> Result<Api> { let generics = &item.generics; if !generics.params.is_empty() || generics.where_clause.is_some() { let struct_token = item.struct_token; let ident = &item.ident; let where_clause = &generics.where_clause; let span = quote!(#struct_token #ident #generics #where_clause); return Err(Error::new_spanned( span, "struct with generic parameters is not supported yet", )); } let mut doc = Doc::new(); let mut derives = Vec::new(); attrs::parse( cx, &item.attrs, attrs::Parser { doc: Some(&mut doc), derives: Some(&mut derives), namespace: Some(&mut namespace), ..Default::default() }, ); let fields = match item.fields { Fields::Named(fields) => fields, Fields::Unit => return Err(Error::new_spanned(item, "unit structs are not supported")), Fields::Unnamed(_) => { return Err(Error::new_spanned(item, "tuple structs are not supported")); } }; Ok(Api::Struct(Struct { doc, derives, struct_token: item.struct_token, name: Pair::new(namespace.clone(), item.ident), brace_token: fields.brace_token, fields: fields .named .into_iter() .map(|field| { Ok(Var { ident: field.ident.unwrap(), ty: parse_type(&field.ty, &namespace)?, }) }) .collect::<Result<_>>()?, })) } fn parse_enum(cx: &mut Errors, item: ItemEnum, mut namespace: Namespace) -> Result<Api> { let generics = &item.generics; if !generics.params.is_empty() || generics.where_clause.is_some() { let enum_token = item.enum_token; let ident = &item.ident; let where_clause = &generics.where_clause; let span = quote!(#enum_token #ident #generics #where_clause); return Err(Error::new_spanned( span, "enums with generic parameters are not allowed", )); } let mut doc = Doc::new(); let mut repr = None; attrs::parse( cx, &item.attrs, attrs::Parser { doc: Some(&mut doc), repr: Some(&mut repr), namespace: Some(&mut namespace), ..Default::default() }, ); let mut variants = Vec::new(); let mut discriminants = DiscriminantSet::new(repr); for variant in item.variants { match variant.fields { Fields::Unit => {} _ => { cx.error(variant, "enums with data are not supported yet"); break; } } let expr = variant.discriminant.as_ref().map(|(_, expr)| expr); let try_discriminant = match &expr { Some(lit) => discriminants.insert(lit), None => discriminants.insert_next(), }; let discriminant = match try_discriminant { Ok(discriminant) => discriminant, Err(err) => { cx.error(variant, err); break; } }; let expr = variant.discriminant.map(|(_, expr)| expr); variants.push(Variant { ident: variant.ident, discriminant, expr, }); } let enum_token = item.enum_token; let brace_token = item.brace_token; let mut repr = U8; match discriminants.inferred_repr() { Ok(inferred) => repr = inferred, Err(err) => { let span = quote_spanned!(brace_token.span=> #enum_token {}); cx.error(span, err); variants.clear(); } } Ok(Api::Enum(Enum { doc, enum_token, name: Pair::new(namespace, item.ident), brace_token, variants, repr, })) } fn parse_foreign_mod( cx: &mut Errors, foreign_mod: ItemForeignMod, out: &mut Vec<Api>, trusted: bool, namespace: &Namespace, ) { let lang = match parse_lang(&foreign_mod.abi) { Ok(lang) => lang, Err(err) => return cx.push(err), }; match lang { Lang::Rust => { if foreign_mod.unsafety.is_some() { let unsafety = foreign_mod.unsafety; let abi = foreign_mod.abi; let span = quote!(#unsafety #abi); cx.error(span, "extern \"Rust\" block does not need to be unsafe"); } } Lang::Cxx => {} } let trusted = trusted || foreign_mod.unsafety.is_some(); let mut items = Vec::new(); for foreign in &foreign_mod.items { match foreign { ForeignItem::Type(foreign) => { match parse_extern_type(cx, foreign, lang, trusted, namespace.clone()) { Ok(ety) => items.push(ety), Err(err) => cx.push(err), } } ForeignItem::Fn(foreign) => match parse_extern_fn(cx, foreign, lang, namespace.clone()) { Ok(efn) => items.push(efn), Err(err) => cx.push(err), }, ForeignItem::Macro(foreign) if foreign.mac.path.is_ident("include") => { match foreign.mac.parse_body_with(parse_include) { Ok(include) => items.push(Api::Include(include)), Err(err) => cx.push(err), } } ForeignItem::Verbatim(tokens) => { match parse_extern_verbatim(cx, tokens, lang, namespace.clone()) { Ok(api) => items.push(api), Err(err) => cx.push(err), } } _ => cx.error(foreign, "unsupported foreign item"), } } let mut types = items.iter().filter_map(|item| match item { Api::CxxType(ety) | Api::RustType(ety) => Some(&ety.name), Api::TypeAlias(alias) => Some(&alias.name), _ => None, }); if let (Some(single_type), None) = (types.next(), types.next()) { let single_type = single_type.clone(); for item in &mut items { if let Api::CxxFunction(efn) | Api::RustFunction(efn) = item { if let Some(receiver) = &mut efn.receiver { if receiver.ty.is_self() { receiver.ty = ResolvableName::new(single_type.rust.clone()); } } } } } out.extend(items); } fn parse_lang(abi: &Abi) -> Result<Lang> { let name = match &abi.name { Some(name) => name, None => { return Err(Error::new_spanned( abi, "ABI name is required, extern \"C\" or extern \"Rust\"", )); } }; match name.value().as_str() { "C" | "C++" => Ok(Lang::Cxx), "Rust" => Ok(Lang::Rust), _ => Err(Error::new_spanned(abi, "unrecognized ABI")), } } fn parse_extern_type( cx: &mut Errors, foreign_type: &ForeignItemType, lang: Lang, trusted: bool, mut namespace: Namespace, ) -> Result<Api> { let mut doc = Doc::new(); attrs::parse( cx, &foreign_type.attrs, attrs::Parser { doc: Some(&mut doc), namespace: Some(&mut namespace), ..Default::default() }, ); let type_token = foreign_type.type_token; let ident = foreign_type.ident.clone(); let semi_token = foreign_type.semi_token; let api_type = match lang { Lang::Cxx => Api::CxxType, Lang::Rust => Api::RustType, }; Ok(api_type(ExternType { doc, type_token, name: Pair::new(namespace, ident), semi_token, trusted, })) } fn parse_extern_fn( cx: &mut Errors, foreign_fn: &ForeignItemFn, lang: Lang, mut namespace: Namespace, ) -> Result<Api> { let generics = &foreign_fn.sig.generics; if !generics.params.is_empty() || generics.where_clause.is_some() { return Err(Error::new_spanned( foreign_fn, "extern function with generic parameters is not supported yet", )); } if let Some(variadic) = &foreign_fn.sig.variadic { return Err(Error::new_spanned( variadic, "variadic function is not supported yet", )); } let mut doc = Doc::new(); let mut cxx_name = None; let mut rust_name = None; attrs::parse( cx, &foreign_fn.attrs, attrs::Parser { doc: Some(&mut doc), cxx_name: Some(&mut cxx_name), rust_name: Some(&mut rust_name), namespace: Some(&mut namespace), ..Default::default() }, ); let mut receiver = None; let mut args = Punctuated::new(); for arg in foreign_fn.sig.inputs.pairs() { let (arg, comma) = arg.into_tuple(); match arg { FnArg::Receiver(arg) => { if let Some((ampersand, lifetime)) = &arg.reference { receiver = Some(Receiver { ampersand: *ampersand, lifetime: lifetime.clone(), mutability: arg.mutability, var: arg.self_token, ty: ResolvableName::make_self(arg.self_token.span), shorthand: true, }); continue; } return Err(Error::new_spanned(arg, "unsupported signature")); } FnArg::Typed(arg) => { let ident = match arg.pat.as_ref() { Pat::Ident(pat) => pat.ident.clone(), Pat::Wild(pat) => { Ident::new(&format!("_{}", args.len()), pat.underscore_token.span) } _ => return Err(Error::new_spanned(arg, "unsupported signature")), }; let ty = parse_type(&arg.ty, &namespace)?; if ident != "self" { args.push_value(Var { ident, ty }); if let Some(comma) = comma { args.push_punct(*comma); } continue; } if let Type::Ref(reference) = ty { if let Type::Ident(ident) = reference.inner { receiver = Some(Receiver { ampersand: reference.ampersand, lifetime: reference.lifetime, mutability: reference.mutability, var: Token![self](ident.rust.span()), ty: ident, shorthand: false, }); continue; } } return Err(Error::new_spanned(arg, "unsupported method receiver")); } } } let mut throws_tokens = None; let ret = parse_return_type(&foreign_fn.sig.output, &mut throws_tokens, &namespace)?; let throws = throws_tokens.is_some(); let unsafety = foreign_fn.sig.unsafety; let fn_token = foreign_fn.sig.fn_token; let name = Pair::new_from_differing_names( namespace, cxx_name.unwrap_or(foreign_fn.sig.ident.clone()), rust_name.unwrap_or(foreign_fn.sig.ident.clone()), ); let paren_token = foreign_fn.sig.paren_token; let semi_token = foreign_fn.semi_token; let api_function = match lang { Lang::Cxx => Api::CxxFunction, Lang::Rust => Api::RustFunction, }; Ok(api_function(ExternFn { lang, doc, name, sig: Signature { unsafety, fn_token, receiver, args, ret, throws, paren_token, throws_tokens, }, semi_token, })) } fn parse_extern_verbatim( cx: &mut Errors, tokens: &TokenStream, lang: Lang, mut namespace: Namespace, ) -> Result<Api> { // type Alias = crate::path::to::Type; let parse = |input: ParseStream| -> Result<TypeAlias> { let attrs = input.call(Attribute::parse_outer)?; let type_token: Token![type] = match input.parse()? { Some(type_token) => type_token, None => { let span = input.cursor().token_stream(); return Err(Error::new_spanned(span, "unsupported foreign item")); } }; let ident: Ident = input.parse()?; let eq_token: Token![=] = input.parse()?; let ty: RustType = input.parse()?; let semi_token: Token![;] = input.parse()?; let mut doc = Doc::new(); attrs::parse( cx, &attrs, attrs::Parser { doc: Some(&mut doc), namespace: Some(&mut namespace), ..Default::default() }, ); Ok(TypeAlias { doc, type_token, name: Pair::new(namespace, ident), eq_token, ty, semi_token, }) }; let type_alias = parse.parse2(tokens.clone())?; match lang { Lang::Cxx => Ok(Api::TypeAlias(type_alias)), Lang::Rust => { let (type_token, semi_token) = (type_alias.type_token, type_alias.semi_token); let span = quote!(#type_token #semi_token); let msg = "type alias in extern \"Rust\" block is not supported"; Err(Error::new_spanned(span, msg)) } } } fn parse_impl(imp: ItemImpl, namespace: &Namespace) -> Result<Api> { if !imp.items.is_empty() { let mut span = Group::new(Delimiter::Brace, TokenStream::new()); span.set_span(imp.brace_token.span); return Err(Error::new_spanned(span, "expected an empty impl block")); } let self_ty = &imp.self_ty; if let Some((bang, path, for_token)) = &imp.trait_ { let span = quote!(#bang #path #for_token #self_ty); return Err(Error::new_spanned( span, "unexpected impl, expected something like `impl UniquePtr<T> {}`", )); } let generics = &imp.generics; if !generics.params.is_empty() || generics.where_clause.is_some() { return Err(Error::new_spanned( imp, "generic parameters on an impl is not supported", )); } Ok(Api::Impl(Impl { impl_token: imp.impl_token, ty: parse_type(&self_ty, namespace)?, brace_token: imp.brace_token, })) } fn parse_include(input: ParseStream) -> Result<Include> { if input.peek(LitStr) { let lit: LitStr = input.parse()?; let span = lit.span(); return Ok(Include { path: lit.value(), kind: IncludeKind::Quoted, begin_span: span, end_span: span, }); } if input.peek(Token![<]) { let mut path = String::new(); let langle: Token![<] = input.parse()?; while !input.is_empty() && !input.peek(Token![>]) { let token: TokenTree = input.parse()?; match token { TokenTree::Ident(token) => path += &token.to_string(), TokenTree::Literal(token) if token .to_string() .starts_with(|ch: char| ch.is_ascii_digit()) => { path += &token.to_string(); } TokenTree::Punct(token) => path.push(token.as_char()), _ => return Err(Error::new(token.span(), "unexpected token in include path")), } } let rangle: Token![>] = input.parse()?; return Ok(Include { path, kind: IncludeKind::Bracketed, begin_span: langle.span, end_span: rangle.span, }); } Err(input.error("expected \"quoted/path/to\" or <bracketed/path/to>")) } fn parse_type(ty: &RustType, namespace: &Namespace) -> Result<Type> { match ty { RustType::Reference(ty) => parse_type_reference(ty, namespace), RustType::Path(ty) => parse_type_path(ty, namespace), RustType::Slice(ty) => parse_type_slice(ty, namespace), RustType::BareFn(ty) => parse_type_fn(ty, namespace), RustType::Tuple(ty) if ty.elems.is_empty() => Ok(Type::Void(ty.paren_token.span)), _ => Err(Error::new_spanned(ty, "unsupported type")), } } fn parse_type_reference(ty: &TypeReference, namespace: &Namespace) -> Result<Type> { let inner = parse_type(&ty.elem, namespace)?; let which = match &inner { Type::Ident(ident) if ident.rust == "str" => { if ty.mutability.is_some() { return Err(Error::new_spanned(ty, "unsupported type")); } else { Type::Str } } Type::Slice(slice) => match &slice.inner { Type::Ident(ident) if ident.rust == U8 && ty.mutability.is_none() => Type::SliceRefU8, _ => Type::Ref, }, _ => Type::Ref, }; Ok(which(Box::new(Ref { ampersand: ty.and_token, lifetime: ty.lifetime.clone(), mutability: ty.mutability, inner, }))) } fn parse_type_path(ty: &TypePath, namespace: &Namespace) -> Result<Type> { let path = &ty.path; if ty.qself.is_none() && path.leading_colon.is_none() && path.segments.len() == 1 { let segment = &path.segments[0]; let ident = segment.ident.clone(); match &segment.arguments { PathArguments::None => return Ok(Type::Ident(ResolvableName::new(ident))), PathArguments::AngleBracketed(generic) => { if ident == "UniquePtr" && generic.args.len() == 1 { if let GenericArgument::Type(arg) = &generic.args[0] { let inner = parse_type(arg, namespace)?; return Ok(Type::UniquePtr(Box::new(Ty1 { name: ident, langle: generic.lt_token, inner, rangle: generic.gt_token, }))); } } else if ident == "CxxVector" && generic.args.len() == 1 { if let GenericArgument::Type(arg) = &generic.args[0] { let inner = parse_type(arg, namespace)?; return Ok(Type::CxxVector(Box::new(Ty1 { name: ident, langle: generic.lt_token, inner, rangle: generic.gt_token, }))); } } else if ident == "Box" && generic.args.len() == 1 { if let GenericArgument::Type(arg) = &generic.args[0] { let inner = parse_type(arg, namespace)?; return Ok(Type::RustBox(Box::new(Ty1 { name: ident, langle: generic.lt_token, inner, rangle: generic.gt_token, }))); } } else if ident == "Vec" && generic.args.len() == 1 { if let GenericArgument::Type(arg) = &generic.args[0] { let inner = parse_type(arg, namespace)?; return Ok(Type::RustVec(Box::new(Ty1 { name: ident, langle: generic.lt_token, inner, rangle: generic.gt_token, }))); } } } PathArguments::Parenthesized(_) => {} } } Err(Error::new_spanned(ty, "unsupported type")) } fn parse_type_slice(ty: &TypeSlice, namespace: &Namespace) -> Result<Type> { let inner = parse_type(&ty.elem, namespace)?; Ok(Type::Slice(Box::new(Slice { bracket: ty.bracket_token, inner, }))) } fn parse_type_fn(ty: &TypeBareFn, namespace: &Namespace) -> Result<Type> { if ty.lifetimes.is_some() { return Err(Error::new_spanned( ty, "function pointer with lifetime parameters is not supported yet", )); } if ty.variadic.is_some() { return Err(Error::new_spanned( ty, "variadic function pointer is not supported yet", )); } let args = ty .inputs .iter() .enumerate() .map(|(i, arg)| { let ty = parse_type(&arg.ty, namespace)?; let ident = match &arg.name { Some(ident) => ident.0.clone(), None => format_ident!("_{}", i), }; Ok(Var { ident, ty }) }) .collect::<Result<_>>()?; let mut throws_tokens = None; let ret = parse_return_type(&ty.output, &mut throws_tokens, namespace)?; let throws = throws_tokens.is_some(); Ok(Type::Fn(Box::new(Signature { unsafety: ty.unsafety, fn_token: ty.fn_token, receiver: None, args, ret, throws, paren_token: ty.paren_token, throws_tokens, }))) } fn parse_return_type( ty: &ReturnType, throws_tokens: &mut Option<(kw::Result, Token![<], Token![>])>, namespace: &Namespace, ) -> Result<Option<Type>> { let mut ret = match ty { ReturnType::Default => return Ok(None), ReturnType::Type(_, ret) => ret.as_ref(), }; if let RustType::Path(ty) = ret { let path = &ty.path; if ty.qself.is_none() && path.leading_colon.is_none() && path.segments.len() == 1 { let segment = &path.segments[0]; let ident = segment.ident.clone(); if let PathArguments::AngleBracketed(generic) = &segment.arguments { if ident == "Result" && generic.args.len() == 1 { if let GenericArgument::Type(arg) = &generic.args[0] { ret = arg; *throws_tokens = Some((kw::Result(ident.span()), generic.lt_token, generic.gt_token)); } } } } } match parse_type(ret, namespace)? { Type::Void(_) => Ok(None), ty => Ok(Some(ty)), } }
33.585034
99
0.506785
abc03af3f0ec6d92c6029860945b6ee864765335
2,196
use jfs; use std::path; use sda_protocol::AgentId; use SdaServerResult; use stores::{BaseStore, AuthTokensStore, AuthToken}; use jfs_stores::JfsStoreExt; pub struct JfsAuthTokensStore { auth_tokens: jfs::Store, } impl JfsAuthTokensStore { pub fn new<P: AsRef<path::Path>>(prefix: P) -> SdaServerResult<JfsAuthTokensStore> { let auth_tokens = prefix.as_ref().join("auth_tokens"); Ok(JfsAuthTokensStore { auth_tokens: jfs::Store::new(auth_tokens.to_str().ok_or("pathbuf to string")?)?, }) } } impl BaseStore for JfsAuthTokensStore { fn ping(&self) -> SdaServerResult<()> { Ok(()) } } impl AuthTokensStore for JfsAuthTokensStore { fn upsert_auth_token(&self, token: &AuthToken) -> SdaServerResult<()> { self.auth_tokens.upsert(token) } fn get_auth_token(&self, id: &AgentId) -> SdaServerResult<Option<AuthToken>> { self.auth_tokens.get_option(id) } fn delete_auth_token(&self, id: &AgentId) -> SdaServerResult<()> { self.auth_tokens.delete(&*id.to_string())?; Ok(()) } } #[cfg(test)] mod test { extern crate tempdir; use sda_protocol::AgentId; use sda_protocol::Identified; use stores::{AuthTokensStore, AuthToken}; use super::JfsAuthTokensStore; #[test] fn delete() { let tmpdir = tempdir::TempDir::new("sda-server").unwrap(); let token = AuthToken { id: AgentId::random(), body: "token".to_string(), }; let store = JfsAuthTokensStore::new(tmpdir.path()).unwrap(); store.upsert_auth_token(&token).unwrap(); store.get_auth_token(&token.id()).unwrap().unwrap(); store.delete_auth_token(&token.id()).unwrap(); } #[test] fn delete_raw() { let tmpdir = tempdir::TempDir::new("sda-server").unwrap(); let token = AuthToken { id: AgentId::random(), body: "token".to_string(), }; let store = ::jfs::Store::new(tmpdir.path().to_str().unwrap()).unwrap(); store.save_with_id(&token, "foo").unwrap(); store.get::<AuthToken>("foo").unwrap(); store.delete("foo").unwrap(); } }
27.797468
92
0.610656
14e2ca35db5457a6f0a8d7fc85963e9d0c48eb33
7,929
use std::{ cell::{Ref, RefCell}, fs::{File, OpenOptions}, rc::Rc, }; use crate::{ encoder::Encoder, raw::{drm_mode_get_planes, drm_mode_get_resources, drm_set_client_capability}, Buffer, BufferType, Connector, Crtc, Error, Output, Plane, Result, }; #[allow(dead_code)] #[derive(Debug)] #[repr(u64)] enum ClientCapability { Stereo3d = 1, UniversalPlanes, Atomic, AspectRatio, WritebackConnectors, } #[derive(Debug)] pub struct Inner { pub(crate) file: File, crtcs: Vec<Rc<Crtc>>, encoders: Vec<Rc<Encoder>>, connectors: Vec<Rc<Connector>>, planes: Vec<Rc<Plane>>, } #[derive(Debug)] pub struct Connectors<'a> { inner: Ref<'a, Inner>, count: usize, } impl<'a> Iterator for Connectors<'a> { type Item = Rc<Connector>; fn next(&mut self) -> Option<Self::Item> { let child = self.inner.connectors.get(self.count); self.count += 1; child.map(|item| Rc::clone(item)) } } #[derive(Debug)] pub struct Crtcs<'a> { inner: Ref<'a, Inner>, count: usize, } impl<'a> Iterator for Crtcs<'a> { type Item = Rc<Crtc>; fn next(&mut self) -> Option<Self::Item> { let child = self.inner.crtcs.get(self.count); self.count += 1; child.map(|item| Rc::clone(item)) } } #[derive(Debug)] pub struct Encoders<'a> { inner: Ref<'a, Inner>, count: usize, } impl<'a> Iterator for Encoders<'a> { type Item = Rc<Encoder>; fn next(&mut self) -> Option<Self::Item> { let child = self.inner.encoders.get(self.count); self.count += 1; child.map(|item| Rc::clone(item)) } } #[derive(Debug)] pub struct Planes<'a> { inner: Ref<'a, Inner>, count: usize, } impl<'a> Iterator for Planes<'a> { type Item = Rc<Plane>; fn next(&mut self) -> Option<Self::Item> { let child = self.inner.planes.get(self.count); self.count += 1; child.map(|item| Rc::clone(item)) } } /// The DRM Device /// /// A Device abstracts a collection of hardware components that glued and used together will provide /// the display capabilities and a number of [Plane]s, [Crtc]s and [Connector]s #[derive(Debug)] pub struct Device { pub(crate) inner: Rc<RefCell<Inner>>, } impl Device { /// Creates a new [Device] from a path /// /// # Errors /// /// Will return [Error] if `path` doesn't exist, the user doesn't have permission to access it /// or if the ioctl fails. /// /// # Example /// /// ```no_run /// use nucleid::Device; /// /// let device = Device::new("/dev/dri/card0").unwrap(); /// ``` pub fn new(path: &str) -> Result<Self> { let file = OpenOptions::new().read(true).write(true).open(path)?; drm_set_client_capability(&file, ClientCapability::Atomic as u64)?; drm_set_client_capability(&file, ClientCapability::UniversalPlanes as u64)?; let mut crtc_ids = Vec::new(); let mut encoder_ids = Vec::new(); let mut connector_ids = Vec::new(); let _res = drm_mode_get_resources( &file, Some(&mut crtc_ids), Some(&mut encoder_ids), Some(&mut connector_ids), )?; let device = Self { inner: Rc::new(RefCell::new(Inner { file, crtcs: Vec::new(), encoders: Vec::new(), connectors: Vec::new(), planes: Vec::new(), })), }; for (idx, id) in crtc_ids.into_iter().enumerate() { let crtc = Rc::new(Crtc::new(&device, id, idx)?); device.inner.borrow_mut().crtcs.push(crtc); } for id in encoder_ids { let encoder = Rc::new(Encoder::new(&device, id)?); device.inner.borrow_mut().encoders.push(encoder); } for id in connector_ids { let connector = Rc::new(Connector::new(&device, id)?); device.inner.borrow_mut().connectors.push(connector); } let plane_ids = drm_mode_get_planes(&device)?; for id in plane_ids { let plane = Rc::new(Plane::new(&device, id)?); device.inner.borrow_mut().planes.push(plane); } Ok(device) } /// Returns an Iterator over the [Connector]s /// /// # Example /// /// ```no_run /// use nucleid::Device; /// /// let device = Device::new("/dev/dri/card0") /// .unwrap(); /// /// let connectors: Vec<_> = device.connectors() /// .collect(); /// ``` #[must_use] pub fn connectors(&self) -> Connectors<'_> { let inner = self.inner.borrow(); Connectors { inner, count: 0 } } /// Returns an Iterator over the [Crtc]s /// /// # Example /// /// ```no_run /// use nucleid::Device; /// /// let device = Device::new("/dev/dri/card0") /// .unwrap(); /// /// let crtcs: Vec<_> = device.crtcs() /// .collect(); /// ``` #[must_use] pub fn crtcs(&self) -> Crtcs<'_> { let inner = self.inner.borrow(); Crtcs { inner, count: 0 } } pub(crate) fn encoders(&self) -> Encoders<'_> { let inner = self.inner.borrow(); Encoders { inner, count: 0 } } /// Returns an Iterator over the [Plane]s /// /// # Example /// /// ```no_run /// use nucleid::Device; /// /// let device = Device::new("/dev/dri/card0") /// .unwrap(); /// /// let planes: Vec<_> = device.planes() /// .collect(); /// ``` #[must_use] pub fn planes(&self) -> Planes<'_> { let inner = self.inner.borrow(); Planes { inner, count: 0 } } /// Allocates a DRM [Buffer] /// /// # Errors /// /// Will return [Error] if the buffer allocation fails /// /// # Example /// /// ```no_run /// use nucleid::BufferType; /// use nucleid::Device; /// /// let device = Device::new("/dev/dri/card0") /// .unwrap(); /// /// let buffer = device.allocate_buffer(BufferType::Dumb, 640, 480, 32) /// .unwrap(); /// ``` pub fn allocate_buffer( &self, buftype: BufferType, width: usize, height: usize, bpp: usize, ) -> Result<Buffer> { let raw = match buftype { BufferType::Dumb => Buffer::new(self, width, height, bpp)?, }; Ok(raw) } /// Builds an [Output] from a [Connector] /// /// Finds a suitable [Crtc] for a given [Connector] and creates an [Output] from /// that. /// /// # Errors /// /// Will return [Error] if the [Device] can't be accessed, if the ioctl fails, or if it could /// not find a suitable [Crtc] for the [Connector] /// /// # Example /// /// ```no_run /// use nucleid::{ConnectorStatus, Device}; /// /// let device = Device::new("/dev/dri/card0").unwrap(); /// /// let connector = device.connectors() /// .into_iter() /// .find(|con| con.status().unwrap() == ConnectorStatus::Connected) /// .unwrap(); /// /// let output = device.output_from_connector(&connector).unwrap(); /// ``` pub fn output_from_connector(&self, connector: &Rc<Connector>) -> Result<Output> { let encoder = connector .encoders()? .into_iter() .next() .ok_or(Error::Empty)?; let crtc = encoder.crtcs()?.into_iter().next().ok_or(Error::Empty)?; Ok(Output::new(self, &crtc, &encoder, connector)) } } impl std::os::unix::io::AsRawFd for Device { fn as_raw_fd(&self) -> std::os::unix::io::RawFd { self.inner.borrow().file.as_raw_fd() } } impl From<Rc<RefCell<Inner>>> for Device { fn from(rc: Rc<RefCell<Inner>>) -> Self { Self { inner: rc } } }
24.396923
100
0.533232
75a3caf22430c0f006bf52bb16881dfa8dd172bc
1,859
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. use crate::bindings; use rusty_v8 as v8; use std::ops::Deref; use std::ops::DerefMut; /// A ZeroCopyBuf encapsulates a slice that's been borrowed from a JavaScript /// ArrayBuffer object. JavaScript objects can normally be garbage collected, /// but the existence of a ZeroCopyBuf inhibits this until it is dropped. It /// behaves much like an Arc<[u8]>. /// /// # Cloning /// Cloning a ZeroCopyBuf does not clone the contents of the buffer, /// it creates a new reference to that buffer. /// /// To actually clone the contents of the buffer do /// `let copy = Vec::from(&*zero_copy_buf);` #[derive(Clone)] pub struct ZeroCopyBuf { backing_store: v8::SharedRef<v8::BackingStore>, byte_offset: usize, byte_length: usize, } unsafe impl Send for ZeroCopyBuf {} impl ZeroCopyBuf { pub fn new<'s>( scope: &mut v8::HandleScope<'s>, view: v8::Local<v8::ArrayBufferView>, ) -> Self { let backing_store = view.buffer(scope).unwrap().get_backing_store(); let byte_offset = view.byte_offset(); let byte_length = view.byte_length(); Self { backing_store, byte_offset, byte_length, } } } impl Deref for ZeroCopyBuf { type Target = [u8]; fn deref(&self) -> &[u8] { unsafe { bindings::get_backing_store_slice( &self.backing_store, self.byte_offset, self.byte_length, ) } } } impl DerefMut for ZeroCopyBuf { fn deref_mut(&mut self) -> &mut [u8] { unsafe { bindings::get_backing_store_slice_mut( &self.backing_store, self.byte_offset, self.byte_length, ) } } } impl AsRef<[u8]> for ZeroCopyBuf { fn as_ref(&self) -> &[u8] { &*self } } impl AsMut<[u8]> for ZeroCopyBuf { fn as_mut(&mut self) -> &mut [u8] { &mut *self } }
23.2375
77
0.649812
2804197c02fd029aefe449b5bf3f47fcfdb504ee
621
#![allow(non_camel_case_types)] pub const BMA421_DEVICE_ID: u8 = 0x11; pub const BMA421_ALT_DEVICE_ID: u8 = 0x12; //TODO this is a guess pub const BMA423_DEFAULT_DEVICE_ID: u8 = 0x18; pub const BMA423_ALT_DEVICE_ID: u8 = 0x19; #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[repr(u8)] pub enum Register { CHIP_ID = 0x00, ERROR = 0x02, STATUS = 0x03, DATA_0 = 0x0A, DATA_8 = 0x12, SENSORTIME_0 = 0x18, INT_STAT_0 = 0x1C, INT_STAT_1 = 0x1D, TEMPERATURE_ = 0x22, CMD = 0x7E, } #[derive(Copy, Clone, Debug, Eq, PartialEq)] #[repr(u8)] pub enum Command { SOFT_RESET = 0xB6, }
19.40625
65
0.661836
7676a80fe18ff34ab6e740d5e615d13f7045010e
284
//! A mininal runtime / startup for OpenSBI on RISC-V. #![no_std] #![feature(llvm_asm, global_asm)] #![feature(alloc_error_handler)] #![deny(warnings, missing_docs)] extern crate alloc; #[macro_use] pub mod io; mod log; mod runtime; pub mod sbi; pub use opensbi_rt_macros::entry;
16.705882
54
0.725352
d56039a665b44cb7a89e26d45698e65210838aa5
1,989
/* * NHL API * * Documenting the publicly accessible portions of the NHL API. * * The version of the OpenAPI document: 1.0.0 * * Generated by: https://openapi-generator.tech */ #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct ScheduleGame { #[serde(rename = "gamePk", skip_serializing_if = "Option::is_none")] pub game_pk: Option<f32>, #[serde(rename = "link", skip_serializing_if = "Option::is_none")] pub link: Option<String>, #[serde(rename = "gameType", skip_serializing_if = "Option::is_none")] pub game_type: Option<String>, #[serde(rename = "season", skip_serializing_if = "Option::is_none")] pub season: Option<String>, #[serde(rename = "gameDate", skip_serializing_if = "Option::is_none")] pub game_date: Option<String>, #[serde(rename = "status", skip_serializing_if = "Option::is_none")] pub status: Option<crate::models::GameGameDataStatus>, #[serde(rename = "teams", skip_serializing_if = "Option::is_none")] pub teams: Option<crate::models::ScheduleGameTeams>, #[serde(rename = "linescore", skip_serializing_if = "Option::is_none")] pub linescore: Option<crate::models::GameLinescore>, #[serde(rename = "venue", skip_serializing_if = "Option::is_none")] pub venue: Option<crate::models::GameGameDataVenue>, #[serde(rename = "tickets", skip_serializing_if = "Option::is_none")] pub tickets: Option<Vec<crate::models::ScheduleGameTickets>>, #[serde(rename = "content", skip_serializing_if = "Option::is_none")] pub content: Option<crate::models::ScheduleGameContent>, } impl ScheduleGame { pub fn new() -> ScheduleGame { ScheduleGame { game_pk: None, link: None, game_type: None, season: None, game_date: None, status: None, teams: None, linescore: None, venue: None, tickets: None, content: None, } } }
34.293103
75
0.638009
f7f77e144778416f1b31715c2f19bb657d07ad7b
28,432
use std::iter; use cgmath::prelude::*; use wgpu::util::DeviceExt; use winit::{ event::*, event_loop::{ControlFlow, EventLoop}, window::Window, }; mod model; mod texture; use model::{DrawLight, DrawModel, Vertex}; #[rustfmt::skip] pub const OPENGL_TO_WGPU_MATRIX: cgmath::Matrix4<f32> = cgmath::Matrix4::new( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.5, 1.0, ); const NUM_INSTANCES_PER_ROW: u32 = 10; struct Camera { eye: cgmath::Point3<f32>, target: cgmath::Point3<f32>, up: cgmath::Vector3<f32>, aspect: f32, fovy: f32, znear: f32, zfar: f32, } impl Camera { fn build_view_projection_matrix(&self) -> cgmath::Matrix4<f32> { let view = cgmath::Matrix4::look_at_rh(self.eye, self.target, self.up); let proj = cgmath::perspective(cgmath::Deg(self.fovy), self.aspect, self.znear, self.zfar); proj * view } } #[repr(C)] #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] struct Uniforms { view_position: [f32; 4], view_proj: [[f32; 4]; 4], } impl Uniforms { fn new() -> Self { Self { view_position: [0.0; 4], view_proj: cgmath::Matrix4::identity().into(), } } fn update_view_proj(&mut self, camera: &Camera) { self.view_position = camera.eye.to_homogeneous().into(); self.view_proj = (OPENGL_TO_WGPU_MATRIX * camera.build_view_projection_matrix()).into(); } } struct CameraController { speed: f32, is_up_pressed: bool, is_down_pressed: bool, is_forward_pressed: bool, is_backward_pressed: bool, is_left_pressed: bool, is_right_pressed: bool, } impl CameraController { fn new(speed: f32) -> Self { Self { speed, is_up_pressed: false, is_down_pressed: false, is_forward_pressed: false, is_backward_pressed: false, is_left_pressed: false, is_right_pressed: false, } } fn process_events(&mut self, event: &WindowEvent) -> bool { match event { WindowEvent::KeyboardInput { input: KeyboardInput { state, virtual_keycode: Some(keycode), .. }, .. } => { let is_pressed = *state == ElementState::Pressed; match keycode { VirtualKeyCode::Space => { self.is_up_pressed = is_pressed; true } VirtualKeyCode::LShift => { self.is_down_pressed = is_pressed; true } VirtualKeyCode::W | VirtualKeyCode::Up => { self.is_forward_pressed = is_pressed; true } VirtualKeyCode::A | VirtualKeyCode::Left => { self.is_left_pressed = is_pressed; true } VirtualKeyCode::S | VirtualKeyCode::Down => { self.is_backward_pressed = is_pressed; true } VirtualKeyCode::D | VirtualKeyCode::Right => { self.is_right_pressed = is_pressed; true } _ => false, } } _ => false, } } fn update_camera(&self, camera: &mut Camera) { let forward = camera.target - camera.eye; let forward_norm = forward.normalize(); let forward_mag = forward.magnitude(); // Prevents glitching when camera gets too close to the // center of the scene. if self.is_forward_pressed && forward_mag > self.speed { camera.eye += forward_norm * self.speed; } if self.is_backward_pressed { camera.eye -= forward_norm * self.speed; } let right = forward_norm.cross(camera.up); // Redo radius calc in case the up/ down is pressed. let forward = camera.target - camera.eye; let forward_mag = forward.magnitude(); if self.is_right_pressed { // Rescale the distance between the target and eye so // that it doesn't change. The eye therefore still // lies on the circle made by the target and eye. camera.eye = camera.target - (forward + right * self.speed).normalize() * forward_mag; } if self.is_left_pressed { camera.eye = camera.target - (forward - right * self.speed).normalize() * forward_mag; } } } struct Instance { position: cgmath::Vector3<f32>, rotation: cgmath::Quaternion<f32>, } impl Instance { fn to_raw(&self) -> InstanceRaw { InstanceRaw { model: (cgmath::Matrix4::from_translation(self.position) * cgmath::Matrix4::from(self.rotation)) .into(), normal: cgmath::Matrix3::from(self.rotation).into(), } } } #[repr(C)] #[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] #[allow(dead_code)] struct InstanceRaw { model: [[f32; 4]; 4], normal: [[f32; 3]; 3], } impl model::Vertex for InstanceRaw { fn desc<'a>() -> wgpu::VertexBufferLayout<'a> { use std::mem; wgpu::VertexBufferLayout { array_stride: mem::size_of::<InstanceRaw>() as wgpu::BufferAddress, // We need to switch from using a step mode of Vertex to Instance // This means that our shaders will only change to use the next // instance when the shader starts processing a new instance step_mode: wgpu::InputStepMode::Instance, attributes: &[ wgpu::VertexAttribute { offset: 0, // While our vertex shader only uses locations 0, and 1 now, in later tutorials we'll // be using 2, 3, and 4, for Vertex. We'll start at slot 5 not conflict with them later shader_location: 5, format: wgpu::VertexFormat::Float32x4, }, // A mat4 takes up 4 vertex slots as it is technically 4 vec4s. We need to define a slot // for each vec4. We don't have to do this in code though. wgpu::VertexAttribute { offset: mem::size_of::<[f32; 4]>() as wgpu::BufferAddress, shader_location: 6, format: wgpu::VertexFormat::Float32x4, }, wgpu::VertexAttribute { offset: mem::size_of::<[f32; 8]>() as wgpu::BufferAddress, shader_location: 7, format: wgpu::VertexFormat::Float32x4, }, wgpu::VertexAttribute { offset: mem::size_of::<[f32; 12]>() as wgpu::BufferAddress, shader_location: 8, format: wgpu::VertexFormat::Float32x4, }, wgpu::VertexAttribute { offset: mem::size_of::<[f32; 16]>() as wgpu::BufferAddress, shader_location: 9, format: wgpu::VertexFormat::Float32x3, }, wgpu::VertexAttribute { offset: mem::size_of::<[f32; 19]>() as wgpu::BufferAddress, shader_location: 10, format: wgpu::VertexFormat::Float32x3, }, wgpu::VertexAttribute { offset: mem::size_of::<[f32; 22]>() as wgpu::BufferAddress, shader_location: 11, format: wgpu::VertexFormat::Float32x3, }, ], } } } #[repr(C)] #[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] struct Light { position: [f32; 3], // Due to uniforms requiring 16 byte (4 float) spacing, we need to use a padding field here _padding: u32, color: [f32; 3], } struct State { surface: wgpu::Surface, device: wgpu::Device, queue: wgpu::Queue, sc_desc: wgpu::SwapChainDescriptor, swap_chain: wgpu::SwapChain, render_pipeline: wgpu::RenderPipeline, obj_model: model::Model, camera: Camera, camera_controller: CameraController, uniforms: Uniforms, uniform_buffer: wgpu::Buffer, uniform_bind_group: wgpu::BindGroup, instances: Vec<Instance>, #[allow(dead_code)] instance_buffer: wgpu::Buffer, depth_texture: texture::Texture, size: winit::dpi::PhysicalSize<u32>, light: Light, light_buffer: wgpu::Buffer, light_bind_group: wgpu::BindGroup, light_render_pipeline: wgpu::RenderPipeline, #[allow(dead_code)] debug_material: model::Material, } fn create_render_pipeline( device: &wgpu::Device, layout: &wgpu::PipelineLayout, color_format: wgpu::TextureFormat, depth_format: Option<wgpu::TextureFormat>, vertex_layouts: &[wgpu::VertexBufferLayout], shader: wgpu::ShaderModuleDescriptor, ) -> wgpu::RenderPipeline { let shader = device.create_shader_module(&shader); device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("Render Pipeline"), layout: Some(layout), vertex: wgpu::VertexState { module: &shader, entry_point: "main", buffers: vertex_layouts, }, fragment: Some(wgpu::FragmentState { module: &shader, entry_point: "main", targets: &[wgpu::ColorTargetState { format: color_format, blend: Some(wgpu::BlendState { alpha: wgpu::BlendComponent::REPLACE, color: wgpu::BlendComponent::REPLACE, }), write_mask: wgpu::ColorWrite::ALL, }], }), primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, strip_index_format: None, front_face: wgpu::FrontFace::Ccw, cull_mode: Some(wgpu::Face::Back), // Setting this to anything other than Fill requires Features::NON_FILL_POLYGON_MODE polygon_mode: wgpu::PolygonMode::Fill, // Requires Features::DEPTH_CLAMPING clamp_depth: false, // Requires Features::CONSERVATIVE_RASTERIZATION conservative: false, }, depth_stencil: depth_format.map(|format| wgpu::DepthStencilState { format, depth_write_enabled: true, depth_compare: wgpu::CompareFunction::Less, stencil: wgpu::StencilState::default(), bias: wgpu::DepthBiasState::default(), }), multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false, }, }) } impl State { async fn new(window: &Window) -> Self { let size = window.inner_size(); // The instance is a handle to our GPU // BackendBit::PRIMARY => Vulkan + Metal + DX12 + Browser WebGPU let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY); let surface = unsafe { instance.create_surface(window) }; let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::default(), compatible_surface: Some(&surface), }) .await .unwrap(); let (device, queue) = adapter .request_device( &wgpu::DeviceDescriptor { label: None, features: wgpu::Features::empty(), limits: wgpu::Limits::default(), }, None, // Trace path ) .await .unwrap(); let sc_desc = wgpu::SwapChainDescriptor { usage: wgpu::TextureUsage::RENDER_ATTACHMENT, format: adapter.get_swap_chain_preferred_format(&surface).unwrap(), width: size.width, height: size.height, present_mode: wgpu::PresentMode::Fifo, }; let swap_chain = device.create_swap_chain(&surface, &sc_desc); let texture_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Texture { multisampled: false, sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2, }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Sampler { comparison: false, filtering: true, }, count: None, }, // normal map wgpu::BindGroupLayoutEntry { binding: 2, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Texture { multisampled: false, sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2, }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 3, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Sampler { comparison: false, filtering: true, }, count: None, }, ], label: Some("texture_bind_group_layout"), }); let camera = Camera { eye: (0.0, 5.0, -10.0).into(), target: (0.0, 0.0, 0.0).into(), up: cgmath::Vector3::unit_y(), aspect: sc_desc.width as f32 / sc_desc.height as f32, fovy: 45.0, znear: 0.1, zfar: 100.0, }; let camera_controller = CameraController::new(0.2); let mut uniforms = Uniforms::new(); uniforms.update_view_proj(&camera); let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("Uniform Buffer"), contents: bytemuck::cast_slice(&[uniforms]), usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, }); const SPACE_BETWEEN: f32 = 3.0; let instances = (0..NUM_INSTANCES_PER_ROW) .flat_map(|z| { (0..NUM_INSTANCES_PER_ROW).map(move |x| { let x = SPACE_BETWEEN * (x as f32 - NUM_INSTANCES_PER_ROW as f32 / 2.0); let z = SPACE_BETWEEN * (z as f32 - NUM_INSTANCES_PER_ROW as f32 / 2.0); let position = cgmath::Vector3 { x, y: 0.0, z }; let rotation = if position.is_zero() { cgmath::Quaternion::from_axis_angle( cgmath::Vector3::unit_z(), cgmath::Deg(0.0), ) } else { cgmath::Quaternion::from_axis_angle(position.normalize(), cgmath::Deg(45.0)) }; Instance { position, rotation } }) }) .collect::<Vec<_>>(); let instance_data = instances.iter().map(Instance::to_raw).collect::<Vec<_>>(); let instance_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("Instance Buffer"), contents: bytemuck::cast_slice(&instance_data), usage: wgpu::BufferUsage::VERTEX, }); let uniform_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None, }, count: None, }], label: Some("uniform_bind_group_layout"), }); let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &uniform_bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: uniform_buffer.as_entire_binding(), }], label: Some("uniform_bind_group"), }); let res_dir = std::path::Path::new(env!("OUT_DIR")).join("res"); let obj_model = model::Model::load( &device, &queue, &texture_bind_group_layout, res_dir.join("cube.obj"), ) .unwrap(); let light = Light { position: [2.0, 2.0, 2.0], _padding: 0, color: [1.0, 1.0, 1.0], }; let light_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("Light VB"), contents: bytemuck::cast_slice(&[light]), usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, }); let light_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None, }, count: None, }], label: None, }); let light_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &light_bind_group_layout, entries: &[wgpu::BindGroupEntry { binding: 0, resource: light_buffer.as_entire_binding(), }], label: None, }); let depth_texture = texture::Texture::create_depth_texture(&device, &sc_desc, "depth_texture"); let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Render Pipeline Layout"), bind_group_layouts: &[ &texture_bind_group_layout, &uniform_bind_group_layout, &light_bind_group_layout, ], push_constant_ranges: &[], }); let render_pipeline = { let shader = wgpu::ShaderModuleDescriptor { label: Some("Normal Shader"), flags: wgpu::ShaderFlags::all(), source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()), }; create_render_pipeline( &device, &render_pipeline_layout, sc_desc.format, Some(texture::Texture::DEPTH_FORMAT), &[model::ModelVertex::desc(), InstanceRaw::desc()], shader, ) }; let light_render_pipeline = { let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Light Pipeline Layout"), bind_group_layouts: &[&uniform_bind_group_layout, &light_bind_group_layout], push_constant_ranges: &[], }); let shader = wgpu::ShaderModuleDescriptor { label: Some("Light Shader"), flags: wgpu::ShaderFlags::all(), source: wgpu::ShaderSource::Wgsl(include_str!("light.wgsl").into()), }; create_render_pipeline( &device, &layout, sc_desc.format, Some(texture::Texture::DEPTH_FORMAT), &[model::ModelVertex::desc()], shader, ) }; let debug_material = { let diffuse_bytes = include_bytes!("../res/cobble-diffuse.png"); let normal_bytes = include_bytes!("../res/cobble-normal.png"); let diffuse_texture = texture::Texture::from_bytes( &device, &queue, diffuse_bytes, "res/alt-diffuse.png", false, ) .unwrap(); let normal_texture = texture::Texture::from_bytes( &device, &queue, normal_bytes, "res/alt-normal.png", true, ) .unwrap(); model::Material::new( &device, "alt-material", diffuse_texture, normal_texture, &texture_bind_group_layout, ) }; Self { surface, device, queue, sc_desc, swap_chain, render_pipeline, obj_model, camera, camera_controller, uniform_buffer, uniform_bind_group, uniforms, instances, instance_buffer, depth_texture, size, light, light_buffer, light_bind_group, light_render_pipeline, #[allow(dead_code)] debug_material, } } fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) { if new_size.width > 0 && new_size.height > 0 { self.camera.aspect = self.sc_desc.width as f32 / self.sc_desc.height as f32; self.size = new_size; self.sc_desc.width = new_size.width; self.sc_desc.height = new_size.height; self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc); self.depth_texture = texture::Texture::create_depth_texture(&self.device, &self.sc_desc, "depth_texture"); } } fn input(&mut self, event: &WindowEvent) -> bool { self.camera_controller.process_events(event) } fn update(&mut self) { self.camera_controller.update_camera(&mut self.camera); self.uniforms.update_view_proj(&self.camera); self.queue.write_buffer( &self.uniform_buffer, 0, bytemuck::cast_slice(&[self.uniforms]), ); // Update the light let old_position: cgmath::Vector3<_> = self.light.position.into(); self.light.position = (cgmath::Quaternion::from_axis_angle((0.0, 1.0, 0.0).into(), cgmath::Deg(1.0)) * old_position) .into(); self.queue .write_buffer(&self.light_buffer, 0, bytemuck::cast_slice(&[self.light])); } fn render(&mut self) -> Result<(), wgpu::SwapChainError> { let frame = self.swap_chain.get_current_frame()?.output; let mut encoder = self .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Render Encoder"), }); { let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { label: Some("Render Pass"), color_attachments: &[wgpu::RenderPassColorAttachment { view: &frame.view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0, }), store: true, }, }], depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { view: &self.depth_texture.view, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(1.0), store: true, }), stencil_ops: None, }), }); render_pass.set_vertex_buffer(1, self.instance_buffer.slice(..)); render_pass.set_pipeline(&self.light_render_pipeline); render_pass.draw_light_model( &self.obj_model, &self.uniform_bind_group, &self.light_bind_group, ); render_pass.set_pipeline(&self.render_pipeline); render_pass.draw_model_instanced( &self.obj_model, 0..self.instances.len() as u32, &self.uniform_bind_group, &self.light_bind_group, ); } self.queue.submit(iter::once(encoder.finish())); Ok(()) } } fn main() { env_logger::init(); let event_loop = EventLoop::new(); let title = env!("CARGO_PKG_NAME"); let window = winit::window::WindowBuilder::new() .with_title(title) .build(&event_loop) .unwrap(); let mut state = pollster::block_on(State::new(&window)); event_loop.run(move |event, _, control_flow| { *control_flow = ControlFlow::Poll; match event { Event::MainEventsCleared => window.request_redraw(), Event::WindowEvent { ref event, window_id, } if window_id == window.id() => { if !state.input(event) { match event { WindowEvent::CloseRequested | WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Escape), .. }, .. } => *control_flow = ControlFlow::Exit, WindowEvent::Resized(physical_size) => { state.resize(*physical_size); } WindowEvent::ScaleFactorChanged { new_inner_size, .. } => { state.resize(**new_inner_size); } _ => {} } } } Event::RedrawRequested(_) => { state.update(); match state.render() { Ok(_) => {} // Recreate the swap_chain if lost Err(wgpu::SwapChainError::Lost) => state.resize(state.size), // The system is out of memory, we should probably quit Err(wgpu::SwapChainError::OutOfMemory) => *control_flow = ControlFlow::Exit, // All other errors (Outdated, Timeout) should be resolved by the next frame Err(e) => eprintln!("{:?}", e), } } _ => {} } }); }
35.944374
107
0.502392
7ad715dbaa55caf38e77a7bbd81fabc9387c0ffd
1,794
use crate::html_to_element; use material_yew::MatIconButton; use yew::prelude::*; pub struct Codeblock { link: ComponentLink<Self>, props: Props, showing_code: bool, } pub enum Msg { FlipShowCode, } #[derive(Properties, Clone)] pub struct Props { // pub children: Children, // pub code: String, pub title: String, pub code_and_html: (String, Html), #[prop_or(45)] pub max_width: u32, } impl Component for Codeblock { type Message = Msg; type Properties = Props; fn create(props: Self::Properties, link: ComponentLink<Self>) -> Self { Self { link, props, showing_code: false, } } fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Msg::FlipShowCode => { self.showing_code = !self.showing_code; true } } } fn change(&mut self, props: Self::Properties) -> bool { self.props = props; true } fn view(&self) -> Html { let code = html_to_element(&self.props.code_and_html.0); html! { <> <section class="codeblock" style=format!("max-width: {}%", self.props.max_width)> <section class="header"> <h2 class="title">{&self.props.title}</h2> <span class="right-icon" onclick=self.link.callback(|_| Msg::FlipShowCode)> <MatIconButton icon="code" /> </span> </section> { if self.showing_code { {code} } else { html!{} } } { self.props.code_and_html.1.clone() } </section> </> } } }
24.575342
95
0.501115
1e489fb926d6bf8af4127690fa22e43d93d372ab
3,656
pub mod conditionals; mod animation_action; mod call; mod control_action; mod delay; mod echo; mod entity_action; mod foreign_entity_action; mod group; mod health_action; mod insert_components; mod lifecycle_action; mod move_action; mod player_action; mod random; mod repeat_delay; mod sound_action; mod spawn_action; mod variable_action; pub mod prelude { pub use super::animation_action::AnimationAction; pub use super::call::Call; pub use super::conditionals; pub use super::control_action::ControlAction; pub use super::delay::Delay; pub use super::echo::Echo; pub use super::entity_action::EntityAction; pub use super::foreign_entity_action::{ ForeignEntityAction, ForeignEntitySelector, }; pub use super::group::Group; pub use super::health_action::HealthAction; pub use super::insert_components::InsertComponents; pub use super::lifecycle_action::LifecycleAction; pub use super::move_action::MoveAction; pub use super::player_action::PlayerAction; pub use super::random::Random; pub use super::repeat_delay::RepeatDelay; pub use super::sound_action::SoundAction; pub use super::spawn_action::SpawnAction; pub use super::variable_action::VariableAction; pub use super::ActionTriggerStorages; pub use super::ActionType; } use super::action_trigger::ActionTrigger; use deathframe::amethyst::ecs::shred::ResourceId; use deathframe::amethyst::ecs::{SystemData, World, WriteStorage}; use prelude::*; #[derive(Clone, Deserialize)] pub enum ActionType { Echo(Echo), Group(Group), MoveAction(MoveAction), Random(Random), Delay(Delay), RepeatDelay(RepeatDelay), InsertComponents(InsertComponents), HealthAction(HealthAction), AnimationAction(AnimationAction), SoundAction(SoundAction), EntityAction(EntityAction), SpawnAction(SpawnAction), LifecycleAction(LifecycleAction), PlayerAction(PlayerAction), Call(Call), If(conditionals::IfAction), ControlAction(ControlAction), VariableAction(VariableAction), ForeignEntityAction(ForeignEntityAction), } #[derive(SystemData)] pub struct ActionTriggerStorages<'a> { pub echo: WriteStorage<'a, ActionTrigger<Echo>>, pub group: WriteStorage<'a, ActionTrigger<Group>>, pub move_action: WriteStorage<'a, ActionTrigger<MoveAction>>, pub random: WriteStorage<'a, ActionTrigger<Random>>, pub delay: WriteStorage<'a, ActionTrigger<Delay>>, pub repeat_delay: WriteStorage<'a, ActionTrigger<RepeatDelay>>, pub insert_components: WriteStorage<'a, ActionTrigger<InsertComponents>>, pub health_action: WriteStorage<'a, ActionTrigger<HealthAction>>, pub animation_action: WriteStorage<'a, ActionTrigger<AnimationAction>>, pub sound_action: WriteStorage<'a, ActionTrigger<SoundAction>>, pub entity_action: WriteStorage<'a, ActionTrigger<EntityAction>>, pub spawn_action: WriteStorage<'a, ActionTrigger<SpawnAction>>, pub lifecycle_action: WriteStorage<'a, ActionTrigger<LifecycleAction>>, pub player_action: WriteStorage<'a, ActionTrigger<PlayerAction>>, pub call: WriteStorage<'a, ActionTrigger<Call>>, pub if_action: WriteStorage<'a, ActionTrigger<conditionals::IfAction>>, pub control_action: WriteStorage<'a, ActionTrigger<ControlAction>>, pub variable_action: WriteStorage<'a, ActionTrigger<VariableAction>>, pub foreign_entity_action: WriteStorage<'a, ActionTrigger<ForeignEntityAction>>, }
36.56
80
0.713895
622ba1a5cce2765568b244c096ce01adade3cb02
10,645
// Type encoding use io::WriterUtil; use std::map::hashmap; use syntax::ast::*; use syntax::diagnostic::span_handler; use middle::ty; use middle::ty::vid; use syntax::print::pprust::*; export ctxt; export ty_abbrev; export ac_no_abbrevs; export ac_use_abbrevs; export enc_ty; export enc_bounds; export enc_mode; type ctxt = { diag: span_handler, // Def -> str Callback: ds: fn@(def_id) -> ~str, // The type context. tcx: ty::ctxt, reachable: fn@(node_id) -> bool, abbrevs: abbrev_ctxt }; // Compact string representation for ty.t values. API ty_str & parse_from_str. // Extra parameters are for converting to/from def_ids in the string rep. // Whatever format you choose should not contain pipe characters. type ty_abbrev = {pos: uint, len: uint, s: @~str}; enum abbrev_ctxt { ac_no_abbrevs, ac_use_abbrevs(hashmap<ty::t, ty_abbrev>), } fn cx_uses_abbrevs(cx: @ctxt) -> bool { match cx.abbrevs { ac_no_abbrevs => return false, ac_use_abbrevs(_) => return true } } fn enc_ty(w: io::Writer, cx: @ctxt, t: ty::t) { match cx.abbrevs { ac_no_abbrevs => { let result_str = match cx.tcx.short_names_cache.find(t) { Some(s) => *s, None => { let buf = io::mem_buffer(); enc_sty(io::mem_buffer_writer(buf), cx, ty::get(t).struct); cx.tcx.short_names_cache.insert(t, @io::mem_buffer_str(buf)); io::mem_buffer_str(buf) } }; w.write_str(result_str); } ac_use_abbrevs(abbrevs) => { match abbrevs.find(t) { Some(a) => { w.write_str(*a.s); return; } None => { let pos = w.tell(); match ty::type_def_id(t) { Some(def_id) => { // Do not emit node ids that map to unexported names. Those // are not helpful. if def_id.crate != local_crate || cx.reachable(def_id.node) { w.write_char('"'); w.write_str(cx.ds(def_id)); w.write_char('|'); } } _ => {} } enc_sty(w, cx, ty::get(t).struct); let end = w.tell(); let len = end - pos; fn estimate_sz(u: uint) -> uint { let mut n = u; let mut len = 0u; while n != 0u { len += 1u; n = n >> 4u; } return len; } let abbrev_len = 3u + estimate_sz(pos) + estimate_sz(len); if abbrev_len < len { // I.e. it's actually an abbreviation. let s = ~"#" + uint::to_str(pos, 16u) + ~":" + uint::to_str(len, 16u) + ~"#"; let a = {pos: pos, len: len, s: @s}; abbrevs.insert(t, a); } return; } } } } } fn enc_mt(w: io::Writer, cx: @ctxt, mt: ty::mt) { match mt.mutbl { m_imm => (), m_mutbl => w.write_char('m'), m_const => w.write_char('?') } enc_ty(w, cx, mt.ty); } fn enc_opt<T>(w: io::Writer, t: Option<T>, enc_f: fn(T)) { match t { None => w.write_char('n'), Some(v) => { w.write_char('s'); enc_f(v); } } } fn enc_substs(w: io::Writer, cx: @ctxt, substs: ty::substs) { do enc_opt(w, substs.self_r) |r| { enc_region(w, cx, r) } do enc_opt(w, substs.self_ty) |t| { enc_ty(w, cx, t) } w.write_char('['); for substs.tps.each |t| { enc_ty(w, cx, t); } w.write_char(']'); } fn enc_region(w: io::Writer, cx: @ctxt, r: ty::region) { match r { ty::re_bound(br) => { w.write_char('b'); enc_bound_region(w, cx, br); } ty::re_free(id, br) => { w.write_char('f'); w.write_char('['); w.write_int(id); w.write_char('|'); enc_bound_region(w, cx, br); w.write_char(']'); } ty::re_scope(nid) => { w.write_char('s'); w.write_int(nid); w.write_char('|'); } ty::re_static => { w.write_char('t'); } ty::re_var(_) => { // these should not crop up after typeck cx.diag.handler().bug(~"Cannot encode region variables"); } } } fn enc_bound_region(w: io::Writer, cx: @ctxt, br: ty::bound_region) { match br { ty::br_self => w.write_char('s'), ty::br_anon(idx) => { w.write_char('a'); w.write_uint(idx); w.write_char('|'); } ty::br_named(s) => { w.write_char('['); w.write_str(cx.tcx.sess.str_of(s)); w.write_char(']') } ty::br_cap_avoid(id, br) => { w.write_char('c'); w.write_int(id); w.write_char('|'); enc_bound_region(w, cx, *br); } } } fn enc_vstore(w: io::Writer, cx: @ctxt, v: ty::vstore) { w.write_char('/'); match v { ty::vstore_fixed(u) => { w.write_uint(u); w.write_char('|'); } ty::vstore_uniq => { w.write_char('~'); } ty::vstore_box => { w.write_char('@'); } ty::vstore_slice(r) => { w.write_char('&'); enc_region(w, cx, r); } } } fn enc_sty(w: io::Writer, cx: @ctxt, st: ty::sty) { match st { ty::ty_nil => w.write_char('n'), ty::ty_bot => w.write_char('z'), ty::ty_bool => w.write_char('b'), ty::ty_int(t) => { match t { ty_i => w.write_char('i'), ty_char => w.write_char('c'), ty_i8 => w.write_str(&"MB"), ty_i16 => w.write_str(&"MW"), ty_i32 => w.write_str(&"ML"), ty_i64 => w.write_str(&"MD") } } ty::ty_uint(t) => { match t { ty_u => w.write_char('u'), ty_u8 => w.write_str(&"Mb"), ty_u16 => w.write_str(&"Mw"), ty_u32 => w.write_str(&"Ml"), ty_u64 => w.write_str(&"Md") } } ty::ty_float(t) => { match t { ty_f => w.write_char('l'), ty_f32 => w.write_str(&"Mf"), ty_f64 => w.write_str(&"MF"), } } ty::ty_enum(def, substs) => { w.write_str(&"t["); w.write_str(cx.ds(def)); w.write_char('|'); enc_substs(w, cx, substs); w.write_char(']'); } ty::ty_trait(def, substs, vstore) => { w.write_str(&"x["); w.write_str(cx.ds(def)); w.write_char('|'); enc_substs(w, cx, substs); enc_vstore(w, cx, vstore); w.write_char(']'); } ty::ty_tup(ts) => { w.write_str(&"T["); for ts.each |t| { enc_ty(w, cx, t); } w.write_char(']'); } ty::ty_box(mt) => { w.write_char('@'); enc_mt(w, cx, mt); } ty::ty_uniq(mt) => { w.write_char('~'); enc_mt(w, cx, mt); } ty::ty_ptr(mt) => { w.write_char('*'); enc_mt(w, cx, mt); } ty::ty_rptr(r, mt) => { w.write_char('&'); enc_region(w, cx, r); enc_mt(w, cx, mt); } ty::ty_evec(mt, v) => { w.write_char('V'); enc_mt(w, cx, mt); enc_vstore(w, cx, v); } ty::ty_estr(v) => { w.write_char('v'); enc_vstore(w, cx, v); } ty::ty_unboxed_vec(mt) => { w.write_char('U'); enc_mt(w, cx, mt); } ty::ty_rec(fields) => { w.write_str(&"R["); for fields.each |field| { w.write_str(cx.tcx.sess.str_of(field.ident)); w.write_char('='); enc_mt(w, cx, field.mt); } w.write_char(']'); } ty::ty_fn(f) => { enc_ty_fn(w, cx, f); } ty::ty_infer(ty::TyVar(id)) => { w.write_char('X'); w.write_uint(id.to_uint()); } ty::ty_infer(ty::IntVar(id)) => { w.write_char('X'); w.write_char('I'); w.write_uint(id.to_uint()); } ty::ty_param({idx: id, def_id: did}) => { w.write_char('p'); w.write_str(cx.ds(did)); w.write_char('|'); w.write_str(uint::str(id)); } ty::ty_self => { w.write_char('s'); } ty::ty_type => w.write_char('Y'), ty::ty_opaque_closure_ptr(ty::ck_block) => w.write_str(&"C&"), ty::ty_opaque_closure_ptr(ty::ck_box) => w.write_str(&"C@"), ty::ty_opaque_closure_ptr(ty::ck_uniq) => w.write_str(&"C~"), ty::ty_opaque_box => w.write_char('B'), ty::ty_class(def, substs) => { debug!("~~~~ %s", ~"a["); w.write_str(&"a["); let s = cx.ds(def); debug!("~~~~ %s", s); w.write_str(s); debug!("~~~~ %s", ~"|"); w.write_char('|'); enc_substs(w, cx, substs); debug!("~~~~ %s", ~"]"); w.write_char(']'); } } } fn enc_proto(w: io::Writer, cx: @ctxt, proto: ty::fn_proto) { w.write_str(&"f"); match proto { ty::proto_bare => w.write_str(&"n"), ty::proto_vstore(vstore) => { w.write_str(&"v"); enc_vstore(w, cx, vstore); } } } fn enc_mode(w: io::Writer, cx: @ctxt, m: mode) { match ty::resolved_mode(cx.tcx, m) { by_mutbl_ref => w.write_char('&'), by_move => w.write_char('-'), by_copy => w.write_char('+'), by_ref => w.write_char('='), by_val => w.write_char('#') } } fn enc_purity(w: io::Writer, p: purity) { match p { pure_fn => w.write_char('p'), impure_fn => w.write_char('i'), unsafe_fn => w.write_char('u'), extern_fn => w.write_char('c') } } fn enc_ty_fn(w: io::Writer, cx: @ctxt, ft: ty::FnTy) { enc_proto(w, cx, ft.meta.proto); enc_purity(w, ft.meta.purity); enc_bounds(w, cx, ft.meta.bounds); w.write_char('['); for ft.sig.inputs.each |arg| { enc_mode(w, cx, arg.mode); enc_ty(w, cx, arg.ty); } w.write_char(']'); match ft.meta.ret_style { noreturn => w.write_char('!'), _ => enc_ty(w, cx, ft.sig.output) } } fn enc_bounds(w: io::Writer, cx: @ctxt, bs: @~[ty::param_bound]) { for vec::each(*bs) |bound| { match bound { ty::bound_send => w.write_char('S'), ty::bound_copy => w.write_char('C'), ty::bound_const => w.write_char('K'), ty::bound_owned => w.write_char('O'), ty::bound_trait(tp) => { w.write_char('I'); enc_ty(w, cx, tp); } } } w.write_char('.'); } // // Local Variables: // mode: rust // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // End: //
27.57772
78
0.480319
1e0c11641f9a4e4a15f3d9e1f389560f75cd4815
35,426
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. //! Contains file writer API, and provides methods to write row groups and columns by //! using row group writers and column writers respectively. use std::{ fs::File, io::{Seek, SeekFrom, Write}, rc::Rc, }; use byteorder::{ByteOrder, LittleEndian}; use parquet_format as parquet; use thrift::protocol::{TCompactOutputProtocol, TOutputProtocol}; use crate::parquet::basic::PageType; use crate::parquet::column::{ page::{CompressedPage, Page, PageWriteSpec, PageWriter}, writer::{get_column_writer, ColumnWriter}, }; use crate::parquet::errors::{ParquetError, Result}; use crate::parquet::file::{ metadata::*, properties::WriterPropertiesPtr, statistics::to_thrift as statistics_to_thrift, FOOTER_SIZE, PARQUET_MAGIC, }; use crate::parquet::schema::types::{self, SchemaDescPtr, SchemaDescriptor, TypePtr}; use crate::parquet::util::io::{FileSink, Position}; // ---------------------------------------------------------------------- // APIs for file & row group writers /// Parquet file writer API. /// Provides methods to write row groups sequentially. /// /// The main workflow should be as following: /// - Create file writer, this will open a new file and potentially write some metadata. /// - Request a new row group writer by calling `next_row_group`. /// - Once finished writing row group, close row group writer by passing it into /// `close_row_group` method - this will finalise row group metadata and update metrics. /// - Write subsequent row groups, if necessary. /// - After all row groups have been written, close the file writer using `close` method. pub trait FileWriter { /// Creates new row group from this file writer. /// In case of IO error or Thrift error, returns `Err`. /// /// There is no limit on a number of row groups in a file; however, row groups have /// to be written sequentially. Every time the next row group is requested, the /// previous row group must be finalised and closed using `close_row_group` method. fn next_row_group(&mut self) -> Result<Box<RowGroupWriter>>; /// Finalises and closes row group that was created using `next_row_group` method. /// After calling this method, the next row group is available for writes. fn close_row_group(&mut self, row_group_writer: Box<RowGroupWriter>) -> Result<()>; /// Closes and finalises file writer. /// /// All row groups must be appended before this method is called. /// No writes are allowed after this point. /// /// Can be called multiple times. It is up to implementation to either result in no-op, /// or return an `Err` for subsequent calls. fn close(&mut self) -> Result<()>; } /// Parquet row group writer API. /// Provides methods to access column writers in an iterator-like fashion, order is /// guaranteed to match the order of schema leaves (column descriptors). /// /// All columns should be written sequentially; the main workflow is: /// - Request the next column using `next_column` method - this will return `None` if no /// more columns are available to write. /// - Once done writing a column, close column writer with `close_column` method - this /// will finalise column chunk metadata and update row group metrics. /// - Once all columns have been written, close row group writer with `close` method - /// it will return row group metadata and is no-op on already closed row group. pub trait RowGroupWriter { /// Returns the next column writer, if available; otherwise returns `None`. /// In case of any IO error or Thrift error, or if row group writer has already been /// closed returns `Err`. /// /// To request the next column writer, the previous one must be finalised and closed /// using `close_column`. fn next_column(&mut self) -> Result<Option<ColumnWriter>>; /// Closes column writer that was created using `next_column` method. /// This should be called before requesting the next column writer. fn close_column(&mut self, column_writer: ColumnWriter) -> Result<()>; /// Closes this row group writer and returns row group metadata. /// After calling this method row group writer must not be used. /// /// It is recommended to call this method before requesting another row group, but it /// will be closed automatically before returning a new row group. /// /// Can be called multiple times. In subsequent calls will result in no-op and return /// already created row group metadata. fn close(&mut self) -> Result<RowGroupMetaDataPtr>; } // ---------------------------------------------------------------------- // Serialized impl for file & row group writers /// A serialized implementation for Parquet [`FileWriter`]. /// See documentation on file writer for more information. pub struct SerializedFileWriter { file: File, schema: TypePtr, descr: SchemaDescPtr, props: WriterPropertiesPtr, total_num_rows: u64, row_groups: Vec<RowGroupMetaDataPtr>, previous_writer_closed: bool, is_closed: bool, } impl SerializedFileWriter { /// Creates new file writer. pub fn new(mut file: File, schema: TypePtr, properties: WriterPropertiesPtr) -> Result<Self> { Self::start_file(&mut file)?; Ok(Self { file, schema: schema.clone(), descr: Rc::new(SchemaDescriptor::new(schema)), props: properties, total_num_rows: 0, row_groups: Vec::new(), previous_writer_closed: true, is_closed: false, }) } /// Writes magic bytes at the beginning of the file. fn start_file(file: &mut File) -> Result<()> { file.write(&PARQUET_MAGIC)?; Ok(()) } /// Finalises active row group writer, otherwise no-op. fn finalise_row_group_writer( &mut self, mut row_group_writer: Box<RowGroupWriter>, ) -> Result<()> { let row_group_metadata = row_group_writer.close()?; self.row_groups.push(row_group_metadata); Ok(()) } /// Assembles and writes metadata at the end of the file. fn write_metadata(&mut self) -> Result<()> { let file_metadata = parquet::FileMetaData { version: self.props.writer_version().as_num(), schema: types::to_thrift(self.schema.as_ref())?, num_rows: self.total_num_rows as i64, row_groups: self .row_groups .as_slice() .into_iter() .map(|v| v.to_thrift()) .collect(), key_value_metadata: None, created_by: Some(self.props.created_by().to_owned()), column_orders: None, }; // Write file metadata let start_pos = self.file.seek(SeekFrom::Current(0))?; { let mut protocol = TCompactOutputProtocol::new(&mut self.file); file_metadata.write_to_out_protocol(&mut protocol)?; protocol.flush()?; } let end_pos = self.file.seek(SeekFrom::Current(0))?; // Write footer let mut footer_buffer: [u8; FOOTER_SIZE] = [0; FOOTER_SIZE]; let metadata_len = (end_pos - start_pos) as i32; LittleEndian::write_i32(&mut footer_buffer, metadata_len); (&mut footer_buffer[4..]).write(&PARQUET_MAGIC)?; self.file.write(&footer_buffer)?; Ok(()) } #[inline] fn assert_closed(&self) -> Result<()> { if self.is_closed { Err(general_err!("File writer is closed")) } else { Ok(()) } } #[inline] fn assert_previous_writer_closed(&self) -> Result<()> { if !self.previous_writer_closed { Err(general_err!("Previous row group writer was not closed")) } else { Ok(()) } } } impl FileWriter for SerializedFileWriter { #[inline] fn next_row_group(&mut self) -> Result<Box<RowGroupWriter>> { self.assert_closed()?; self.assert_previous_writer_closed()?; let row_group_writer = SerializedRowGroupWriter::new(self.descr.clone(), self.props.clone(), &self.file); self.previous_writer_closed = false; Ok(Box::new(row_group_writer)) } #[inline] fn close_row_group(&mut self, row_group_writer: Box<RowGroupWriter>) -> Result<()> { self.assert_closed()?; let res = self.finalise_row_group_writer(row_group_writer); self.previous_writer_closed = res.is_ok(); res } #[inline] fn close(&mut self) -> Result<()> { self.assert_closed()?; self.assert_previous_writer_closed()?; self.write_metadata()?; self.is_closed = true; Ok(()) } } /// A serialized implementation for Parquet [`RowGroupWriter`]. /// Coordinates writing of a row group with column writers. /// See documentation on row group writer for more information. pub struct SerializedRowGroupWriter { descr: SchemaDescPtr, props: WriterPropertiesPtr, file: File, total_rows_written: Option<u64>, total_bytes_written: u64, column_index: usize, previous_writer_closed: bool, row_group_metadata: Option<RowGroupMetaDataPtr>, column_chunks: Vec<ColumnChunkMetaDataPtr>, } impl SerializedRowGroupWriter { pub fn new(schema_descr: SchemaDescPtr, properties: WriterPropertiesPtr, file: &File) -> Self { let num_columns = schema_descr.num_columns(); Self { descr: schema_descr, props: properties, file: file.try_clone().unwrap(), total_rows_written: None, total_bytes_written: 0, column_index: 0, previous_writer_closed: true, row_group_metadata: None, column_chunks: Vec::with_capacity(num_columns), } } /// Checks and finalises current column writer. fn finalise_column_writer(&mut self, writer: ColumnWriter) -> Result<()> { let (bytes_written, rows_written, metadata) = match writer { ColumnWriter::BoolColumnWriter(typed) => typed.close()?, ColumnWriter::Int32ColumnWriter(typed) => typed.close()?, ColumnWriter::Int64ColumnWriter(typed) => typed.close()?, ColumnWriter::Int96ColumnWriter(typed) => typed.close()?, ColumnWriter::FloatColumnWriter(typed) => typed.close()?, ColumnWriter::DoubleColumnWriter(typed) => typed.close()?, ColumnWriter::ByteArrayColumnWriter(typed) => typed.close()?, ColumnWriter::FixedLenByteArrayColumnWriter(typed) => typed.close()?, }; // Update row group writer metrics self.total_bytes_written += bytes_written; self.column_chunks.push(Rc::new(metadata)); if let Some(rows) = self.total_rows_written { if rows != rows_written { return Err(general_err!( "Incorrect number of rows, expected {} != {} rows", rows, rows_written )); } } else { self.total_rows_written = Some(rows_written); } Ok(()) } #[inline] fn assert_closed(&self) -> Result<()> { if self.row_group_metadata.is_some() { Err(general_err!("Row group writer is closed")) } else { Ok(()) } } #[inline] fn assert_previous_writer_closed(&self) -> Result<()> { if !self.previous_writer_closed { Err(general_err!("Previous column writer was not closed")) } else { Ok(()) } } } impl RowGroupWriter for SerializedRowGroupWriter { #[inline] fn next_column(&mut self) -> Result<Option<ColumnWriter>> { self.assert_closed()?; self.assert_previous_writer_closed()?; if self.column_index >= self.descr.num_columns() { return Ok(None); } let sink = FileSink::new(&self.file); let page_writer = Box::new(SerializedPageWriter::new(sink)); let column_writer = get_column_writer( self.descr.column(self.column_index), self.props.clone(), page_writer, ); self.column_index += 1; self.previous_writer_closed = false; Ok(Some(column_writer)) } #[inline] fn close_column(&mut self, column_writer: ColumnWriter) -> Result<()> { let res = self.finalise_column_writer(column_writer); self.previous_writer_closed = res.is_ok(); res } #[inline] fn close(&mut self) -> Result<RowGroupMetaDataPtr> { if self.row_group_metadata.is_none() { self.assert_previous_writer_closed()?; let row_group_metadata = RowGroupMetaData::builder(self.descr.clone()) .set_column_metadata(self.column_chunks.clone()) .set_total_byte_size(self.total_bytes_written as i64) .set_num_rows(self.total_rows_written.unwrap_or(0) as i64) .build()?; self.row_group_metadata = Some(Rc::new(row_group_metadata)); } let metadata = self.row_group_metadata.as_ref().unwrap().clone(); Ok(metadata) } } /// A serialized implementation for Parquet [`PageWriter`]. /// Writes and serializes pages and metadata into output stream. /// /// `SerializedPageWriter` should not be used after calling `close()`. pub struct SerializedPageWriter<T: Write + Position> { sink: T, } impl<T: Write + Position> SerializedPageWriter<T> { /// Creates new page writer. pub fn new(sink: T) -> Self { Self { sink } } /// Serializes page header into Thrift. /// Returns number of bytes that have been written into the sink. #[inline] fn serialize_page_header(&mut self, header: parquet::PageHeader) -> Result<usize> { let start_pos = self.sink.pos(); { let mut protocol = TCompactOutputProtocol::new(&mut self.sink); header.write_to_out_protocol(&mut protocol)?; protocol.flush()?; } Ok((self.sink.pos() - start_pos) as usize) } /// Serializes column chunk into Thrift. /// Returns Ok() if there are not errors serializing and writing data into the sink. #[inline] fn serialize_column_chunk(&mut self, chunk: parquet::ColumnChunk) -> Result<()> { let mut protocol = TCompactOutputProtocol::new(&mut self.sink); chunk.write_to_out_protocol(&mut protocol)?; protocol.flush()?; Ok(()) } } impl<T: Write + Position> PageWriter for SerializedPageWriter<T> { fn write_page(&mut self, page: CompressedPage) -> Result<PageWriteSpec> { let uncompressed_size = page.uncompressed_size(); let compressed_size = page.compressed_size(); let num_values = page.num_values(); let encoding = page.encoding(); let page_type = page.page_type(); let mut page_header = parquet::PageHeader { type_: page_type.into(), uncompressed_page_size: uncompressed_size as i32, compressed_page_size: compressed_size as i32, // TODO: Add support for crc checksum crc: None, data_page_header: None, index_page_header: None, dictionary_page_header: None, data_page_header_v2: None, }; match page.compressed_page() { &Page::DataPage { def_level_encoding, rep_level_encoding, ref statistics, .. } => { let data_page_header = parquet::DataPageHeader { num_values: num_values as i32, encoding: encoding.into(), definition_level_encoding: def_level_encoding.into(), repetition_level_encoding: rep_level_encoding.into(), statistics: statistics_to_thrift(statistics.as_ref()), }; page_header.data_page_header = Some(data_page_header); } &Page::DataPageV2 { num_nulls, num_rows, def_levels_byte_len, rep_levels_byte_len, is_compressed, ref statistics, .. } => { let data_page_header_v2 = parquet::DataPageHeaderV2 { num_values: num_values as i32, num_nulls: num_nulls as i32, num_rows: num_rows as i32, encoding: encoding.into(), definition_levels_byte_length: def_levels_byte_len as i32, repetition_levels_byte_length: rep_levels_byte_len as i32, is_compressed: Some(is_compressed), statistics: statistics_to_thrift(statistics.as_ref()), }; page_header.data_page_header_v2 = Some(data_page_header_v2); } &Page::DictionaryPage { is_sorted, .. } => { let dictionary_page_header = parquet::DictionaryPageHeader { num_values: num_values as i32, encoding: encoding.into(), is_sorted: Some(is_sorted), }; page_header.dictionary_page_header = Some(dictionary_page_header); } } let start_pos = self.sink.pos(); let header_size = self.serialize_page_header(page_header)?; self.sink.write_all(page.data())?; let mut spec = PageWriteSpec::new(); spec.page_type = page_type; spec.uncompressed_size = uncompressed_size + header_size; spec.compressed_size = compressed_size + header_size; spec.offset = start_pos; spec.bytes_written = self.sink.pos() - start_pos; // Number of values is incremented for data pages only if page_type == PageType::DATA_PAGE || page_type == PageType::DATA_PAGE_V2 { spec.num_values = num_values; } Ok(spec) } fn write_metadata(&mut self, metadata: &ColumnChunkMetaData) -> Result<()> { self.serialize_column_chunk(metadata.to_thrift()) } fn close(&mut self) -> Result<()> { self.sink.flush()?; Ok(()) } } #[cfg(test)] mod tests { use super::*; use std::{error::Error, io::Cursor}; use crate::parquet::basic::{Compression, Encoding, Repetition, Type}; use crate::parquet::column::page::PageReader; use crate::parquet::compression::{create_codec, Codec}; use crate::parquet::file::{ properties::WriterProperties, reader::{FileReader, SerializedFileReader, SerializedPageReader}, statistics::{from_thrift, to_thrift, Statistics}, }; use crate::parquet::record::RowAccessor; use crate::parquet::util::{memory::ByteBufferPtr, test_common::get_temp_file}; #[test] fn test_file_writer_error_after_close() { let file = get_temp_file("test_file_writer_error_after_close", &[]); let schema = Rc::new(types::Type::group_type_builder("schema").build().unwrap()); let props = Rc::new(WriterProperties::builder().build()); let mut writer = SerializedFileWriter::new(file, schema, props).unwrap(); writer.close().unwrap(); { let res = writer.next_row_group(); assert!(res.is_err()); if let Err(err) = res { assert_eq!(err.description(), "File writer is closed"); } } { let res = writer.close(); assert!(res.is_err()); if let Err(err) = res { assert_eq!(err.description(), "File writer is closed"); } } } #[test] fn test_row_group_writer_error_after_close() { let file = get_temp_file("test_file_writer_row_group_error_after_close", &[]); let schema = Rc::new(types::Type::group_type_builder("schema").build().unwrap()); let props = Rc::new(WriterProperties::builder().build()); let mut writer = SerializedFileWriter::new(file, schema, props).unwrap(); let mut row_group_writer = writer.next_row_group().unwrap(); row_group_writer.close().unwrap(); let res = row_group_writer.next_column(); assert!(res.is_err()); if let Err(err) = res { assert_eq!(err.description(), "Row group writer is closed"); } } #[test] fn test_row_group_writer_error_not_all_columns_written() { let file = get_temp_file("test_row_group_writer_error_not_all_columns_written", &[]); let schema = Rc::new( types::Type::group_type_builder("schema") .with_fields(&mut vec![Rc::new( types::Type::primitive_type_builder("col1", Type::INT32) .build() .unwrap(), )]) .build() .unwrap(), ); let props = Rc::new(WriterProperties::builder().build()); let mut writer = SerializedFileWriter::new(file, schema, props).unwrap(); let mut row_group_writer = writer.next_row_group().unwrap(); let res = row_group_writer.close(); assert!(res.is_err()); if let Err(err) = res { assert_eq!(err.description(), "Column length mismatch: 1 != 0"); } } #[test] fn test_row_group_writer_num_records_mismatch() { let file = get_temp_file("test_row_group_writer_num_records_mismatch", &[]); let schema = Rc::new( types::Type::group_type_builder("schema") .with_fields(&mut vec![ Rc::new( types::Type::primitive_type_builder("col1", Type::INT32) .with_repetition(Repetition::REQUIRED) .build() .unwrap(), ), Rc::new( types::Type::primitive_type_builder("col2", Type::INT32) .with_repetition(Repetition::REQUIRED) .build() .unwrap(), ), ]) .build() .unwrap(), ); let props = Rc::new(WriterProperties::builder().build()); let mut writer = SerializedFileWriter::new(file, schema, props).unwrap(); let mut row_group_writer = writer.next_row_group().unwrap(); let mut col_writer = row_group_writer.next_column().unwrap().unwrap(); if let ColumnWriter::Int32ColumnWriter(ref mut typed) = col_writer { typed.write_batch(&[1, 2, 3], None, None).unwrap(); } row_group_writer.close_column(col_writer).unwrap(); let mut col_writer = row_group_writer.next_column().unwrap().unwrap(); if let ColumnWriter::Int32ColumnWriter(ref mut typed) = col_writer { typed.write_batch(&[1, 2], None, None).unwrap(); } let res = row_group_writer.close_column(col_writer); assert!(res.is_err()); if let Err(err) = res { assert_eq!( err.description(), "Incorrect number of rows, expected 3 != 2 rows" ); } } #[test] fn test_file_writer_empty_file() { let file = get_temp_file("test_file_writer_write_empty_file", &[]); let schema = Rc::new( types::Type::group_type_builder("schema") .with_fields(&mut vec![Rc::new( types::Type::primitive_type_builder("col1", Type::INT32) .build() .unwrap(), )]) .build() .unwrap(), ); let props = Rc::new(WriterProperties::builder().build()); let mut writer = SerializedFileWriter::new(file.try_clone().unwrap(), schema, props).unwrap(); writer.close().unwrap(); let reader = SerializedFileReader::new(file).unwrap(); assert_eq!(reader.get_row_iter(None).unwrap().count(), 0); } #[test] fn test_file_writer_empty_row_groups() { let file = get_temp_file("test_file_writer_write_empty_row_groups", &[]); test_file_roundtrip(file, vec![]); } #[test] fn test_file_writer_single_row_group() { let file = get_temp_file("test_file_writer_write_single_row_group", &[]); test_file_roundtrip(file, vec![vec![1, 2, 3, 4, 5]]); } #[test] fn test_file_writer_multiple_row_groups() { let file = get_temp_file("test_file_writer_write_multiple_row_groups", &[]); test_file_roundtrip( file, vec![ vec![1, 2, 3, 4, 5], vec![1, 2, 3], vec![1], vec![1, 2, 3, 4, 5, 6], ], ); } #[test] fn test_file_writer_multiple_large_row_groups() { let file = get_temp_file("test_file_writer_multiple_large_row_groups", &[]); test_file_roundtrip( file, vec![vec![123; 1024], vec![124; 1000], vec![125; 15], vec![]], ); } #[test] fn test_page_writer_data_pages() { let pages = vec![ Page::DataPage { buf: ByteBufferPtr::new(vec![1, 2, 3, 4, 5, 6, 7, 8]), num_values: 10, encoding: Encoding::DELTA_BINARY_PACKED, def_level_encoding: Encoding::RLE, rep_level_encoding: Encoding::RLE, statistics: Some(Statistics::int32(Some(1), Some(3), None, 7, true)), }, Page::DataPageV2 { buf: ByteBufferPtr::new(vec![4; 128]), num_values: 10, encoding: Encoding::DELTA_BINARY_PACKED, num_nulls: 2, num_rows: 12, def_levels_byte_len: 24, rep_levels_byte_len: 32, is_compressed: false, statistics: Some(Statistics::int32(Some(1), Some(3), None, 7, true)), }, ]; test_page_roundtrip(&pages[..], Compression::SNAPPY, Type::INT32); test_page_roundtrip(&pages[..], Compression::UNCOMPRESSED, Type::INT32); } #[test] fn test_page_writer_dict_pages() { let pages = vec![ Page::DictionaryPage { buf: ByteBufferPtr::new(vec![1, 2, 3, 4, 5]), num_values: 5, encoding: Encoding::RLE_DICTIONARY, is_sorted: false, }, Page::DataPage { buf: ByteBufferPtr::new(vec![1, 2, 3, 4, 5, 6, 7, 8]), num_values: 10, encoding: Encoding::DELTA_BINARY_PACKED, def_level_encoding: Encoding::RLE, rep_level_encoding: Encoding::RLE, statistics: Some(Statistics::int32(Some(1), Some(3), None, 7, true)), }, Page::DataPageV2 { buf: ByteBufferPtr::new(vec![4; 128]), num_values: 10, encoding: Encoding::DELTA_BINARY_PACKED, num_nulls: 2, num_rows: 12, def_levels_byte_len: 24, rep_levels_byte_len: 32, is_compressed: false, statistics: None, }, ]; test_page_roundtrip(&pages[..], Compression::SNAPPY, Type::INT32); test_page_roundtrip(&pages[..], Compression::UNCOMPRESSED, Type::INT32); } /// Tests writing and reading pages. /// Physical type is for statistics only, should match any defined statistics type in /// pages. fn test_page_roundtrip(pages: &[Page], codec: Compression, physical_type: Type) { let mut compressed_pages = vec![]; let mut total_num_values = 0i64; let mut compressor = create_codec(codec).unwrap(); for page in pages { let uncompressed_len = page.buffer().len(); let compressed_page = match page { &Page::DataPage { ref buf, num_values, encoding, def_level_encoding, rep_level_encoding, ref statistics, } => { total_num_values += num_values as i64; let output_buf = compress_helper(compressor.as_mut(), buf.data()); Page::DataPage { buf: ByteBufferPtr::new(output_buf), num_values, encoding, def_level_encoding, rep_level_encoding, statistics: from_thrift(physical_type, to_thrift(statistics.as_ref())), } } &Page::DataPageV2 { ref buf, num_values, encoding, num_nulls, num_rows, def_levels_byte_len, rep_levels_byte_len, ref statistics, .. } => { total_num_values += num_values as i64; let offset = (def_levels_byte_len + rep_levels_byte_len) as usize; let cmp_buf = compress_helper(compressor.as_mut(), &buf.data()[offset..]); let mut output_buf = Vec::from(&buf.data()[..offset]); output_buf.extend_from_slice(&cmp_buf[..]); Page::DataPageV2 { buf: ByteBufferPtr::new(output_buf), num_values, encoding, num_nulls, num_rows, def_levels_byte_len, rep_levels_byte_len, is_compressed: compressor.is_some(), statistics: from_thrift(physical_type, to_thrift(statistics.as_ref())), } } &Page::DictionaryPage { ref buf, num_values, encoding, is_sorted, } => { let output_buf = compress_helper(compressor.as_mut(), buf.data()); Page::DictionaryPage { buf: ByteBufferPtr::new(output_buf), num_values, encoding, is_sorted, } } }; let compressed_page = CompressedPage::new(compressed_page, uncompressed_len); compressed_pages.push(compressed_page); } let mut buffer: Vec<u8> = vec![]; let mut result_pages: Vec<Page> = vec![]; { let cursor = Cursor::new(&mut buffer); let mut page_writer = SerializedPageWriter::new(cursor); for page in compressed_pages { page_writer.write_page(page).unwrap(); } page_writer.close().unwrap(); } { let mut page_reader = SerializedPageReader::new( Cursor::new(&buffer), total_num_values, codec, physical_type, ) .unwrap(); while let Some(page) = page_reader.get_next_page().unwrap() { result_pages.push(page); } } assert_eq!(result_pages.len(), pages.len()); for i in 0..result_pages.len() { assert_page(&result_pages[i], &pages[i]); } } /// Helper function to compress a slice fn compress_helper(compressor: Option<&mut Box<Codec>>, data: &[u8]) -> Vec<u8> { let mut output_buf = vec![]; if let Some(cmpr) = compressor { cmpr.compress(data, &mut output_buf).unwrap(); } else { output_buf.extend_from_slice(data); } output_buf } /// Check if pages match. fn assert_page(left: &Page, right: &Page) { assert_eq!(left.page_type(), right.page_type()); assert_eq!(left.buffer().data(), right.buffer().data()); assert_eq!(left.num_values(), right.num_values()); assert_eq!(left.encoding(), right.encoding()); assert_eq!(to_thrift(left.statistics()), to_thrift(right.statistics())); } /// File write-read roundtrip. /// `data` consists of arrays of values for each row group. fn test_file_roundtrip(file: File, data: Vec<Vec<i32>>) { let schema = Rc::new( types::Type::group_type_builder("schema") .with_fields(&mut vec![Rc::new( types::Type::primitive_type_builder("col1", Type::INT32) .with_repetition(Repetition::REQUIRED) .build() .unwrap(), )]) .build() .unwrap(), ); let props = Rc::new(WriterProperties::builder().build()); let mut file_writer = SerializedFileWriter::new(file.try_clone().unwrap(), schema, props).unwrap(); for subset in &data { let mut row_group_writer = file_writer.next_row_group().unwrap(); let col_writer = row_group_writer.next_column().unwrap(); if let Some(mut writer) = col_writer { match writer { ColumnWriter::Int32ColumnWriter(ref mut typed) => { typed.write_batch(&subset[..], None, None).unwrap(); } _ => { unimplemented!(); } } row_group_writer.close_column(writer).unwrap(); } file_writer.close_row_group(row_group_writer).unwrap(); } file_writer.close().unwrap(); let reader = SerializedFileReader::new(file).unwrap(); assert_eq!(reader.num_row_groups(), data.len()); for i in 0..reader.num_row_groups() { let row_group_reader = reader.get_row_group(i).unwrap(); let iter = row_group_reader.get_row_iter(None).unwrap(); let res = iter .map(|elem| elem.get_int(0).unwrap()) .collect::<Vec<i32>>(); assert_eq!(res, data[i]); } } }
37.807898
99
0.571332
f5417dbf32f61bcc146e1cb200210626aa34663c
11,561
pub mod convert; use std::fmt; use proc_macro2::TokenStream; use quote::{ToTokens, TokenStreamExt}; use syn::{ ext::IdentExt, parenthesized, parse::{Parse, ParseStream}, punctuated::Punctuated, token::{Let, Match, Paren}, LitStr, Token, }; pub type Epsilon = Token![_]; pub type Ident = syn::Ident; pub type Literal = LitStr; #[derive(Clone)] pub struct Fix { bang_token: Token![!], pub expr: Box<Term>, } impl ToTokens for Fix { fn to_tokens(&self, tokens: &mut TokenStream) { self.bang_token.to_tokens(tokens); self.expr.to_tokens(tokens); } } impl Parse for Fix { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let bang_token = input.parse()?; let expr = input.parse()?; Ok(Self { bang_token, expr }) } } impl fmt::Debug for Fix { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Fix").field("expr", &self.expr).finish() } } #[derive(Clone)] pub struct ParenExpression { paren_token: Paren, pub expr: Expression, } impl ToTokens for ParenExpression { fn to_tokens(&self, tokens: &mut TokenStream) { self.paren_token.surround(tokens, |tokens| self.expr.to_tokens(tokens)) } } impl Parse for ParenExpression { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let expr; let paren_token = parenthesized!(expr in input); let expr = expr.parse()?; Ok(Self { paren_token, expr }) } } impl fmt::Debug for ParenExpression { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ParenExpression") .field("expr", &self.expr) .finish() } } #[derive(Clone)] pub enum Term { Epsilon(Epsilon), Ident(Ident), Literal(Literal), Fix(Fix), Parens(ParenExpression), } impl ToTokens for Term { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::Epsilon(e) => e.to_tokens(tokens), Self::Ident(i) => i.to_tokens(tokens), Self::Literal(l) => l.to_tokens(tokens), Self::Fix(f) => f.to_tokens(tokens), Self::Parens(p) => p.to_tokens(tokens), } } } impl Parse for Term { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(Token![_]) { input.parse().map(Self::Epsilon) } else if lookahead.peek(LitStr) { input.parse().map(Self::Literal) } else if lookahead.peek(Token![!]) { input.parse().map(Self::Fix) } else if lookahead.peek(Paren) { input.parse().map(Self::Parens) } else if lookahead.peek(Ident::peek_any) { input.call(Ident::parse_any).map(Self::Ident) } else { Err(lookahead.error()) } } } impl fmt::Debug for Term { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Term::Epsilon(_) => write!(f, "Term::Epsilon"), Term::Ident(i) => write!(f, "Term::Ident({:?})", i), Term::Literal(l) => write!(f, "Term::Literal({:?})", l.value()), Term::Fix(x) => write!(f, "Term::Fix({:?})", x), Term::Parens(p) => write!(f, "Term::Parens({:?})", p), } } } #[derive(Clone, Debug)] pub struct Call(pub Vec<Term>); impl ToTokens for Call { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(&self.0) } } impl Parse for Call { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let mut out = vec![input.parse()?]; loop { let lookahead = input.lookahead1(); if lookahead.peek(Token![_]) || lookahead.peek(LitStr) || lookahead.peek(Token![!]) || lookahead.peek(Paren) || lookahead.peek(Ident::peek_any) { out.push(input.parse()?); } else { break; } } Ok(Self(out)) } } #[derive(Clone)] pub struct Cat(pub Punctuated<Call, Token![.]>); impl ToTokens for Cat { fn to_tokens(&self, tokens: &mut TokenStream) { self.0.to_tokens(tokens) } } impl Parse for Cat { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { input.call(Punctuated::parse_separated_nonempty).map(Self) } } impl fmt::Debug for Cat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Cat")?; f.debug_list().entries(&self.0).finish() } } #[derive(Clone)] pub struct Label { colon_tok: Token![:], pub label: Ident, } impl ToTokens for Label { fn to_tokens(&self, tokens: &mut TokenStream) { self.colon_tok.to_tokens(tokens); self.label.to_tokens(tokens); } } impl Parse for Label { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let colon_tok = input.parse()?; let label = input.call(Ident::parse_any)?; Ok(Self { colon_tok, label }) } } impl fmt::Debug for Label { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Label").field("label", &self.label).finish() } } #[derive(Clone, Debug)] pub struct Labelled { pub cat: Cat, pub label: Option<Label>, } impl ToTokens for Labelled { fn to_tokens(&self, tokens: &mut TokenStream) { self.cat.to_tokens(tokens); if let Some(label) = &self.label { label.to_tokens(tokens); } } } impl Parse for Labelled { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let cat = input.parse()?; let label = if input.peek(Token![:]) { Some(input.parse()?) } else { None }; Ok(Self { cat, label }) } } #[derive(Clone)] pub struct Alt(pub Punctuated<Labelled, Token![|]>); impl ToTokens for Alt { fn to_tokens(&self, tokens: &mut TokenStream) { self.0.to_tokens(tokens) } } impl Parse for Alt { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { input.call(Punctuated::parse_separated_nonempty).map(Self) } } impl fmt::Debug for Alt { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Alt")?; f.debug_list().entries(&self.0).finish() } } #[derive(Clone)] pub struct Lambda { slash_tok_left: Token![/], pub args: Vec<Ident>, slash_tok_right: Token![/], pub expr: Alt, } impl ToTokens for Lambda { fn to_tokens(&self, tokens: &mut TokenStream) { self.slash_tok_left.to_tokens(tokens); tokens.append_all(&self.args); self.slash_tok_right.to_tokens(tokens); self.expr.to_tokens(tokens); } } impl Parse for Lambda { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let slash_tok_left = input.parse()?; let mut args = Vec::new(); loop { args.push(input.parse()?); let lookahead = input.lookahead1(); if lookahead.peek(Token![/]) { break; } else if !lookahead.peek(Ident::peek_any) { return Err(lookahead.error()); } } let slash_tok_right = input.parse()?; let expr = input.parse()?; Ok(Self { slash_tok_left, args, slash_tok_right, expr, }) } } impl fmt::Debug for Lambda { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Lambda") .field("args", &self.args) .field("expr", &self.expr) .finish() } } #[derive(Clone, Debug)] pub enum Expression { Alt(Alt), Lambda(Lambda), } impl ToTokens for Expression { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::Alt(a) => a.to_tokens(tokens), Self::Lambda(l) => l.to_tokens(tokens), } } } impl Parse for Expression { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { if input.peek(Token![/]) { input.parse().map(Self::Lambda) } else { input.parse().map(Self::Alt) } } } #[derive(Clone)] pub struct GoalStatement { match_token: Token![match], expr: Expression, semi_token: Token![;], } impl ToTokens for GoalStatement { fn to_tokens(&self, tokens: &mut TokenStream) { self.match_token.to_tokens(tokens); self.expr.to_tokens(tokens); self.semi_token.to_tokens(tokens); } } impl Parse for GoalStatement { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let match_token = input.parse()?; let expr = input.parse()?; let semi_token = input.parse()?; Ok(Self { match_token, expr, semi_token, }) } } impl fmt::Debug for GoalStatement { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("GoalStatement") .field("expr", &self.expr) .finish() } } #[derive(Clone)] pub struct LetStatement { let_token: Token![let], name: Ident, args: Vec<Ident>, eq_token: Token![=], expr: Expression, semi_token: Token![;], next: Box<Statement>, } impl ToTokens for LetStatement { fn to_tokens(&self, tokens: &mut TokenStream) { self.let_token.to_tokens(tokens); self.name.to_tokens(tokens); tokens.append_all(&self.args); self.eq_token.to_tokens(tokens); self.expr.to_tokens(tokens); self.semi_token.to_tokens(tokens); self.next.to_tokens(tokens); } } impl Parse for LetStatement { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let let_token = input.parse()?; let name = input.call(Ident::parse_any)?; let mut args = Vec::new(); loop { let lookahead = input.lookahead1(); if lookahead.peek(Token![=]) { break; } else if lookahead.peek(Ident::peek_any) { args.push(input.parse()?); } else { return Err(lookahead.error()); } } let eq_token = input.parse()?; let expr = input.parse()?; let semi_token = input.parse()?; let next = Box::new(input.parse()?); Ok(Self { let_token, name, args, eq_token, expr, semi_token, next, }) } } impl fmt::Debug for LetStatement { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("LetStatement") .field("name", &self.name) .field("args", &self.args) .field("expr", &self.expr) .field("next", &self.next) .finish() } } #[derive(Clone, Debug)] pub enum Statement { Goal(GoalStatement), Let(LetStatement), } impl ToTokens for Statement { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::Goal(g) => g.to_tokens(tokens), Self::Let(l) => l.to_tokens(tokens), } } } impl Parse for Statement { fn parse(input: ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(Let) { input.parse().map(Self::Let) } else if lookahead.peek(Match) { input.parse().map(Self::Goal) } else { Err(lookahead.error()) } } }
24.862366
79
0.549001
7acced20249675ff469713ff2e42f83a473de2b6
26,764
//! This module contains the `CyclesAccountManager` which is responsible for //! updating the cycles account of canisters. //! //! A canister has an associated cycles balance, and may `send` a part of //! this cycles balance to another canister //! In addition to sending cycles to another canister, a canister `spend`s //! cycles in the following three ways: //! a) executing messages, //! b) sending messages to other canisters, //! c) storing data over time/rounds //! Each of the above spending is done in three phases: //! 1. reserving maximum cycles the operation can require //! 2. executing the operation and return `cycles_spent` //! 3. reimburse the canister with `cycles_reserved` - `cycles_spent` use ic_config::subnet_config::CyclesAccountManagerConfig; use ic_interfaces::execution_environment::CanisterOutOfCyclesError; use ic_logger::{info, ReplicaLogger}; use ic_registry_subnet_type::SubnetType; use ic_replicated_state::{CanisterState, SystemState}; use ic_types::{ ic00::{ CanisterIdRecord, InstallCodeArgs, Method, Payload, SetControllerArgs, UpdateSettingsArgs, }, messages::{ is_subnet_message, Request, Response, SignedIngressContent, MAX_INTER_CANISTER_PAYLOAD_IN_BYTES, }, nominal_cycles::NominalCycles, CanisterId, ComputeAllocation, Cycles, MemoryAllocation, NumBytes, NumInstructions, SubnetId, }; use std::{str::FromStr, time::Duration}; /// Errors returned by the [`CyclesAccountManager`]. #[derive(Clone, Debug, PartialEq, Eq)] pub enum CyclesAccountManagerError { /// One of the API contracts that the cycles account manager enforces was /// violated. ContractViolation(String), } impl std::error::Error for CyclesAccountManagerError {} impl std::fmt::Display for CyclesAccountManagerError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { CyclesAccountManagerError::ContractViolation(msg) => { write!(f, "Contract violation: {}", msg) } } } } /// Handles any operation related to cycles accounting, such as charging (due to /// using system resources) or refunding unused cycles. #[derive(Clone, Copy, Debug, PartialEq)] pub struct CyclesAccountManager { /// The maximum allowed instructions to be spent on a single message /// execution. max_num_instructions: NumInstructions, /// The maximum amount of cycles a canister can hold. /// If set to None, the canisters have no upper limit. max_cycles_per_canister: Option<Cycles>, /// The subnet type of this [`CyclesAccountManager`]. own_subnet_type: SubnetType, /// The subnet id of this [`CyclesAccountManager`]. own_subnet_id: SubnetId, /// The configuration of this [`CyclesAccountManager`] controlling the fees /// that are charged for various operations. config: CyclesAccountManagerConfig, } impl CyclesAccountManager { pub fn new( // Note: `max_num_instructions` and `max_cycles_per_canister` are passed from different // Configs max_num_instructions: NumInstructions, max_cycles_per_canister: Option<Cycles>, own_subnet_type: SubnetType, own_subnet_id: SubnetId, config: CyclesAccountManagerConfig, ) -> Self { Self { max_num_instructions, max_cycles_per_canister, own_subnet_type, own_subnet_id, config, } } /// Returns the subnet type of this [`CyclesAccountManager`]. pub fn subnet_type(&self) -> SubnetType { self.own_subnet_type } /// Returns the Subnet Id of this [`CyclesAccountManager`]. pub fn get_subnet_id(&self) -> SubnetId { self.own_subnet_id } //////////////////////////////////////////////////////////////////////////// // // Execution/Computation // //////////////////////////////////////////////////////////////////////////// /// Returns the fee to create a canister in [`Cycles`]. pub fn canister_creation_fee(&self) -> Cycles { self.config.canister_creation_fee } /// Returns the fee for receiving an ingress message in [`Cycles`]. pub fn ingress_message_received_fee(&self) -> Cycles { self.config.ingress_message_reception_fee } /// Returns the fee per byte of ingress message received in [`Cycles`]. pub fn ingress_byte_received_fee(&self) -> Cycles { self.config.ingress_byte_reception_fee } /// Returns the fee for performing a xnet call in [`Cycles`]. pub fn xnet_call_performed_fee(&self) -> Cycles { self.config.xnet_call_fee } /// Returns the fee per byte of transmitted xnet call in [`Cycles`]. pub fn xnet_call_bytes_transmitted_fee(&self, payload_size: NumBytes) -> Cycles { self.config.xnet_byte_transmission_fee * Cycles::from(payload_size.get()) } /// Returns the freezing threshold for this canister in Cycles. pub fn freeze_threshold_cycles( &self, system_state: &SystemState, memory_usage: NumBytes, compute_allocation: ComputeAllocation, ) -> Cycles { let one_gib = 1 << 30; let memory_fee = { let memory = match system_state.memory_allocation { MemoryAllocation::Reserved(bytes) => bytes, MemoryAllocation::BestEffort => memory_usage, }; Cycles::from( (memory.get() as u128 * self.config.gib_storage_per_second_fee.get() * system_state.freeze_threshold.get() as u128) / one_gib, ) }; let compute_fee = { Cycles::from( compute_allocation.as_percent() as u128 * self.config.compute_percent_allocated_per_second_fee.get() * system_state.freeze_threshold.get() as u128, ) }; memory_fee + compute_fee } /// Withdraws `cycles` worth of cycles from the canister's balance. /// /// NOTE: This method is intended for use in inter-canister transfers. /// It doesn't report these cycles as consumed. To withdraw cycles /// and have them reported as consumed, use `consume_cycles`. /// /// # Errors /// /// Returns a `CanisterOutOfCyclesError` if the /// requested amount is greater than the currently available. pub fn withdraw_cycles_for_transfer( &self, system_state: &mut SystemState, canister_current_memory_usage: NumBytes, canister_compute_allocation: ComputeAllocation, cycles: Cycles, ) -> Result<(), CanisterOutOfCyclesError> { let threshold = self.freeze_threshold_cycles( system_state, canister_current_memory_usage, canister_compute_allocation, ); self.withdraw_with_threshold(system_state, cycles, threshold) } /// Withdraws and consumes cycles from the canister's balance. /// /// NOTE: This method reports the cycles withdrawn as consumed (i.e. burnt). /// For withdrawals where cycles are not consumed, such as the case /// for inter-canister transfers, use `withdraw_cycles_for_transfer`. /// /// # Errors /// /// Returns a `CanisterOutOfCyclesError` if the /// requested amount is greater than the currently available. pub fn consume_cycles( &self, system_state: &mut SystemState, canister_current_memory_usage: NumBytes, canister_compute_allocation: ComputeAllocation, cycles: Cycles, ) -> Result<(), CanisterOutOfCyclesError> { let threshold = self.freeze_threshold_cycles( system_state, canister_current_memory_usage, canister_compute_allocation, ); self.consume_with_threshold(system_state, cycles, threshold) } /// Updates the metric `consumed_cycles_since_replica_started` with the /// amount of cycles consumed. pub fn observe_consumed_cycles(&self, system_state: &mut SystemState, cycles: Cycles) { system_state .canister_metrics .consumed_cycles_since_replica_started += NominalCycles::from_cycles(cycles); } /// Subtracts the corresponding cycles worth of the provided /// `num_instructions` from the canister's balance. /// /// # Errors /// /// Returns a `CanisterOutOfCyclesError` if the /// requested amount is greater than the currently available. pub fn withdraw_execution_cycles( &self, system_state: &mut SystemState, canister_current_memory_usage: NumBytes, canister_compute_allocation: ComputeAllocation, num_instructions: NumInstructions, ) -> Result<(), CanisterOutOfCyclesError> { let cycles_to_withdraw = self.execution_cost(num_instructions); self.consume_with_threshold( system_state, cycles_to_withdraw, self.freeze_threshold_cycles( system_state, canister_current_memory_usage, canister_compute_allocation, ), ) } /// Refunds the corresponding cycles worth of the provided /// `num_instructions` to the canister's balance. pub fn refund_execution_cycles( &self, system_state: &mut SystemState, num_instructions: NumInstructions, ) { let cycles_to_refund = self.config.ten_update_instructions_execution_fee * Cycles::from(num_instructions.get() / 10); self.refund_cycles(system_state, cycles_to_refund); } /// Charges the canister for its compute allocation /// /// # Errors /// /// Returns a `CanisterOutOfCyclesError` if the /// requested amount is greater than the currently available. pub fn charge_for_compute_allocation( &self, system_state: &mut SystemState, compute_allocation: ComputeAllocation, duration: Duration, ) -> Result<(), CanisterOutOfCyclesError> { let cycles = self.compute_allocation_cost(compute_allocation, duration); // Can charge all the way to the empty account (zero cycles) self.consume_with_threshold(system_state, cycles, Cycles::from(0)) } /// The cost of compute allocation, per round #[doc(hidden)] // pub for usage in tests pub fn compute_allocation_cost( &self, compute_allocation: ComputeAllocation, duration: Duration, ) -> Cycles { self.config.compute_percent_allocated_per_second_fee * Cycles::from(duration.as_secs()) * Cycles::from(compute_allocation.as_percent()) } /// Computes the cost of inducting an ingress message. /// /// Returns a tuple containing: /// - ID of the canister that should pay for the cost. /// - The cost of inducting the message. pub fn ingress_induction_cost( &self, ingress: &SignedIngressContent, ) -> Result<IngressInductionCost, IngressInductionCostError> { let paying_canister = if is_subnet_message(ingress, self.own_subnet_id) { // If a subnet message, inspect the payload to figure out who should pay for the // message. match Method::from_str(ingress.method_name()) { Ok(Method::ProvisionalCreateCanisterWithCycles) | Ok(Method::ProvisionalTopUpCanister) => { // Provisional methods are free. None } Ok(Method::StartCanister) | Ok(Method::CanisterStatus) | Ok(Method::DeleteCanister) | Ok(Method::UninstallCode) | Ok(Method::StopCanister) => match CanisterIdRecord::decode(ingress.arg()) { Ok(record) => Some(record.get_canister_id()), Err(_) => return Err(IngressInductionCostError::InvalidSubnetPayload), }, Ok(Method::UpdateSettings) => match UpdateSettingsArgs::decode(ingress.arg()) { Ok(record) => Some(record.get_canister_id()), Err(_) => return Err(IngressInductionCostError::InvalidSubnetPayload), }, Ok(Method::SetController) => match SetControllerArgs::decode(ingress.arg()) { Ok(record) => Some(record.get_canister_id()), Err(_) => return Err(IngressInductionCostError::InvalidSubnetPayload), }, Ok(Method::InstallCode) => match InstallCodeArgs::decode(ingress.arg()) { Ok(record) => Some(record.get_canister_id()), Err(_) => return Err(IngressInductionCostError::InvalidSubnetPayload), }, Ok(Method::CreateCanister) | Ok(Method::SetupInitialDKG) | Ok(Method::DepositCycles) | Ok(Method::RawRand) | Ok(Method::SignWithECDSA) | Ok(Method::GetMockECDSAPublicKey) | Ok(Method::SignWithMockECDSA) | Err(_) => { return Err(IngressInductionCostError::UnknownSubnetMethod); } } } else { // A message to a canister is always paid for by the receiving canister. Some(ingress.canister_id()) }; match paying_canister { Some(paying_canister) => { let bytes_to_charge = ingress.arg().len() + ingress.method_name().len() + ingress.nonce().map(|n| n.len()).unwrap_or(0); let cost = self.config.ingress_message_reception_fee + self.config.ingress_byte_reception_fee * bytes_to_charge; Ok(IngressInductionCost::Fee { payer: paying_canister, cost, }) } None => Ok(IngressInductionCost::Free), } } /// How often canisters should be charged for memory and compute allocation. pub fn duration_between_allocation_charges(&self) -> Duration { self.config.duration_between_allocation_charges } //////////////////////////////////////////////////////////////////////////// // // Storage // //////////////////////////////////////////////////////////////////////////// /// Subtracts the cycles cost of using a `bytes` amount of memory. /// /// Note: The following charges for memory taken by the canister. It /// currently takes into account all the pages in the canister's heap and /// stable memory (among other things). This will be revised in the future /// to take into account charging for dirty/read pages by the canister. /// /// # Errors /// /// Returns a `CanisterOutOfCyclesError` if there's /// not enough cycles to charge for memory. pub fn charge_for_memory( &self, system_state: &mut SystemState, bytes: NumBytes, duration: Duration, ) -> Result<(), CanisterOutOfCyclesError> { let cycles_amount = self.memory_cost(bytes, duration); // Can charge all the way to the empty account (zero cycles) self.consume_with_threshold(system_state, cycles_amount, Cycles::from(0)) } /// The cost of using `bytes` worth of memory. #[doc(hidden)] // pub for usage in tests pub fn memory_cost(&self, bytes: NumBytes, duration: Duration) -> Cycles { let one_gib = 1024 * 1024 * 1024; Cycles::from( (bytes.get() as u128 * self.config.gib_storage_per_second_fee.get() * duration.as_secs() as u128) / one_gib, ) } //////////////////////////////////////////////////////////////////////////// // // Request // //////////////////////////////////////////////////////////////////////////// /// When sending a request it's necessary to pay for: /// * The network cost of sending the request payload, which depends on /// the size (bytes) of the request. /// * The max cycles `max_num_instructions` that would be required to /// process the `Response`. /// * The max network cost of receiving the response, since we don't know /// yet the exact size the response will have. /// /// The leftover cycles is reimbursed after the `Response` for this request /// is received and executed. Only at that point will be known how much /// cycles receiving and executing the `Response` costs exactly. /// /// # Errors /// /// Returns a `CanisterOutOfCyclesError` if there is /// not enough cycles available to send the `Request`. pub fn withdraw_request_cycles( &self, system_state: &mut SystemState, canister_current_memory_usage: NumBytes, canister_compute_allocation: ComputeAllocation, request: &Request, ) -> Result<(), CanisterOutOfCyclesError> { // The total amount charged is the fee to do the xnet call (request + // response) + the fee to send the request + the fee for the largest // possible response + the fee for executing the largest allowed // response when it eventually arrives. let fee = self.config.xnet_call_fee + self.config.xnet_byte_transmission_fee * Cycles::from(request.payload_size_bytes().get()) + self.config.xnet_byte_transmission_fee * Cycles::from(MAX_INTER_CANISTER_PAYLOAD_IN_BYTES.get()) + self.execution_cost(self.max_num_instructions); self.consume_with_threshold( system_state, fee, self.freeze_threshold_cycles( system_state, canister_current_memory_usage, canister_compute_allocation, ), ) } /// Refunds the cycles from the response. In particular, adds leftover /// cycles from the what was reserved when the corresponding `Request` was /// sent earlier. pub fn response_cycles_refund(&self, system_state: &mut SystemState, response: &mut Response) { // We originally charged for the maximum number of bytes possible so // figure out how many extra bytes we charged for. let extra_bytes = MAX_INTER_CANISTER_PAYLOAD_IN_BYTES - response.response_payload.size_of(); let cycles_to_refund = self.config.xnet_byte_transmission_fee * Cycles::from(extra_bytes.get()); self.refund_cycles(system_state, cycles_to_refund); } //////////////////////////////////////////////////////////////////////////// // // Utility functions // //////////////////////////////////////////////////////////////////////////// /// Checks whether the requested amount of cycles can be withdrawn from the /// canister's balance while respecting the freezing threshold. /// /// Returns a `CanisterOutOfCyclesError` if the requested amount cannot be /// withdrawn. pub fn can_withdraw_cycles( &self, system_state: &SystemState, requested: Cycles, canister_current_memory_usage: NumBytes, canister_compute_allocation: ComputeAllocation, ) -> Result<(), CanisterOutOfCyclesError> { let threshold = self.freeze_threshold_cycles( system_state, canister_current_memory_usage, canister_compute_allocation, ); if threshold + requested > system_state.cycles_balance { Err(CanisterOutOfCyclesError { canister_id: system_state.canister_id(), available: system_state.cycles_balance, requested, threshold, }) } else { Ok(()) } } /// Note that this function is made public only for the tests. #[doc(hidden)] pub fn refund_cycles(&self, system_state: &mut SystemState, cycles: Cycles) { system_state.cycles_balance += cycles; system_state .canister_metrics .consumed_cycles_since_replica_started -= NominalCycles::from_cycles(cycles); } /// Subtracts and consumes the cycles. This call should be used when the /// cycles are not being sent somewhere else. pub fn consume_with_threshold( &self, system_state: &mut SystemState, cycles: Cycles, threshold: Cycles, ) -> Result<(), CanisterOutOfCyclesError> { self.withdraw_with_threshold(system_state, cycles, threshold) .map(|()| self.observe_consumed_cycles(system_state, cycles)) } /// Subtracts `cycles` worth of cycles from the canister's balance as long /// as there's enough above the provided `threshold`. This call should be /// used when the withdrawn cycles are sent somewhere else. // #[doc(hidden)] // pub for usage in tests pub fn withdraw_with_threshold( &self, system_state: &mut SystemState, cycles: Cycles, threshold: Cycles, ) -> Result<(), CanisterOutOfCyclesError> { let cycles_available = if system_state.cycles_balance > threshold { system_state.cycles_balance - threshold } else { Cycles::from(0) }; if cycles > cycles_available { return Err(CanisterOutOfCyclesError { canister_id: system_state.canister_id, available: system_state.cycles_balance, requested: cycles, threshold, }); } system_state.cycles_balance -= cycles; Ok(()) } /// Returns the maximum amount of `Cycles` that can be added to a canister's /// balance taking into account the `max_cycles_per_canister` value if /// present. pub fn check_max_cycles_can_add( &self, current_balance: Cycles, cycles_to_add: Cycles, ) -> Cycles { match self.own_subnet_type { SubnetType::System => cycles_to_add, SubnetType::Application | SubnetType::VerifiedApplication => { match self.max_cycles_per_canister { None => cycles_to_add, Some(max_cycles) => std::cmp::min(cycles_to_add, max_cycles - current_balance), } } } } /// Adds `cycles` worth of cycles to the canister's balance. /// The cycles balance added in a single go is limited to u64::max_value() /// Returns the amount of cycles that does not fit in the balance. pub fn add_cycles(&self, system_state: &mut SystemState, cycles_to_add: Cycles) -> Cycles { let cycles = self.check_max_cycles_can_add(system_state.cycles_balance, cycles_to_add); system_state.cycles_balance += cycles; cycles_to_add - cycles } /// Mints `amount_to_mint` [`Cycles`]. /// /// # Errors /// Returns a `CyclesAccountManagerError::ContractViolation` if not on NNS /// subnet. pub fn mint_cycles( &self, system_state: &mut SystemState, amount_to_mint: Cycles, nns_subnet_id: SubnetId, ) -> Result<(), CyclesAccountManagerError> { if self.own_subnet_id != nns_subnet_id { let error_str = format!("ic0.mint_cycles cannot be executed. Should only be called by a canister on the NNS subnet: {} != {}", self.own_subnet_id, nns_subnet_id); Err(CyclesAccountManagerError::ContractViolation(error_str)) } else { self.add_cycles(system_state, amount_to_mint); Ok(()) } } /// Returns the cost of the provided `num_instructions` in `Cycles`. /// /// Note that this function is made public to facilitate some logistic in /// tests. #[doc(hidden)] pub fn execution_cost(&self, num_instructions: NumInstructions) -> Cycles { self.config.update_message_execution_fee + self.config.ten_update_instructions_execution_fee * Cycles::from(num_instructions.get() / 10) } /// Charges a canister for its resource allocation and usage for the /// duration specified. If fees were successfully charged, then returns /// Ok(CanisterState) else returns Err(CanisterState). pub fn charge_canister_for_resource_allocation_and_usage( &self, log: &ReplicaLogger, canister: &mut CanisterState, duration_between_blocks: Duration, ) -> Result<(), CanisterOutOfCyclesError> { let bytes_to_charge = match canister.memory_allocation() { // The canister has explicitly asked for a memory allocation, so charge // based on it accordingly. MemoryAllocation::Reserved(bytes) => bytes, // The canister uses best-effort memory allocation, so charge based on current usage. MemoryAllocation::BestEffort => canister.memory_usage(self.own_subnet_type), }; if let Err(err) = self.charge_for_memory( &mut canister.system_state, bytes_to_charge, duration_between_blocks, ) { info!( log, "Charging canister {} for memory allocation/usage failed with {}", canister.canister_id(), err ); return Err(err); } let compute_allocation = canister.compute_allocation(); if let Err(err) = self.charge_for_compute_allocation( &mut canister.system_state, compute_allocation, duration_between_blocks, ) { info!( log, "Charging canister {} for compute allocation failed with {}", canister.canister_id(), err ); return Err(err); } Ok(()) } } /// Encapsulates the payer and cost of inducting an ingress messages. #[derive(Debug, Eq, PartialEq)] pub enum IngressInductionCost { /// Induction is free. Free, /// Induction cost and the canister to pay for it. Fee { payer: CanisterId, cost: Cycles }, } impl IngressInductionCost { /// Returns the cost of inducting an ingress message in [`Cycles`]. pub fn cost(&self) -> Cycles { match self { Self::Free => Cycles::from(0), Self::Fee { cost, .. } => *cost, } } } /// Errors returned when computing the cost of receiving an ingress. #[derive(Debug, Eq, PartialEq)] pub enum IngressInductionCostError { UnknownSubnetMethod, InvalidSubnetPayload, }
38.620491
166
0.611456