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
14c4f99cb7bec53461f22dfb8ff482e790be9b36
1,949
use crate::errors::ApiError; use crate::models::{ConstructionSubmitRequest, ConstructionSubmitResponse}; use crate::request::transaction_operation_results::TransactionOperationResults; use crate::request::transaction_results::TransactionResults; use crate::request_handler::{verify_network_id, RosettaRequestHandler}; use crate::transaction_id::{self, TransactionIdentifier}; impl RosettaRequestHandler { /// Submit a Signed Transaction. /// See https://www.rosetta-api.org/docs/ConstructionApi.html#constructionsubmit // Normally we'd just use the canister client Agent for this but because this // request is constructed in such an odd way it's easier to just do it from // scratch pub async fn construction_submit( &self, msg: ConstructionSubmitRequest, ) -> Result<ConstructionSubmitResponse, ApiError> { verify_network_id(self.ledger.ledger_canister_id(), &msg.network_identifier)?; let envelopes = msg.signed_transaction()?; let results = self.ledger.submit(envelopes).await?; let transaction_identifier = transaction_identifier(&results); let metadata = TransactionOperationResults::from_transaction_results( results, self.ledger.token_symbol(), )?; Ok(ConstructionSubmitResponse { transaction_identifier, metadata, }) } } /// Return the last transaction identifier if any or a pseudo one otherwise. fn transaction_identifier(results: &TransactionResults) -> TransactionIdentifier { results .last_transaction_id() .cloned() .map(From::from) .unwrap_or_else(|| { assert!(results .operations .iter() .all(|r| r._type.is_neuron_management())); TransactionIdentifier { hash: transaction_id::NEURON_MANAGEMENT_PSEUDO_HASH.to_owned(), } }) }
39.77551
86
0.67727
565182dd323f6e7a10034167526ff8a0ab4768e3
29,752
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::BTreeSet; use std::sync::Arc; use common_base::tokio; use common_base::tokio::time::Duration; use common_meta_api::KVApi; use common_meta_sled_store::openraft; use common_meta_sled_store::openraft::LogIdOptionExt; use common_meta_sled_store::openraft::RaftMetrics; use common_meta_sled_store::openraft::State; use common_meta_types::protobuf::raft_service_client::RaftServiceClient; use common_meta_types::AppliedState; use common_meta_types::Cmd; use common_meta_types::DatabaseMeta; use common_meta_types::ForwardToLeader; use common_meta_types::LogEntry; use common_meta_types::MatchSeq; use common_meta_types::MetaError; use common_meta_types::NodeId; use common_meta_types::Operation; use common_meta_types::RetryableError; use common_meta_types::SeqV; use common_tracing::tracing; use databend_meta::configs; use databend_meta::meta_service::meta_leader::MetaLeader; use databend_meta::meta_service::ForwardRequest; use databend_meta::meta_service::ForwardRequestBody; use databend_meta::meta_service::JoinRequest; use databend_meta::meta_service::MetaNode; use databend_meta::Opened; use maplit::btreeset; use pretty_assertions::assert_eq; use crate::init_meta_ut; use crate::tests::service::MetaSrvTestContext; #[tokio::test(flavor = "multi_thread", worker_threads = 5)] async fn test_meta_node_boot() -> anyhow::Result<()> { // - Start a single node meta service cluster. // - Test the single node is recorded by this cluster. let (_log_guards, ut_span) = init_meta_ut!(); let _ent = ut_span.enter(); let tc = MetaSrvTestContext::new(0); let addr = tc.config.raft_config.raft_api_addr(); let mn = MetaNode::boot(&tc.config.raft_config).await?; let got = mn.get_node(&0).await?; assert_eq!(addr, got.unwrap().address); mn.stop().await?; Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 5)] async fn test_meta_node_graceful_shutdown() -> anyhow::Result<()> { // - Start a leader then shutdown. let (_log_guards, ut_span) = init_meta_ut!(); let _ent = ut_span.enter(); let (_nid0, tc) = start_meta_node_leader().await?; let mn0 = tc.meta_node(); let mut rx0 = mn0.raft.metrics(); let joined = mn0.stop().await?; assert_eq!(3, joined); // tx closed: loop { let r = rx0.changed().await; if r.is_err() { tracing::info!("done!!!"); break; } tracing::info!("st: {:?}", rx0.borrow()); } assert!(rx0.changed().await.is_err()); Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 5)] async fn test_meta_node_leader_and_non_voter() -> anyhow::Result<()> { // - Start a leader and a non-voter; // - Write to leader, check on non-voter. let (_log_guards, ut_span) = init_meta_ut!(); let _ent = ut_span.enter(); { let span = tracing::span!(tracing::Level::DEBUG, "test_meta_node_leader_and_non_voter"); let _ent = span.enter(); let (_nid0, tc0) = start_meta_node_leader().await?; let mn0 = tc0.meta_node(); let (_nid1, tc1) = start_meta_node_non_voter(mn0.clone(), 1).await?; let mn1 = tc1.meta_node(); assert_upsert_kv_synced(vec![mn0.clone(), mn1.clone()], "metakey2").await?; } Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 5)] async fn test_meta_node_write_to_local_leader() -> anyhow::Result<()> { // - Start a leader, 2 followers and a non-voter; // - Write to the raft node on the leader, expect Ok. // - Write to the raft node on the non-leader, expect ForwardToLeader error. let (_log_guards, ut_span) = init_meta_ut!(); let _ent = ut_span.enter(); { let span = tracing::span!(tracing::Level::DEBUG, "test_meta_node_leader_and_non_voter"); let _ent = span.enter(); let (mut _nlog, tcs) = start_meta_node_cluster(btreeset![0, 1, 2], btreeset![3]).await?; let all = test_context_nodes(&tcs); let leader_id = all[0].raft.metrics().borrow().current_leader.unwrap(); // test writing to leader and non-leader let key = "t-non-leader-write"; for id in 0u64..4 { let mn = &all[id as usize]; let maybe_leader = MetaLeader::new(mn); let rst = maybe_leader .write(LogEntry { txid: None, cmd: Cmd::UpsertKV { key: key.to_string(), seq: MatchSeq::Any, value: Operation::Update(key.to_string().into_bytes()), value_meta: None, }, }) .await; if id == leader_id { assert!(rst.is_ok()); } else { assert!(rst.is_err()); let e = rst.unwrap_err(); match e { MetaError::ForwardToLeader(ForwardToLeader { leader }) => { assert_eq!(Some(leader_id), leader); } _ => { panic!("expect ForwardToLeader") } } } } } Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 5)] async fn test_meta_node_add_database() -> anyhow::Result<()> { // - Start a leader, 2 followers and a non-voter; // - Assert that every node handles AddDatabase request correctly. let (_log_guards, ut_span) = init_meta_ut!(); let _ent = ut_span.enter(); let tenant = "tenant1"; { let (_nlog, all_tc) = start_meta_node_cluster(btreeset![0, 1, 2], btreeset![3]).await?; let all = all_tc.iter().map(|tc| tc.meta_node()).collect::<Vec<_>>(); // ensure cluster works assert_upsert_kv_synced(all.clone(), "foo").await?; // - db name to create // - expected db id let cases: Vec<(&str, u64)> = vec![("foo", 1), ("bar", 2), ("foo", 1), ("bar", 2)]; // Sending AddDatabase request to any node is ok. for (i, (name, want_id)) in cases.iter().enumerate() { let mn = &all[i as usize]; let last_applied = mn.raft.metrics().borrow().last_applied; let rst = mn .write(LogEntry { txid: None, cmd: Cmd::CreateDatabase { tenant: tenant.to_string(), name: name.to_string(), meta: DatabaseMeta { engine: "default".to_string(), ..Default::default() }, }, }) .await; assert!(rst.is_ok()); // No matter if a db is created, the log that tries to create db always applies. assert_applied_index(all.clone(), last_applied.next_index()).await?; for (i, mn) in all.iter().enumerate() { let got = mn .get_state_machine() .await .get_database_id(tenant, name.as_ref())?; assert_eq!(*want_id, got, "n{} applied AddDatabase", i); } } } Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 5)] async fn test_meta_node_snapshot_replication() -> anyhow::Result<()> { // - Bring up a cluster of 3. // - Write just enough logs to trigger a snapshot. // - Add a non-voter, test the snapshot is sync-ed // - Write logs to trigger another snapshot. // - Add let (_log_guards, ut_span) = init_meta_ut!(); let _ent = ut_span.enter(); // Create a snapshot every 10 logs let snap_logs = 10; let mut tc = MetaSrvTestContext::new(0); tc.config.raft_config.snapshot_logs_since_last = snap_logs; tc.config.raft_config.install_snapshot_timeout = 10_1000; // milli seconds. In a CI multi-threads test delays async task badly. tc.config.raft_config.max_applied_log_to_keep = 0; let mn = MetaNode::boot(&tc.config.raft_config).await?; tc.assert_raft_server_connection().await?; wait_for_state(&mn, State::Leader).await?; wait_for_current_leader(&mn, 0).await?; // initial membership, leader blank log, add node. let mut log_index = 2; mn.raft .wait(timeout()) .log(Some(log_index), "leader init logs") .await?; let n_req = 12; for i in 0..n_req { let key = format!("test_meta_node_snapshot_replication-key-{}", i); mn.write(LogEntry { txid: None, cmd: Cmd::UpsertKV { key: key.clone(), seq: MatchSeq::Any, value: Some(b"v".to_vec()).into(), value_meta: None, }, }) .await?; } log_index += n_req; tracing::info!("--- check the log is locally applied"); mn.raft .wait(timeout()) .log(Some(log_index), "applied on leader") .await?; tracing::info!("--- check the snapshot is created"); mn.raft .wait(timeout()) .metrics( |x| x.snapshot.map(|x| x.term) == Some(1) && x.snapshot.next_index() >= snap_logs, "snapshot is created by leader", ) .await?; tracing::info!("--- start a non_voter to receive snapshot replication"); let (_, tc1) = start_meta_node_non_voter(mn.clone(), 1).await?; log_index += 1; let mn1 = tc1.meta_node(); mn1.raft .wait(timeout()) .log(Some(log_index), "non-voter replicated all logs") .await?; mn1.raft .wait(timeout()) .metrics( |x| x.snapshot.map(|x| x.term) == Some(1) && x.snapshot.next_index() >= snap_logs, "snapshot is received by non-voter", ) .await?; for i in 0..n_req { let key = format!("test_meta_node_snapshot_replication-key-{}", i); let got = mn1.get_kv(&key).await?; match got { None => { panic!("expect get some value for {}", key) } Some(SeqV { ref data, .. }) => { assert_eq!(data, b"v"); } } } Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 5)] async fn test_meta_node_join() -> anyhow::Result<()> { // - Bring up a cluster // - Join a new node by sending a Join request to leader. // - Join a new node by sending a Join request to a non-voter. // - Restart all nodes and check if states are restored. let (_log_guards, ut_span) = init_meta_ut!(); let _ent = ut_span.enter(); let span = tracing::span!(tracing::Level::INFO, "test_meta_node_join"); let _ent = span.enter(); let (mut _nlog, mut tcs) = start_meta_node_cluster(btreeset![0], btreeset![1]).await?; let mut all = test_context_nodes(&tcs); let tc0 = tcs.remove(0); let tc1 = tcs.remove(0); tracing::info!("--- bring up non-voter 2"); let node_id = 2; let tc2 = MetaSrvTestContext::new(node_id); let mn2 = MetaNode::open_create_boot(&tc2.config.raft_config, None, Some(()), None).await?; tracing::info!("--- join non-voter 2 to cluster by leader"); let leader_id = all[0].get_leader().await; let leader = all[leader_id as usize].clone(); let admin_req = join_req(node_id, tc2.config.raft_config.raft_api_addr(), 0); leader.handle_forwardable_request(admin_req).await?; all.push(mn2.clone()); tracing::info!("--- check all nodes has node-3 joined"); { for mn in all.iter() { mn.raft .wait(timeout()) .members(btreeset! {0,2}, format!("node-2 is joined: {}", mn.sto.id)) .await?; } } tracing::info!("--- bring up non-voter 3"); let node_id = 3; let tc3 = MetaSrvTestContext::new(node_id); let mn3 = MetaNode::open_create_boot(&tc3.config.raft_config, None, Some(()), None).await?; tracing::info!("--- join node-3 by sending rpc `join` to a non-leader"); { let to_addr = tc1.config.raft_config.raft_api_addr(); let mut client = RaftServiceClient::connect(format!("http://{}", to_addr)).await?; let admin_req = join_req(node_id, tc3.config.raft_config.raft_api_addr(), 1); client.forward(admin_req).await?; } tracing::info!("--- check all nodes has node-3 joined"); all.push(mn3.clone()); for mn in all.iter() { mn.raft .wait(timeout()) .members( btreeset! {0,2,3}, format!("node-3 is joined: {}", mn.sto.id), ) .await?; } tracing::info!("--- stop all meta node"); for mn in all.drain(..) { mn.stop().await?; } tracing::info!("--- re-open all meta node"); let mn0 = MetaNode::open_create_boot(&tc0.config.raft_config, Some(()), None, None).await?; let mn1 = MetaNode::open_create_boot(&tc1.config.raft_config, Some(()), None, None).await?; let mn2 = MetaNode::open_create_boot(&tc2.config.raft_config, Some(()), None, None).await?; let mn3 = MetaNode::open_create_boot(&tc3.config.raft_config, Some(()), None, None).await?; let all = vec![mn0, mn1, mn2, mn3]; tracing::info!("--- check reopened memberships"); for mn in all.iter() { mn.raft .wait(timeout()) .members(btreeset! {0,2,3}, format!("node-{} membership", mn.sto.id)) .await?; } Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 5)] async fn test_meta_node_join_rejoin() -> anyhow::Result<()> { // - Bring up a cluster // - Join a new node. // - Join another new node twice. let (_log_guards, ut_span) = init_meta_ut!(); let _ent = ut_span.enter(); let span = tracing::span!(tracing::Level::INFO, "test_meta_node_join_rejoin"); let _ent = span.enter(); let (mut _nlog, mut tcs) = start_meta_node_cluster(btreeset![0], btreeset![]).await?; let mut all = test_context_nodes(&tcs); let _tc0 = tcs.remove(0); tracing::info!("--- bring up non-voter 1"); let node_id = 1; let tc1 = MetaSrvTestContext::new(node_id); let mn1 = MetaNode::open_create_boot(&tc1.config.raft_config, None, Some(()), None).await?; tracing::info!("--- join non-voter 1 to cluster"); let leader_id = all[0].get_leader().await; let leader = all[leader_id as usize].clone(); let req = join_req(node_id, tc1.config.raft_config.raft_api_addr(), 1); leader.handle_forwardable_request(req).await?; all.push(mn1.clone()); tracing::info!("--- check all nodes has node-1 joined"); { for mn in all.iter() { mn.raft .wait(timeout()) .members(btreeset! {0,1}, format!("node-1 is joined: {}", mn.sto.id)) .await?; } } tracing::info!("--- bring up non-voter 3"); let node_id = 2; let tc2 = MetaSrvTestContext::new(node_id); let mn2 = MetaNode::open_create_boot(&tc2.config.raft_config, None, Some(()), None).await?; tracing::info!("--- join node-2 by sending rpc `join` to a non-leader"); { let req = join_req(node_id, tc2.config.raft_config.raft_api_addr(), 1); leader.handle_forwardable_request(req).await?; } tracing::info!("--- join node-2 again"); { let req = join_req(node_id, tc2.config.raft_config.raft_api_addr(), 1); mn1.handle_forwardable_request(req).await?; } all.push(mn2.clone()); tracing::info!("--- check all nodes has node-3 joined"); for mn in all.iter() { mn.raft .wait(timeout()) .members( btreeset! {0,1,2}, format!("node-2 is joined: {}", mn.sto.id), ) .await?; } Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 5)] async fn test_meta_node_restart() -> anyhow::Result<()> { // TODO check restarted follower. // - Start a leader and a non-voter; // - Restart them. // - Check old data an new written data. // TODO(xp): this only tests for in-memory storage. let (_log_guards, ut_span) = init_meta_ut!(); let _ent = ut_span.enter(); let (_nid0, tc0) = start_meta_node_leader().await?; let mn0 = tc0.meta_node(); let (_nid1, tc1) = start_meta_node_non_voter(mn0.clone(), 1).await?; let mn1 = tc1.meta_node(); let sto0 = mn0.sto.clone(); let sto1 = mn1.sto.clone(); let meta_nodes = vec![mn0.clone(), mn1.clone()]; assert_upsert_kv_synced(meta_nodes.clone(), "key1").await?; // stop tracing::info!("shutting down all"); let n = mn0.stop().await?; assert_eq!(3, n); let n = mn1.stop().await?; assert_eq!(3, n); tracing::info!("restart all"); // restart let config = configs::Config::empty(); let mn0 = MetaNode::builder(&config.raft_config) .node_id(0) .sto(sto0) .build() .await?; let mn1 = MetaNode::builder(&config.raft_config) .node_id(1) .sto(sto1) .build() .await?; let meta_nodes = vec![mn0.clone(), mn1.clone()]; wait_for_state(&mn0, State::Leader).await?; wait_for_state(&mn1, State::Learner).await?; wait_for_current_leader(&mn1, 0).await?; assert_upsert_kv_synced(meta_nodes.clone(), "key2").await?; // check old data assert_get_kv(meta_nodes, "key1", "key1").await?; Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 5)] async fn test_meta_node_restart_single_node() -> anyhow::Result<()> { // TODO(xp): This function will replace `test_meta_node_restart` after disk backed state machine is ready. // Test disk backed meta node restart. // - Start a cluster of a solo leader; // - Write one log. // - Restart. // - Check node state: // - raft hard state // - raft logs. // - state machine: // - Nodes // - TODO(xp): snapshot is empty, since snapshot is not persisted in this version see `MetaStore`. // - Check cluster: // - Leader is elected. // - TODO(xp): Leader starts replication to follower and non-voter. // - TODO(xp): New log will be successfully written and sync // - TODO(xp): A new snapshot will be created and transferred on demand. let (_log_guards, ut_span) = init_meta_ut!(); let _ent = ut_span.enter(); let mut log_index: u64 = 0; let (_id, tc) = start_meta_node_leader().await?; // initial membeship, leader blank, add node log_index += 2; let want_hs; { let leader = tc.meta_node(); leader .as_leader() .await? .write(LogEntry { txid: None, cmd: Cmd::UpsertKV { key: "foo".to_string(), seq: MatchSeq::Any, value: Operation::Update(b"1".to_vec()), value_meta: None, }, }) .await?; log_index += 1; want_hs = leader.sto.raft_state.read_hard_state()?; leader.stop().await?; } tracing::info!("--- reopen MetaNode"); let leader = MetaNode::open_create_boot(&tc.config.raft_config, Some(()), None, None).await?; log_index += 1; wait_for_state(&leader, State::Leader).await?; wait_for_log(&leader, log_index as u64).await?; tracing::info!("--- check hard state"); { let hs = leader.sto.raft_state.read_hard_state()?; assert_eq!(want_hs, hs); } tracing::info!("--- check logs"); { let logs = leader.sto.log.range_values(..)?; tracing::info!("logs: {:?}", logs); assert_eq!(log_index as usize + 1, logs.len()); } tracing::info!("--- check state machine: nodes"); { let node = leader.sto.get_node(&0).await?.unwrap(); assert_eq!(tc.config.raft_config.raft_api_addr(), node.address); } Ok(()) } /// Setup a cluster with several voter and several non_voter /// The node id 0 must be in `voters` and node 0 is elected as leader. pub(crate) async fn start_meta_node_cluster( voters: BTreeSet<NodeId>, non_voters: BTreeSet<NodeId>, ) -> anyhow::Result<(u64, Vec<MetaSrvTestContext>)> { // TODO(xp): use setup_cluster if possible in tests. Get rid of boilerplate snippets. // leader is always node-0 assert!(voters.contains(&0)); assert!(!non_voters.contains(&0)); let mut test_contexts = vec![]; let (_id, tc0) = start_meta_node_leader().await?; let leader = tc0.meta_node(); test_contexts.push(tc0); // membership log, blank log and add node let mut log_index = 2; wait_for_log(&leader, log_index).await?; for id in voters.iter() { // leader is already created. if *id == 0 { continue; } let (_id, tc) = start_meta_node_non_voter(leader.clone(), *id).await?; // Adding a node log_index += 1; tc.meta_node() .raft .wait(timeout()) .log(Some(log_index), format!("add :{}", id)) .await?; test_contexts.push(tc); } for id in non_voters.iter() { let (_id, tc) = start_meta_node_non_voter(leader.clone(), *id).await?; // Adding a node log_index += 1; tc.meta_node() .raft .wait(timeout()) .log(Some(log_index), format!("add :{}", id)) .await?; // wait_for_log(&tc.meta_nodes[0], log_index).await?; test_contexts.push(tc); } if voters != btreeset! {0} { leader.raft.change_membership(voters.clone(), true).await?; log_index += 2; } tracing::info!("--- check node roles"); { wait_for_state(&leader, State::Leader).await?; for item in test_contexts.iter().take(voters.len()).skip(1) { wait_for_state(&item.meta_node(), State::Follower).await?; } for item in test_contexts .iter() .skip(voters.len()) .take(non_voters.len()) { wait_for_state(&item.meta_node(), State::Learner).await?; } } tracing::info!("--- check node logs"); { for tc in &test_contexts { wait_for_log(&tc.meta_node(), log_index).await?; } } Ok((log_index, test_contexts)) } pub(crate) async fn start_meta_node_leader() -> anyhow::Result<(NodeId, MetaSrvTestContext)> { // Setup a cluster in which there is a leader and a non-voter. // asserts states are consistent let nid = 0; let mut tc = MetaSrvTestContext::new(nid); let addr = tc.config.raft_config.raft_api_addr(); // boot up a single-node cluster let mn = MetaNode::boot(&tc.config.raft_config).await?; tc.meta_node = Some(mn.clone()); { tc.assert_raft_server_connection().await?; // assert that boot() adds the node to meta. let got = mn.get_node(&nid).await?; assert_eq!(addr, got.unwrap().address, "nid0 is added"); wait_for_state(&mn, State::Leader).await?; wait_for_current_leader(&mn, 0).await?; } Ok((nid, tc)) } /// Start a NonVoter and setup replication from leader to it. /// Assert the NonVoter is ready and upto date such as the known leader, state and grpc service. async fn start_meta_node_non_voter( leader: Arc<MetaNode>, id: NodeId, ) -> anyhow::Result<(NodeId, MetaSrvTestContext)> { let mut tc = MetaSrvTestContext::new(id); let addr = tc.config.raft_config.raft_api_addr(); let raft_config = tc.config.raft_config.clone(); let mn = MetaNode::open_create_boot(&raft_config, None, Some(()), None).await?; assert!(!mn.is_opened()); tc.meta_node = Some(mn.clone()); { // add node to cluster as a non-voter let resp = leader.add_node(id, addr.clone()).await?; match resp { AppliedState::Node { prev: _, result } => { assert_eq!(addr.clone(), result.unwrap().address); } _ => { panic!("expect node") } } } { tc.assert_raft_server_connection().await?; wait_for_state(&mn, State::Learner).await?; wait_for_current_leader(&mn, 0).await?; } Ok((id, tc)) } fn join_req(node_id: NodeId, address: String, forward: u64) -> ForwardRequest { ForwardRequest { forward_to_leader: forward, body: ForwardRequestBody::Join(JoinRequest { node_id, address }), } } /// Write one log on leader, check all nodes replicated the log. /// Returns the number log committed. async fn assert_upsert_kv_synced(meta_nodes: Vec<Arc<MetaNode>>, key: &str) -> anyhow::Result<u64> { let leader_id = meta_nodes[0].get_leader().await; let leader = meta_nodes[leader_id as usize].clone(); let last_applied = leader.raft.metrics().borrow().last_applied; tracing::info!("leader: last_applied={:?}", last_applied); { leader .as_leader() .await? .write(LogEntry { txid: None, cmd: Cmd::UpsertKV { key: key.to_string(), seq: MatchSeq::Any, value: Operation::Update(key.to_string().into_bytes()), value_meta: None, }, }) .await?; } assert_applied_index(meta_nodes.clone(), last_applied.next_index()).await?; assert_get_kv(meta_nodes.clone(), key, key).await?; Ok(1) } /// Wait nodes for applied index to be upto date: applied >= at_least. async fn assert_applied_index(meta_nodes: Vec<Arc<MetaNode>>, at_least: u64) -> anyhow::Result<()> { for (_i, mn) in meta_nodes.iter().enumerate() { wait_for_log(mn, at_least).await?; } Ok(()) } async fn assert_get_kv( meta_nodes: Vec<Arc<MetaNode>>, key: &str, value: &str, ) -> anyhow::Result<()> { for (i, mn) in meta_nodes.iter().enumerate() { let got = mn.get_kv(key).await?; // let got = mn.get_file(key).await?; assert_eq!( value.to_string().into_bytes(), got.unwrap().data, "n{} applied value", i ); } Ok(()) } /// Wait for the known leader of a raft to become the expected `leader_id` until a default 2000 ms time out. #[tracing::instrument(level = "info", skip(mn))] pub async fn wait_for_current_leader( mn: &MetaNode, leader_id: NodeId, ) -> anyhow::Result<RaftMetrics> { let metrics = mn .raft .wait(timeout()) .current_leader(leader_id, "") .await?; Ok(metrics) } /// Wait for raft log to become the expected `index` until a default 2000 ms time out. #[tracing::instrument(level = "info", skip(mn))] async fn wait_for_log(mn: &MetaNode, index: u64) -> anyhow::Result<RaftMetrics> { let metrics = mn.raft.wait(timeout()).log(Some(index), "").await?; Ok(metrics) } /// Wait for raft state to become the expected `state` until a default 2000 ms time out. #[tracing::instrument(level = "debug", skip(mn))] pub async fn wait_for_state(mn: &MetaNode, state: openraft::State) -> anyhow::Result<RaftMetrics> { let metrics = mn.raft.wait(timeout()).state(state, "").await?; Ok(metrics) } /// Wait for raft metrics to become a state that satisfies `func`. #[tracing::instrument(level = "debug", skip(mn, func))] async fn wait_for<T>(mn: &MetaNode, func: T) -> anyhow::Result<RaftMetrics> where T: Fn(&RaftMetrics) -> bool + Send { let metrics = mn.raft.wait(timeout()).metrics(func, "").await?; Ok(metrics) } /// Make a default timeout for wait() for test. fn timeout() -> Option<Duration> { Some(Duration::from_millis(10000)) } fn test_context_nodes(tcs: &[MetaSrvTestContext]) -> Vec<Arc<MetaNode>> { tcs.iter().map(|tc| tc.meta_node()).collect::<Vec<_>>() } #[tokio::test(flavor = "multi_thread", worker_threads = 3)] async fn test_meta_node_incr_seq() -> anyhow::Result<()> { let (_log_guards, ut_span) = init_meta_ut!(); let _ent = ut_span.enter(); let tc = MetaSrvTestContext::new(0); let addr = tc.config.raft_config.raft_api_addr(); let _mn = MetaNode::boot(&tc.config.raft_config).await?; tc.assert_raft_server_connection().await?; let mut client = RaftServiceClient::connect(format!("http://{}", addr)).await?; let cases = common_meta_raft_store::state_machine::testing::cases_incr_seq(); for (name, txid, k, want) in cases.iter() { let req = LogEntry { txid: txid.clone(), cmd: Cmd::IncrSeq { key: k.to_string() }, }; let raft_reply = client.write(req).await?.into_inner(); let res: Result<AppliedState, RetryableError> = raft_reply.into(); let resp: AppliedState = res?; match resp { AppliedState::Seq { seq } => { assert_eq!(*want, seq, "{}", name); } _ => { panic!("not Seq") } } } Ok(()) }
31.252101
131
0.586616
11f7fc9deb8e185a28383b9c2cebc53819507cf2
3,260
use ring::digest::*; use std::fs::File; use std::io::{self, Read, Write}; use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; #[cfg(target_pointer_width = "64")] //pub type AtomicU64 = AtomicUsize; pub struct AtomicU64 { inner: AtomicUsize, } #[cfg(target_pointer_width = "64")] impl AtomicU64 { pub fn new(initial: u64) -> Self { Self { inner: AtomicUsize::new(initial as usize), } } pub fn load(&self, order: Ordering) -> u64 { self.inner.load(order) as u64 } pub fn fetch_add(&self, val: u64, order: Ordering) -> u64 { self.inner.fetch_add(val as usize, order) as u64 } } #[cfg(not(target_pointer_width = "64"))] pub type AtomicU64 = !; // until the proper AtomicU64 type is stable, this needs to be compiled 64-bit. pub struct HashingWrite<T: Write> { ctx: Context, inner: T, } impl<T: Write> HashingWrite<T> { pub fn new(inner: T, algo: &'static Algorithm) -> HashingWrite<T> { HashingWrite { ctx: Context::new(algo), inner, } } pub fn finish(self) -> Vec<u8> { self.ctx.finish().as_ref().to_vec() } } pub fn write_file_and_sidecar<R: Read>( input: &mut R, path: &Path, sidecar_path: &Path, algo: &'static Algorithm, progress: &AtomicU64, ) -> Result<(), String> { /* let mut hash_filename = path.file_name().unwrap().to_os_string(); hash_filename.push(suffix); let hash_file_path = path.with_file_name(hash_filename); */ let out = File::create(path).map_err(|e| format!("failed to create {:?}: {}", path, e))?; let mut hash_out = HashingWrite::new(out, algo); let mut buf = [0u8; 8192]; loop { match input.read(&mut buf) { Ok(0) => break, Ok(nread) => { progress.fetch_add(nread as u64, Ordering::Relaxed); match hash_out.write(&buf[0..nread]) { Ok(nwritten) => { if nwritten != nread { let msg = format!("nwritten({}) != nread({})", nwritten, nread); return Err(msg); } }, Err(e) => { return Err(format!("write error: {}", e)); } } }, Err(e) => { return Err(format!("read error: {}", e)); } } } let hash: String = hash_out.finish().iter() .fold(String::new(), |s, byte| s + &format!("{:02x}", byte)); let mut sidecar_file = match File::create(sidecar_path) { Ok(f) => f, Err(e) => { let msg = format!("failed to create sidecar {:?}: {}", sidecar_path, e); return Err(msg); } }; if let Err(e) = sidecar_file.write_all(hash.as_bytes()) { return Err(format!("failed to write hash sidecar {:?}: {}", sidecar_path, e)); } Ok(()) } impl<T: Write> Write for HashingWrite<T> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.ctx.update(buf); self.inner.write(buf) } fn flush(&mut self) -> io::Result<()> { self.inner.flush() } }
26.721311
103
0.517485
e2c282d13bb37c7cf904abc588d1108d9ccd2f4f
4,136
use async_std::io::{BufRead as AsyncBufRead, Read as AsyncRead}; use async_std::prelude::*; use async_std::task::{ready, Context, Poll}; use std::io; use std::pin::Pin; use std::time::Duration; pin_project_lite::pin_project! { /// An SSE protocol encoder. #[derive(Debug)] pub struct Encoder { buf: Box<[u8]>, cursor: usize, #[pin] receiver: async_channel::Receiver<Vec<u8>>, } } impl AsyncRead for Encoder { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<usize>> { let mut this = self.project(); // Request a new buffer if current one is exhausted. if this.buf.len() <= *this.cursor { match ready!(this.receiver.as_mut().poll_next(cx)) { Some(buf) => { log::trace!("> Received a new buffer with len {}", buf.len()); *this.buf = buf.into_boxed_slice(); *this.cursor = 0; } None => { log::trace!("> Encoder done reading"); return Poll::Ready(Ok(0)); } }; } // Write the current buffer to completion. let local_buf = &this.buf[*this.cursor..]; let max = buf.len().min(local_buf.len()); buf[..max].clone_from_slice(&local_buf[..max]); *this.cursor += max; // Return bytes read. Poll::Ready(Ok(max)) } } impl AsyncBufRead for Encoder { fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> { let mut this = self.project(); // Request a new buffer if current one is exhausted. if this.buf.len() <= *this.cursor { match ready!(this.receiver.as_mut().poll_next(cx)) { Some(buf) => { log::trace!("> Received a new buffer with len {}", buf.len()); *this.buf = buf.into_boxed_slice(); *this.cursor = 0; } None => { log::trace!("> Encoder done reading"); return Poll::Ready(Ok(&[])); } }; } Poll::Ready(Ok(&this.buf[*this.cursor..])) } fn consume(self: Pin<&mut Self>, amt: usize) { let this = self.project(); *this.cursor += amt; } } /// The sending side of the encoder. #[derive(Debug, Clone)] pub struct Sender(async_channel::Sender<Vec<u8>>); /// Create a new SSE encoder. pub fn encode() -> (Sender, Encoder) { let (sender, receiver) = async_channel::bounded(1); let encoder = Encoder { receiver, buf: Box::default(), cursor: 0, }; (Sender(sender), encoder) } impl Sender { async fn inner_send(&self, bytes: impl Into<Vec<u8>>) -> io::Result<()> { self.0 .send(bytes.into()) .await .map_err(|_| io::Error::new(io::ErrorKind::ConnectionAborted, "sse disconnected")) } /// Send a new message over SSE. pub async fn send( &self, name: impl Into<Option<&str>>, data: &str, id: Option<&str>, ) -> io::Result<()> { // Write the event name if let Some(name) = name.into() { self.inner_send(format!("event:{}\n", name)).await?; } // Write the id if let Some(id) = id { self.inner_send(format!("id:{}\n", id)).await?; } // Write the data section, and end. let msg = format!("data:{}\n\n", data); self.inner_send(msg).await?; Ok(()) } /// Send a new "retry" message over SSE. pub async fn send_retry(&self, dur: Duration, id: Option<&str>) -> io::Result<()> { // Write the id if let Some(id) = id { self.inner_send(format!("id:{}\n", id)).await?; } // Write the retry section, and end. let dur = dur.as_secs_f64() as u64; let msg = format!("retry:{}\n\n", dur); self.inner_send(msg).await?; Ok(()) } }
29.542857
94
0.502901
e284b354e3037f17f0e0aa1c2df20e553892aa08
13,988
//! Statement and declaration parsing. //! //! More information: //! - [MDN documentation][mdn] //! - [ECMAScript specification][spec] //! //! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements //! [spec]: https://tc39.es/ecma262/#sec-ecmascript-language-statements-and-declarations mod block; mod break_stm; mod continue_stm; mod declaration; mod expression; mod if_stm; mod iteration; mod labelled_stm; mod return_stm; mod switch; mod throw; mod try_stm; mod variable; use self::{ block::BlockStatement, break_stm::BreakStatement, continue_stm::ContinueStatement, declaration::Declaration, expression::ExpressionStatement, if_stm::IfStatement, iteration::{DoWhileStatement, ForStatement, WhileStatement}, return_stm::ReturnStatement, switch::SwitchStatement, throw::ThrowStatement, try_stm::TryStatement, variable::VariableStatement, }; use super::{AllowAwait, AllowReturn, AllowYield, Cursor, ParseError, TokenParser}; use crate::{ syntax::{ ast::{node, Keyword, Node, Punctuator}, lexer::{Error as LexError, InputElement, TokenKind}, parser::expression::await_expr::AwaitExpression, }, BoaProfiler, }; use labelled_stm::LabelledStatement; use std::io::Read; /// Statement parsing. /// /// This can be one of the following: /// /// - `BlockStatement` /// - `VariableStatement` /// - `EmptyStatement` /// - `ExpressionStatement` /// - `IfStatement` /// - `BreakableStatement` /// - `ContinueStatement` /// - `BreakStatement` /// - `ReturnStatement` /// - `WithStatement` /// - `LabelledStatement` /// - `ThrowStatement` /// - `SwitchStatement` /// - `TryStatement` /// - `DebuggerStatement` /// /// More information: /// - [MDN documentation][mdn] /// - [ECMAScript specification][spec] /// /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements /// [spec]: https://tc39.es/ecma262/#prod-Statement #[derive(Debug, Clone, Copy)] pub(super) struct Statement { allow_yield: AllowYield, allow_await: AllowAwait, allow_return: AllowReturn, } impl Statement { /// Creates a new `Statement` parser. pub(super) fn new<Y, A, R>(allow_yield: Y, allow_await: A, allow_return: R) -> Self where Y: Into<AllowYield>, A: Into<AllowAwait>, R: Into<AllowReturn>, { Self { allow_yield: allow_yield.into(), allow_await: allow_await.into(), allow_return: allow_return.into(), } } } impl<R> TokenParser<R> for Statement where R: Read, { type Output = Node; fn parse(self, cursor: &mut Cursor<R>) -> Result<Self::Output, ParseError> { let _timer = BoaProfiler::global().start_event("Statement", "Parsing"); // TODO: add BreakableStatement and divide Whiles, fors and so on to another place. let tok = cursor.peek(0)?.ok_or(ParseError::AbruptEnd)?; match tok.kind() { TokenKind::Keyword(Keyword::Await) => AwaitExpression::new(self.allow_yield) .parse(cursor) .map(Node::from), TokenKind::Keyword(Keyword::If) => { IfStatement::new(self.allow_yield, self.allow_await, self.allow_return) .parse(cursor) .map(Node::from) } TokenKind::Keyword(Keyword::Var) => { VariableStatement::new(self.allow_yield, self.allow_await) .parse(cursor) .map(Node::from) } TokenKind::Keyword(Keyword::While) => { WhileStatement::new(self.allow_yield, self.allow_await, self.allow_return) .parse(cursor) .map(Node::from) } TokenKind::Keyword(Keyword::Do) => { DoWhileStatement::new(self.allow_yield, self.allow_await, self.allow_return) .parse(cursor) .map(Node::from) } TokenKind::Keyword(Keyword::For) => { ForStatement::new(self.allow_yield, self.allow_await, self.allow_return) .parse(cursor) .map(Node::from) } TokenKind::Keyword(Keyword::Return) => { if self.allow_return.0 { ReturnStatement::new(self.allow_yield, self.allow_await) .parse(cursor) .map(Node::from) } else { Err(ParseError::unexpected(tok.clone(), "statement")) } } TokenKind::Keyword(Keyword::Break) => { BreakStatement::new(self.allow_yield, self.allow_await) .parse(cursor) .map(Node::from) } TokenKind::Keyword(Keyword::Continue) => { ContinueStatement::new(self.allow_yield, self.allow_await) .parse(cursor) .map(Node::from) } TokenKind::Keyword(Keyword::Try) => { TryStatement::new(self.allow_yield, self.allow_await, self.allow_return) .parse(cursor) .map(Node::from) } TokenKind::Keyword(Keyword::Throw) => { ThrowStatement::new(self.allow_yield, self.allow_await) .parse(cursor) .map(Node::from) } TokenKind::Keyword(Keyword::Switch) => { SwitchStatement::new(self.allow_yield, self.allow_await, self.allow_return) .parse(cursor) .map(Node::from) } TokenKind::Punctuator(Punctuator::OpenBlock) => { BlockStatement::new(self.allow_yield, self.allow_await, self.allow_return) .parse(cursor) .map(Node::from) } TokenKind::Identifier(_) => { // Labelled Statement check cursor.set_goal(InputElement::Div); let tok = cursor.peek(1)?; if tok.is_some() && matches!( tok.unwrap().kind(), TokenKind::Punctuator(Punctuator::Colon) ) { return LabelledStatement::new( self.allow_yield, self.allow_await, self.allow_return, ) .parse(cursor) .map(Node::from); } ExpressionStatement::new(self.allow_yield, self.allow_await).parse(cursor) } _ => ExpressionStatement::new(self.allow_yield, self.allow_await).parse(cursor), } } } /// Reads a list of statements. /// /// More information: /// - [ECMAScript specification][spec] /// /// [spec]: https://tc39.es/ecma262/#prod-StatementList #[derive(Debug, Clone, Copy)] pub(super) struct StatementList { allow_yield: AllowYield, allow_await: AllowAwait, allow_return: AllowReturn, in_block: bool, break_nodes: &'static [TokenKind], } impl StatementList { /// Creates a new `StatementList` parser. pub(super) fn new<Y, A, R>( allow_yield: Y, allow_await: A, allow_return: R, in_block: bool, break_nodes: &'static [TokenKind], ) -> Self where Y: Into<AllowYield>, A: Into<AllowAwait>, R: Into<AllowReturn>, { Self { allow_yield: allow_yield.into(), allow_await: allow_await.into(), allow_return: allow_return.into(), in_block, break_nodes, } } } impl<R> TokenParser<R> for StatementList where R: Read, { type Output = node::StatementList; /// The function parses a node::StatementList using the StatementList's /// break_nodes to know when to terminate. /// /// Returns a ParseError::AbruptEnd if end of stream is reached before a /// break token. /// /// Returns a ParseError::unexpected if an unexpected token is found. /// /// Note that the last token which causes the parse to finish is not /// consumed. fn parse(self, cursor: &mut Cursor<R>) -> Result<Self::Output, ParseError> { let _timer = BoaProfiler::global().start_event("StatementList", "Parsing"); let mut items = Vec::new(); loop { match cursor.peek(0)? { Some(token) if self.break_nodes.contains(token.kind()) => break, None => break, _ => {} } let item = StatementListItem::new( self.allow_yield, self.allow_await, self.allow_return, self.in_block, ) .parse(cursor)?; items.push(item); // move the cursor forward for any consecutive semicolon. while cursor.next_if(Punctuator::Semicolon)?.is_some() {} } items.sort_by(Node::hoistable_order); Ok(items.into()) } } /// Statement list item parsing /// /// A statement list item can either be an statement or a declaration. /// /// More information: /// - [MDN documentation][mdn] /// - [ECMAScript specification][spec] /// /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements /// [spec]: https://tc39.es/ecma262/#prod-StatementListItem #[derive(Debug, Clone, Copy)] struct StatementListItem { allow_yield: AllowYield, allow_await: AllowAwait, allow_return: AllowReturn, in_block: bool, } impl StatementListItem { /// Creates a new `StatementListItem` parser. fn new<Y, A, R>(allow_yield: Y, allow_await: A, allow_return: R, in_block: bool) -> Self where Y: Into<AllowYield>, A: Into<AllowAwait>, R: Into<AllowReturn>, { Self { allow_yield: allow_yield.into(), allow_await: allow_await.into(), allow_return: allow_return.into(), in_block, } } } impl<R> TokenParser<R> for StatementListItem where R: Read, { type Output = Node; fn parse(self, cursor: &mut Cursor<R>) -> Result<Self::Output, ParseError> { let _timer = BoaProfiler::global().start_event("StatementListItem", "Parsing"); let strict_mode = cursor.strict_mode(); let tok = cursor.peek(0)?.ok_or(ParseError::AbruptEnd)?; match *tok.kind() { TokenKind::Keyword(Keyword::Function) | TokenKind::Keyword(Keyword::Async) => { if strict_mode && self.in_block { return Err(ParseError::lex(LexError::Syntax( "Function declaration in blocks not allowed in strict mode".into(), tok.span().start(), ))); } Declaration::new(self.allow_yield, self.allow_await, true).parse(cursor) } TokenKind::Keyword(Keyword::Const) | TokenKind::Keyword(Keyword::Let) => { Declaration::new(self.allow_yield, self.allow_await, true).parse(cursor) } _ => { Statement::new(self.allow_yield, self.allow_await, self.allow_return).parse(cursor) } } } } /// Label identifier parsing. /// /// This seems to be the same as a `BindingIdentifier`. /// /// More information: /// - [ECMAScript specification][spec] /// /// [spec]: https://tc39.es/ecma262/#prod-LabelIdentifier pub(super) type LabelIdentifier = BindingIdentifier; /// Binding identifier parsing. /// /// More information: /// - [ECMAScript specification][spec] /// /// [spec]: https://tc39.es/ecma262/#prod-BindingIdentifier #[derive(Debug, Clone, Copy)] pub(super) struct BindingIdentifier { allow_yield: AllowYield, allow_await: AllowAwait, } impl BindingIdentifier { /// Creates a new `BindingIdentifier` parser. pub(super) fn new<Y, A>(allow_yield: Y, allow_await: A) -> Self where Y: Into<AllowYield>, A: Into<AllowAwait>, { Self { allow_yield: allow_yield.into(), allow_await: allow_await.into(), } } } impl<R> TokenParser<R> for BindingIdentifier where R: Read, { type Output = Box<str>; /// Strict mode parsing as per <https://tc39.es/ecma262/#sec-identifiers-static-semantics-early-errors>. fn parse(self, cursor: &mut Cursor<R>) -> Result<Self::Output, ParseError> { let _timer = BoaProfiler::global().start_event("BindingIdentifier", "Parsing"); let next_token = cursor.next()?.ok_or(ParseError::AbruptEnd)?; match next_token.kind() { TokenKind::Identifier(ref s) => Ok(s.clone()), TokenKind::Keyword(k @ Keyword::Yield) if !self.allow_yield.0 => { if cursor.strict_mode() { Err(ParseError::lex(LexError::Syntax( "yield keyword in binding identifier not allowed in strict mode".into(), next_token.span().start(), ))) } else { Ok(k.as_str().into()) } } TokenKind::Keyword(k @ Keyword::Await) if !self.allow_await.0 => { if cursor.strict_mode() { Err(ParseError::lex(LexError::Syntax( "await keyword in binding identifier not allowed in strict mode".into(), next_token.span().start(), ))) } else { Ok(k.as_str().into()) } } _ => Err(ParseError::expected( vec![TokenKind::identifier("identifier")], next_token, "binding identifier", )), } } }
32.009153
108
0.558908
ffd4b950a1cf4116f85fd772fbf557d4c3f4f782
1,542
use crate::{ data::{DEBUG, DISABLE_SSL_VERIFY}, ConversationInfo, }; use curl::{easy::Easy, Error}; use std::env; use std::io::Read; use std::time::SystemTime; fn format_and_transfer(curl: &mut Easy, mut msg: &[u8], result: &mut Vec<u8>) -> Result<(), Error> { let now = SystemTime::now(); match env::var(DISABLE_SSL_VERIFY) { Ok(var) if var == "true" => { curl.ssl_verify_host(false)?; curl.ssl_verify_peer(false)?; } _ => (), }; curl.post_field_size(msg.len() as u64)?; let mut transfer = curl.transfer(); transfer.read_function(|buf| Ok(msg.read(buf).unwrap_or(0)))?; transfer.write_function(|new_data| { result.extend_from_slice(new_data); Ok(new_data.len()) })?; transfer.perform()?; if let Ok(var) = env::var(DEBUG) { if var == "true" { let el = now.elapsed().unwrap(); println!( "http post callback_url - {}.{}", el.as_secs(), el.as_millis() ); } } Ok(()) } //-> Result<(), Error> pub fn api(c_info: &mut ConversationInfo, msg: &[u8]) { let curl = match &mut c_info.curl { Some(val) => val, None => return, }; let mut result = Vec::new(); if let Err(err) = format_and_transfer(curl, msg, &mut result) { match env::var(DEBUG) { Ok(ref var) if var == "true" => println!("fail to send msg {:?}", err), _ => (), }; return; }; }
25.7
100
0.518807
90656330795aba4d289b19d9acc35b9f188043ca
49,517
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[derive(Debug)] pub(crate) struct Handle< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { client: aws_smithy_client::Client<C, M, R>, conf: crate::Config, } /// An ergonomic service client for `AmazonConnectParticipantServiceLambda`. /// /// This client allows ergonomic access to a `AmazonConnectParticipantServiceLambda`-shaped service. /// Each method corresponds to an endpoint defined in the service's Smithy model, /// and the request and response shapes are auto-generated from that same model. /// /// # Using a Client /// /// Once you have a client set up, you can access the service's endpoints /// by calling the appropriate method on [`Client`]. Each such method /// returns a request builder for that endpoint, with methods for setting /// the various fields of the request. Once your request is complete, use /// the `send` method to send the request. `send` returns a future, which /// you then have to `.await` to get the service's response. /// /// [builder pattern]: https://rust-lang.github.io/api-guidelines/type-safety.html#c-builder /// [SigV4-signed requests]: https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html #[derive(std::fmt::Debug)] pub struct Client< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<Handle<C, M, R>>, } impl<C, M, R> std::clone::Clone for Client<C, M, R> { fn clone(&self) -> Self { Self { handle: self.handle.clone(), } } } #[doc(inline)] pub use aws_smithy_client::Builder; impl<C, M, R> From<aws_smithy_client::Client<C, M, R>> for Client<C, M, R> { fn from(client: aws_smithy_client::Client<C, M, R>) -> Self { Self::with_config(client, crate::Config::builder().build()) } } impl<C, M, R> Client<C, M, R> { /// Creates a client with the given service configuration. pub fn with_config(client: aws_smithy_client::Client<C, M, R>, conf: crate::Config) -> Self { Self { handle: std::sync::Arc::new(Handle { client, conf }), } } /// Returns the client's configuration. pub fn conf(&self) -> &crate::Config { &self.handle.conf } } impl<C, M, R> Client<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Constructs a fluent builder for the `CompleteAttachmentUpload` operation. /// /// See [`CompleteAttachmentUpload`](crate::client::fluent_builders::CompleteAttachmentUpload) for more information about the /// operation and its arguments. pub fn complete_attachment_upload(&self) -> fluent_builders::CompleteAttachmentUpload<C, M, R> { fluent_builders::CompleteAttachmentUpload::new(self.handle.clone()) } /// Constructs a fluent builder for the `CreateParticipantConnection` operation. /// /// See [`CreateParticipantConnection`](crate::client::fluent_builders::CreateParticipantConnection) for more information about the /// operation and its arguments. pub fn create_participant_connection( &self, ) -> fluent_builders::CreateParticipantConnection<C, M, R> { fluent_builders::CreateParticipantConnection::new(self.handle.clone()) } /// Constructs a fluent builder for the `DisconnectParticipant` operation. /// /// See [`DisconnectParticipant`](crate::client::fluent_builders::DisconnectParticipant) for more information about the /// operation and its arguments. pub fn disconnect_participant(&self) -> fluent_builders::DisconnectParticipant<C, M, R> { fluent_builders::DisconnectParticipant::new(self.handle.clone()) } /// Constructs a fluent builder for the `GetAttachment` operation. /// /// See [`GetAttachment`](crate::client::fluent_builders::GetAttachment) for more information about the /// operation and its arguments. pub fn get_attachment(&self) -> fluent_builders::GetAttachment<C, M, R> { fluent_builders::GetAttachment::new(self.handle.clone()) } /// Constructs a fluent builder for the `GetTranscript` operation. /// /// See [`GetTranscript`](crate::client::fluent_builders::GetTranscript) for more information about the /// operation and its arguments. pub fn get_transcript(&self) -> fluent_builders::GetTranscript<C, M, R> { fluent_builders::GetTranscript::new(self.handle.clone()) } /// Constructs a fluent builder for the `SendEvent` operation. /// /// See [`SendEvent`](crate::client::fluent_builders::SendEvent) for more information about the /// operation and its arguments. pub fn send_event(&self) -> fluent_builders::SendEvent<C, M, R> { fluent_builders::SendEvent::new(self.handle.clone()) } /// Constructs a fluent builder for the `SendMessage` operation. /// /// See [`SendMessage`](crate::client::fluent_builders::SendMessage) for more information about the /// operation and its arguments. pub fn send_message(&self) -> fluent_builders::SendMessage<C, M, R> { fluent_builders::SendMessage::new(self.handle.clone()) } /// Constructs a fluent builder for the `StartAttachmentUpload` operation. /// /// See [`StartAttachmentUpload`](crate::client::fluent_builders::StartAttachmentUpload) for more information about the /// operation and its arguments. pub fn start_attachment_upload(&self) -> fluent_builders::StartAttachmentUpload<C, M, R> { fluent_builders::StartAttachmentUpload::new(self.handle.clone()) } } pub mod fluent_builders { //! //! Utilities to ergonomically construct a request to the service. //! //! Fluent builders are created through the [`Client`](crate::client::Client) by calling //! one if its operation methods. After parameters are set using the builder methods, //! the `send` method can be called to initiate the request. //! /// Fluent builder constructing a request to `CompleteAttachmentUpload`. /// /// <p>Allows you to confirm that the attachment has been uploaded using the pre-signed URL /// provided in StartAttachmentUpload API. </p> /// <p>The Amazon Connect Participant Service APIs do not use <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature Version 4 /// authentication</a>.</p> #[derive(std::fmt::Debug)] pub struct CompleteAttachmentUpload< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::complete_attachment_upload_input::Builder, } impl<C, M, R> CompleteAttachmentUpload<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `CompleteAttachmentUpload`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::CompleteAttachmentUploadOutput, aws_smithy_http::result::SdkError<crate::error::CompleteAttachmentUploadError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::CompleteAttachmentUploadInputOperationOutputAlias, crate::output::CompleteAttachmentUploadOutput, crate::error::CompleteAttachmentUploadError, crate::input::CompleteAttachmentUploadInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// Appends an item to `AttachmentIds`. /// /// To override the contents of this collection use [`set_attachment_ids`](Self::set_attachment_ids). /// /// <p>A list of unique identifiers for the attachments.</p> pub fn attachment_ids(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.attachment_ids(inp); self } /// <p>A list of unique identifiers for the attachments.</p> pub fn set_attachment_ids( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.inner = self.inner.set_attachment_ids(input); self } /// <p>A unique, case-sensitive identifier that you provide to ensure the idempotency of the /// request.</p> pub fn client_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.client_token(inp); self } /// <p>A unique, case-sensitive identifier that you provide to ensure the idempotency of the /// request.</p> pub fn set_client_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_client_token(input); self } /// <p>The authentication token associated with the participant's connection.</p> pub fn connection_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.connection_token(inp); self } /// <p>The authentication token associated with the participant's connection.</p> pub fn set_connection_token( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_connection_token(input); self } } /// Fluent builder constructing a request to `CreateParticipantConnection`. /// /// <p>Creates the participant's connection. Note that ParticipantToken is used for invoking this API instead of /// ConnectionToken.</p> /// <p>The participant token is valid for the lifetime of the participant – /// until they are part of a contact.</p> /// <p>The response URL for <code>WEBSOCKET</code> Type has a connect expiry timeout of 100s. /// Clients must manually connect to the returned websocket URL and subscribe to the desired /// topic. </p> /// <p>For chat, you need to publish the following on the established websocket /// connection:</p> /// <p> /// <code>{"topic":"aws/subscribe","content":{"topics":["aws/chat"]}}</code> /// </p> /// <p>Upon websocket URL expiry, as specified in the response ConnectionExpiry parameter, /// clients need to call this API again to obtain a new websocket URL and perform the same /// steps as before.</p> /// <p> /// <b>Message streaming support</b>: This API can also be used together with the /// <a href="https://docs.aws.amazon.com/connect/latest/APIReference/API_StartContactStreaming.html">StartContactStreaming</a> /// API to create a participant connection for chat contacts that are /// not using a websocket. For more information about message streaming, <a href="https://docs.aws.amazon.com/connect/latest/adminguide/chat-message-streaming.html">Enable real-time chat message streaming</a> in the <i>Amazon Connect /// Administrator Guide</i>.</p> /// <p> /// <b>Feature specifications</b>: For information about feature specifications, such as the allowed number of open /// websocket connections per participant, see <a href="https://docs.aws.amazon.com/connect/latest/adminguide/amazon-connect-service-limits.html#feature-limits">Feature specifications</a> in the <i>Amazon Connect Administrator /// Guide</i>. </p> /// <note> /// <p>The Amazon Connect Participant Service APIs do not use <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature Version 4 /// authentication</a>.</p> /// </note> #[derive(std::fmt::Debug)] pub struct CreateParticipantConnection< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::create_participant_connection_input::Builder, } impl<C, M, R> CreateParticipantConnection<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `CreateParticipantConnection`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::CreateParticipantConnectionOutput, aws_smithy_http::result::SdkError<crate::error::CreateParticipantConnectionError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::CreateParticipantConnectionInputOperationOutputAlias, crate::output::CreateParticipantConnectionOutput, crate::error::CreateParticipantConnectionError, crate::input::CreateParticipantConnectionInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// Appends an item to `Type`. /// /// To override the contents of this collection use [`set_type`](Self::set_type). /// /// <p>Type of connection information required.</p> pub fn r#type(mut self, inp: impl Into<crate::model::ConnectionType>) -> Self { self.inner = self.inner.r#type(inp); self } /// <p>Type of connection information required.</p> pub fn set_type( mut self, input: std::option::Option<std::vec::Vec<crate::model::ConnectionType>>, ) -> Self { self.inner = self.inner.set_type(input); self } /// <p>This is a header parameter.</p> /// <p>The ParticipantToken as obtained from <a href="https://docs.aws.amazon.com/connect/latest/APIReference/API_StartChatContact.html">StartChatContact</a> /// API response.</p> pub fn participant_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.participant_token(inp); self } /// <p>This is a header parameter.</p> /// <p>The ParticipantToken as obtained from <a href="https://docs.aws.amazon.com/connect/latest/APIReference/API_StartChatContact.html">StartChatContact</a> /// API response.</p> pub fn set_participant_token( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_participant_token(input); self } /// <p>Amazon Connect Participant is used to mark the participant as connected for message /// streaming.</p> pub fn connect_participant(mut self, inp: bool) -> Self { self.inner = self.inner.connect_participant(inp); self } /// <p>Amazon Connect Participant is used to mark the participant as connected for message /// streaming.</p> pub fn set_connect_participant(mut self, input: std::option::Option<bool>) -> Self { self.inner = self.inner.set_connect_participant(input); self } } /// Fluent builder constructing a request to `DisconnectParticipant`. /// /// <p>Disconnects a participant. Note that ConnectionToken is used for invoking this API /// instead of ParticipantToken.</p> /// <p>The Amazon Connect Participant Service APIs do not use <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature Version 4 /// authentication</a>.</p> #[derive(std::fmt::Debug)] pub struct DisconnectParticipant< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::disconnect_participant_input::Builder, } impl<C, M, R> DisconnectParticipant<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `DisconnectParticipant`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::DisconnectParticipantOutput, aws_smithy_http::result::SdkError<crate::error::DisconnectParticipantError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::DisconnectParticipantInputOperationOutputAlias, crate::output::DisconnectParticipantOutput, crate::error::DisconnectParticipantError, crate::input::DisconnectParticipantInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p>A unique, case-sensitive identifier that you provide to ensure the idempotency of the /// request.</p> pub fn client_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.client_token(inp); self } /// <p>A unique, case-sensitive identifier that you provide to ensure the idempotency of the /// request.</p> pub fn set_client_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_client_token(input); self } /// <p>The authentication token associated with the participant's connection.</p> pub fn connection_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.connection_token(inp); self } /// <p>The authentication token associated with the participant's connection.</p> pub fn set_connection_token( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_connection_token(input); self } } /// Fluent builder constructing a request to `GetAttachment`. /// /// <p>Provides a pre-signed URL for download of a completed attachment. This is an /// asynchronous API for use with active contacts.</p> /// <p>The Amazon Connect Participant Service APIs do not use <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature Version 4 /// authentication</a>.</p> #[derive(std::fmt::Debug)] pub struct GetAttachment< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::get_attachment_input::Builder, } impl<C, M, R> GetAttachment<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `GetAttachment`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::GetAttachmentOutput, aws_smithy_http::result::SdkError<crate::error::GetAttachmentError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::GetAttachmentInputOperationOutputAlias, crate::output::GetAttachmentOutput, crate::error::GetAttachmentError, crate::input::GetAttachmentInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p>A unique identifier for the attachment.</p> pub fn attachment_id(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.attachment_id(inp); self } /// <p>A unique identifier for the attachment.</p> pub fn set_attachment_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_attachment_id(input); self } /// <p>The authentication token associated with the participant's connection.</p> pub fn connection_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.connection_token(inp); self } /// <p>The authentication token associated with the participant's connection.</p> pub fn set_connection_token( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_connection_token(input); self } } /// Fluent builder constructing a request to `GetTranscript`. /// /// <p>Retrieves a transcript of the session, including details about any attachments. Note /// that ConnectionToken is used for invoking this API instead of ParticipantToken.</p> /// <p>The Amazon Connect Participant Service APIs do not use <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature Version 4 /// authentication</a>.</p> #[derive(std::fmt::Debug)] pub struct GetTranscript< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::get_transcript_input::Builder, } impl<C, M, R> GetTranscript<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `GetTranscript`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::GetTranscriptOutput, aws_smithy_http::result::SdkError<crate::error::GetTranscriptError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::GetTranscriptInputOperationOutputAlias, crate::output::GetTranscriptOutput, crate::error::GetTranscriptError, crate::input::GetTranscriptInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p>The contactId from the current contact chain for which transcript is needed.</p> pub fn contact_id(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.contact_id(inp); self } /// <p>The contactId from the current contact chain for which transcript is needed.</p> pub fn set_contact_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_contact_id(input); self } /// <p>The maximum number of results to return in the page. Default: 10. </p> pub fn max_results(mut self, inp: i32) -> Self { self.inner = self.inner.max_results(inp); self } /// <p>The maximum number of results to return in the page. Default: 10. </p> pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.inner = self.inner.set_max_results(input); self } /// <p>The pagination token. Use the value returned previously in the next subsequent request /// to retrieve the next set of results.</p> pub fn next_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.next_token(inp); self } /// <p>The pagination token. Use the value returned previously in the next subsequent request /// to retrieve the next set of results.</p> pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_next_token(input); self } /// <p>The direction from StartPosition from which to retrieve message. Default: BACKWARD /// when no StartPosition is provided, FORWARD with StartPosition. </p> pub fn scan_direction(mut self, inp: crate::model::ScanDirection) -> Self { self.inner = self.inner.scan_direction(inp); self } /// <p>The direction from StartPosition from which to retrieve message. Default: BACKWARD /// when no StartPosition is provided, FORWARD with StartPosition. </p> pub fn set_scan_direction( mut self, input: std::option::Option<crate::model::ScanDirection>, ) -> Self { self.inner = self.inner.set_scan_direction(input); self } /// <p>The sort order for the records. Default: DESCENDING.</p> pub fn sort_order(mut self, inp: crate::model::SortKey) -> Self { self.inner = self.inner.sort_order(inp); self } /// <p>The sort order for the records. Default: DESCENDING.</p> pub fn set_sort_order(mut self, input: std::option::Option<crate::model::SortKey>) -> Self { self.inner = self.inner.set_sort_order(input); self } /// <p>A filtering option for where to start.</p> pub fn start_position(mut self, inp: crate::model::StartPosition) -> Self { self.inner = self.inner.start_position(inp); self } /// <p>A filtering option for where to start.</p> pub fn set_start_position( mut self, input: std::option::Option<crate::model::StartPosition>, ) -> Self { self.inner = self.inner.set_start_position(input); self } /// <p>The authentication token associated with the participant's connection.</p> pub fn connection_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.connection_token(inp); self } /// <p>The authentication token associated with the participant's connection.</p> pub fn set_connection_token( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_connection_token(input); self } } /// Fluent builder constructing a request to `SendEvent`. /// /// <p>Sends an event. Note that ConnectionToken is used for invoking this API instead of /// ParticipantToken.</p> /// <p>The Amazon Connect Participant Service APIs do not use <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature Version 4 /// authentication</a>.</p> #[derive(std::fmt::Debug)] pub struct SendEvent< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::send_event_input::Builder, } impl<C, M, R> SendEvent<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `SendEvent`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::SendEventOutput, aws_smithy_http::result::SdkError<crate::error::SendEventError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::SendEventInputOperationOutputAlias, crate::output::SendEventOutput, crate::error::SendEventError, crate::input::SendEventInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p>The content type of the request. Supported types are:</p> /// /// <ul> /// <li> /// <p>application/vnd.amazonaws.connect.event.typing</p> /// </li> /// <li> /// <p>application/vnd.amazonaws.connect.event.connection.acknowledged</p> /// </li> /// </ul> pub fn content_type(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.content_type(inp); self } /// <p>The content type of the request. Supported types are:</p> /// /// <ul> /// <li> /// <p>application/vnd.amazonaws.connect.event.typing</p> /// </li> /// <li> /// <p>application/vnd.amazonaws.connect.event.connection.acknowledged</p> /// </li> /// </ul> pub fn set_content_type(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_content_type(input); self } /// <p>The content of the event to be sent (for example, message text). This is not yet /// supported.</p> pub fn content(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.content(inp); self } /// <p>The content of the event to be sent (for example, message text). This is not yet /// supported.</p> pub fn set_content(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_content(input); self } /// <p>A unique, case-sensitive identifier that you provide to ensure the idempotency of the /// request.</p> pub fn client_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.client_token(inp); self } /// <p>A unique, case-sensitive identifier that you provide to ensure the idempotency of the /// request.</p> pub fn set_client_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_client_token(input); self } /// <p>The authentication token associated with the participant's connection.</p> pub fn connection_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.connection_token(inp); self } /// <p>The authentication token associated with the participant's connection.</p> pub fn set_connection_token( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_connection_token(input); self } } /// Fluent builder constructing a request to `SendMessage`. /// /// <p>Sends a message. Note that ConnectionToken is used for invoking this API instead of /// ParticipantToken.</p> /// <p>The Amazon Connect Participant Service APIs do not use <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature Version 4 /// authentication</a>.</p> #[derive(std::fmt::Debug)] pub struct SendMessage< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::send_message_input::Builder, } impl<C, M, R> SendMessage<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `SendMessage`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::SendMessageOutput, aws_smithy_http::result::SdkError<crate::error::SendMessageError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::SendMessageInputOperationOutputAlias, crate::output::SendMessageOutput, crate::error::SendMessageError, crate::input::SendMessageInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p>The type of the content. Supported types are text/plain.</p> pub fn content_type(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.content_type(inp); self } /// <p>The type of the content. Supported types are text/plain.</p> pub fn set_content_type(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_content_type(input); self } /// <p>The content of the message.</p> pub fn content(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.content(inp); self } /// <p>The content of the message.</p> pub fn set_content(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_content(input); self } /// <p>A unique, case-sensitive identifier that you provide to ensure the idempotency of the /// request.</p> pub fn client_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.client_token(inp); self } /// <p>A unique, case-sensitive identifier that you provide to ensure the idempotency of the /// request.</p> pub fn set_client_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_client_token(input); self } /// <p>The authentication token associated with the connection.</p> pub fn connection_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.connection_token(inp); self } /// <p>The authentication token associated with the connection.</p> pub fn set_connection_token( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_connection_token(input); self } } /// Fluent builder constructing a request to `StartAttachmentUpload`. /// /// <p>Provides a pre-signed Amazon S3 URL in response for uploading the file directly to /// S3.</p> /// <p>The Amazon Connect Participant Service APIs do not use <a href="https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature Version 4 /// authentication</a>.</p> #[derive(std::fmt::Debug)] pub struct StartAttachmentUpload< C = aws_smithy_client::erase::DynConnector, M = aws_hyper::AwsMiddleware, R = aws_smithy_client::retry::Standard, > { handle: std::sync::Arc<super::Handle<C, M, R>>, inner: crate::input::start_attachment_upload_input::Builder, } impl<C, M, R> StartAttachmentUpload<C, M, R> where C: aws_smithy_client::bounds::SmithyConnector, M: aws_smithy_client::bounds::SmithyMiddleware<C>, R: aws_smithy_client::retry::NewRequestPolicy, { /// Creates a new `StartAttachmentUpload`. pub(crate) fn new(handle: std::sync::Arc<super::Handle<C, M, R>>) -> Self { Self { handle, inner: Default::default(), } } /// Sends the request and returns the response. /// /// If an error occurs, an `SdkError` will be returned with additional details that /// can be matched against. /// /// By default, any retryable failures will be retried twice. Retry behavior /// is configurable with the [RetryConfig](aws_smithy_types::retry::RetryConfig), which can be /// set when configuring the client. pub async fn send( self, ) -> std::result::Result< crate::output::StartAttachmentUploadOutput, aws_smithy_http::result::SdkError<crate::error::StartAttachmentUploadError>, > where R::Policy: aws_smithy_client::bounds::SmithyRetryPolicy< crate::input::StartAttachmentUploadInputOperationOutputAlias, crate::output::StartAttachmentUploadOutput, crate::error::StartAttachmentUploadError, crate::input::StartAttachmentUploadInputOperationRetryAlias, >, { let input = self.inner.build().map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; let op = input .make_operation(&self.handle.conf) .await .map_err(|err| { aws_smithy_http::result::SdkError::ConstructionFailure(err.into()) })?; self.handle.client.call(op).await } /// <p>Describes the MIME file type of the attachment. For a list of supported file types, see <a href="https://docs.aws.amazon.com/connect/latest/adminguide/amazon-connect-service-limits.html#feature-limits">Feature specifications</a> in the <i>Amazon Connect Administrator Guide</i>.</p> pub fn content_type(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.content_type(inp); self } /// <p>Describes the MIME file type of the attachment. For a list of supported file types, see <a href="https://docs.aws.amazon.com/connect/latest/adminguide/amazon-connect-service-limits.html#feature-limits">Feature specifications</a> in the <i>Amazon Connect Administrator Guide</i>.</p> pub fn set_content_type(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_content_type(input); self } /// <p>The size of the attachment in bytes.</p> pub fn attachment_size_in_bytes(mut self, inp: i64) -> Self { self.inner = self.inner.attachment_size_in_bytes(inp); self } /// <p>The size of the attachment in bytes.</p> pub fn set_attachment_size_in_bytes(mut self, input: std::option::Option<i64>) -> Self { self.inner = self.inner.set_attachment_size_in_bytes(input); self } /// <p>A case-sensitive name of the attachment being uploaded.</p> pub fn attachment_name(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.attachment_name(inp); self } /// <p>A case-sensitive name of the attachment being uploaded.</p> pub fn set_attachment_name( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_attachment_name(input); self } /// <p>A unique case sensitive identifier to support idempotency of request.</p> pub fn client_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.client_token(inp); self } /// <p>A unique case sensitive identifier to support idempotency of request.</p> pub fn set_client_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.inner = self.inner.set_client_token(input); self } /// <p>The authentication token associated with the participant's connection.</p> pub fn connection_token(mut self, inp: impl Into<std::string::String>) -> Self { self.inner = self.inner.connection_token(inp); self } /// <p>The authentication token associated with the participant's connection.</p> pub fn set_connection_token( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.inner = self.inner.set_connection_token(input); self } } } impl<C> Client<C, aws_hyper::AwsMiddleware, aws_smithy_client::retry::Standard> { /// Creates a client with the given service config and connector override. pub fn from_conf_conn(conf: crate::Config, conn: C) -> Self { let retry_config = conf.retry_config.as_ref().cloned().unwrap_or_default(); let client = aws_hyper::Client::new(conn).with_retry_config(retry_config.into()); Self { handle: std::sync::Arc::new(Handle { client, conf }), } } } impl Client< aws_smithy_client::erase::DynConnector, aws_hyper::AwsMiddleware, aws_smithy_client::retry::Standard, > { /// Creates a new client from a shared config. #[cfg(any(feature = "rustls", feature = "native-tls"))] pub fn new(config: &aws_types::config::Config) -> Self { Self::from_conf(config.into()) } /// Creates a new client from the service [`Config`](crate::Config). #[cfg(any(feature = "rustls", feature = "native-tls"))] pub fn from_conf(conf: crate::Config) -> Self { let retry_config = conf.retry_config.as_ref().cloned().unwrap_or_default(); let client = aws_hyper::Client::https().with_retry_config(retry_config.into()); Self { handle: std::sync::Arc::new(Handle { client, conf }), } } }
45.345238
297
0.60456
fec4066a42ee93e70e5e4ea81225ca5329c0d486
1,406
struct Solution; impl Solution { fn check_valid(matrix: Vec<Vec<i32>>) -> bool { let n = matrix.len(); for i in 0..n { let mut col = vec![false; n]; for j in 0..n { let x = matrix[i][j]; if (1..=n as i32).contains(&x) { let k = (x - 1) as usize; col[k] = true; } else { return false; } } for j in 0..n { if !col[j] { return false; } } } for i in 0..n { let mut row = vec![false; n]; for j in 0..n { let x = matrix[j][i]; if (1..=n as i32).contains(&x) { let k = (x - 1) as usize; row[k] = true; } else { return false; } } for j in 0..n { if !row[j] { return false; } } } true } } #[test] fn test() { let matrix = vec_vec_i32![[1, 2, 3], [3, 1, 2], [2, 3, 1]]; let res = true; assert_eq!(Solution::check_valid(matrix), res); let matrix = vec_vec_i32![[1, 1, 1], [1, 2, 3], [1, 2, 3]]; let res = false; assert_eq!(Solution::check_valid(matrix), res); }
26.037037
63
0.347084
9c6089f0fc79849e0f8f787488e5ed3bbb94837e
24,054
//! The reactor notifying [`Async`][`crate::Async`] and [`Timer`][`crate::Timer`]. //! //! There is a single global reactor that contains all registered I/O handles and timers. The //! reactor is polled by the executor, i.e. the [`run()`][`crate::run()`] function. #[cfg(not(any( target_os = "linux", // epoll target_os = "android", // epoll target_os = "illumos", // epoll target_os = "macos", // kqueue target_os = "ios", // kqueue target_os = "freebsd", // kqueue target_os = "netbsd", // kqueue target_os = "openbsd", // kqueue target_os = "dragonfly", // kqueue target_os = "windows", // wepoll )))] compile_error!("reactor does not support this target OS"); use std::collections::BTreeMap; use std::fmt::Debug; use std::io; use std::mem; #[cfg(unix)] use std::os::unix::io::RawFd; #[cfg(windows)] use std::os::windows::io::{FromRawSocket, RawSocket}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::task::{Poll, Waker}; use std::time::{Duration, Instant}; use crossbeam::queue::ArrayQueue; use futures_util::future; #[cfg(unix)] use nix::fcntl::{fcntl, FcntlArg, OFlag}; use once_cell::sync::Lazy; use slab::Slab; #[cfg(windows)] use socket2::Socket; use crate::io_event::IoEvent; /// The reactor. /// /// Every async I/O handle and every timer is registered here. Invocations of /// [`run()`][`crate::run()`] poll the reactor to check for new events every now and then. /// /// There is only one global instance of this type, accessible by [`Reactor::get()`]. pub(crate) struct Reactor { /// Raw bindings to epoll/kqueue/wepoll. sys: sys::Reactor, /// Registered sources. sources: piper::Mutex<Slab<Arc<Source>>>, /// Temporary storage for I/O events when polling the reactor. events: piper::Lock<sys::Events>, /// An ordered map of registered timers. /// /// Timers are in the order in which they fire. The `usize` in this type is a timer ID used to /// distinguish timers that fire at the same time. The `Waker` represents the task awaiting the /// timer. timers: piper::Mutex<BTreeMap<(Instant, usize), Waker>>, /// A queue of timer operations (insert and remove). /// /// When inserting or removing a timer, we don't process it immediately - we just push it into /// this queue. Timers actually get processed when the queue fills up or the reactor is polled. timer_ops: ArrayQueue<TimerOp>, /// An I/O event that is triggered when a new timer is registered. /// /// The reason why this field is lazily created is because `IoEvent`s can be created only after /// the reactor is fully initialized. timer_event: Lazy<IoEvent>, } impl Reactor { /// Returns a reference to the reactor. pub fn get() -> &'static Reactor { static REACTOR: Lazy<Reactor> = Lazy::new(|| Reactor { sys: sys::Reactor::new().expect("cannot initialize I/O event notification"), sources: piper::Mutex::new(Slab::new()), events: piper::Lock::new(sys::Events::new()), timers: piper::Mutex::new(BTreeMap::new()), timer_ops: ArrayQueue::new(1000), timer_event: Lazy::new(|| IoEvent::new().expect("cannot create an `IoEvent`")), }); &REACTOR } /// Registers an I/O source in the reactor. pub fn insert_io( &self, #[cfg(unix)] raw: RawFd, #[cfg(windows)] raw: RawSocket, ) -> io::Result<Arc<Source>> { let mut sources = self.sources.lock(); let vacant = sources.vacant_entry(); // Put the I/O handle in non-blocking mode. #[cfg(unix)] { let flags = fcntl(raw, FcntlArg::F_GETFL).map_err(io_err)?; let flags = OFlag::from_bits_truncate(flags) | OFlag::O_NONBLOCK; fcntl(raw, FcntlArg::F_SETFL(flags)).map_err(io_err)?; } #[cfg(windows)] { let socket = unsafe { Socket::from_raw_socket(raw) }; mem::ManuallyDrop::new(socket).set_nonblocking(true)?; } // Create a source and register it. let key = vacant.key(); self.sys.register(raw, key)?; let source = Arc::new(Source { raw, key, wakers: piper::Mutex::new(Wakers { readers: Vec::new(), writers: Vec::new(), }), }); Ok(vacant.insert(source).clone()) } /// Deregisters an I/O source from the reactor. pub fn remove_io(&self, source: &Source) -> io::Result<()> { let mut sources = self.sources.lock(); sources.remove(source.key); self.sys.deregister(source.raw) } /// Registers a timer in the reactor. /// /// Returns the inserted timer's ID. pub fn insert_timer(&self, when: Instant, waker: &Waker) -> usize { // Generate a new timer ID. static ID_GENERATOR: AtomicUsize = AtomicUsize::new(1); let id = ID_GENERATOR.fetch_add(1, Ordering::Relaxed); // Push an insert operation. while self .timer_ops .push(TimerOp::Insert(when, id, waker.clone())) .is_err() { // Fire timers to drain the queue. self.fire_timers(); } // Notify that a timer was added. self.timer_event.notify(); id } /// Deregisters a timer from the reactor. pub fn remove_timer(&self, when: Instant, id: usize) { // Push a remove operation. while self.timer_ops.push(TimerOp::Remove(when, id)).is_err() { // Fire timers to drain the queue. self.fire_timers(); } } /// Attempts to lock the reactor. pub fn try_lock(&self) -> Option<ReactorLock<'_>> { self.events.try_lock().map(|events| { let reactor = self; ReactorLock { reactor, events } }) } /// Locks the reactor. pub async fn lock(&self) -> ReactorLock<'_> { let reactor = self; let events = self.events.lock().await; ReactorLock { reactor, events } } /// Fires ready timers. /// /// Returns the duration until the next timer before this method was called. fn fire_timers(&self) -> Option<Duration> { // Clear this event because we're about to fire timers. self.timer_event.clear(); let mut timers = self.timers.lock(); // Process timer operations, but no more than the queue capacity because otherwise we could // keep popping operations forever. for _ in 0..self.timer_ops.capacity() { match self.timer_ops.pop() { Ok(TimerOp::Insert(when, id, waker)) => { timers.insert((when, id), waker); } Ok(TimerOp::Remove(when, id)) => { timers.remove(&(when, id)); } Err(_) => break, } } let now = Instant::now(); // Split timers into ready and pending timers. let pending = timers.split_off(&(now, 0)); let ready = mem::replace(&mut *timers, pending); // Calculate the duration until the next event. let dur = if ready.is_empty() { // Duration until the next timer. timers .keys() .next() .map(|(when, _)| when.saturating_duration_since(now)) } else { // Timers are about to fire right now. Some(Duration::from_secs(0)) }; // Wake up tasks waiting on timers. for (_, waker) in ready { waker.wake(); } dur } } /// A lock on the reactor. pub(crate) struct ReactorLock<'a> { reactor: &'a Reactor, events: piper::LockGuard<sys::Events>, } impl ReactorLock<'_> { /// Processes ready events without blocking. pub fn poll(&mut self) -> io::Result<()> { self.react(false) } /// Blocks until at least one event is processed. pub fn wait(&mut self) -> io::Result<()> { self.react(true) } /// Processes new events, optionally blocking until the first event. fn react(&mut self, block: bool) -> io::Result<()> { // Fire timers and compute the timeout for blocking on I/O events. let next_timer = self.reactor.fire_timers(); let timeout = if block { next_timer } else { Some(Duration::from_secs(0)) }; loop { // Block on I/O events. match self.reactor.sys.wait(&mut self.events, timeout) { // The timeout was hit so fire ready timers. Ok(0) => { self.reactor.fire_timers(); return Ok(()); } // At least one I/O event occured. Ok(_) => { // Iterate over sources in the event list. let sources = self.reactor.sources.lock(); for ev in self.events.iter() { // Check if there is a source in the table with this key. if let Some(source) = sources.get(ev.key) { let mut wakers = source.wakers.lock(); // Wake readers if a readability event was emitted. if ev.readable { for w in wakers.readers.drain(..) { w.wake(); } } // Wake writers if a writability event was emitted. if ev.writable { for w in wakers.writers.drain(..) { w.wake(); } } } } return Ok(()); } // The syscall was interrupted. Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, // An actual error occureed. Err(err) => return Err(err), } } } } /// A single timer operation. enum TimerOp { Insert(Instant, usize, Waker), Remove(Instant, usize), } /// A registered source of I/O events. #[derive(Debug)] pub(crate) struct Source { /// Raw file descriptor on Unix platforms. #[cfg(unix)] pub(crate) raw: RawFd, /// Raw socket handle on Windows. #[cfg(windows)] pub(crate) raw: RawSocket, /// The key of this source obtained during registration. key: usize, /// Tasks interested in events on this source. wakers: piper::Mutex<Wakers>, } /// Tasks interested in events on a source. #[derive(Debug)] struct Wakers { /// Tasks waiting for the next readability event. readers: Vec<Waker>, /// Tasks waiting for the next writability event. writers: Vec<Waker>, } impl Source { /// Re-registers the I/O event to wake the poller. pub(crate) fn reregister_io_event(&self) -> io::Result<()> { let wakers = self.wakers.lock(); Reactor::get() .sys .reregister(self.raw, self.key, true, !wakers.writers.is_empty())?; Ok(()) } /// Waits until the I/O source is readable. /// /// This function may occasionally complete even if the I/O source is not readable. pub(crate) async fn readable(&self) -> io::Result<()> { let mut polled = false; future::poll_fn(|cx| { if polled { Poll::Ready(Ok(())) } else { let mut wakers = self.wakers.lock(); // If there are no other readers, re-register in the reactor. if wakers.readers.is_empty() { Reactor::get().sys.reregister( self.raw, self.key, true, !wakers.writers.is_empty(), )?; } // Register the current task's waker if not present already. if wakers.readers.iter().all(|w| !w.will_wake(cx.waker())) { wakers.readers.push(cx.waker().clone()); } polled = true; Poll::Pending } }) .await } /// Waits until the I/O source is writable. /// /// This function may occasionally complete even if the I/O source is not writable. pub(crate) async fn writable(&self) -> io::Result<()> { let mut polled = false; future::poll_fn(|cx| { if polled { Poll::Ready(Ok(())) } else { let mut wakers = self.wakers.lock(); // If there are no other writers, re-register in the reactor. if wakers.writers.is_empty() { Reactor::get().sys.reregister( self.raw, self.key, !wakers.readers.is_empty(), true, )?; } // Register the current task's waker if not present already. if wakers.writers.iter().all(|w| !w.will_wake(cx.waker())) { wakers.writers.push(cx.waker().clone()); } polled = true; Poll::Pending } }) .await } } /// Converts a [`nix::Error`] into [`io::Error`]. #[cfg(unix)] fn io_err(err: nix::Error) -> io::Error { match err { nix::Error::Sys(code) => code.into(), err => io::Error::new(io::ErrorKind::Other, Box::new(err)), } } /// Raw bindings to epoll (Linux, Android, illumos). #[cfg(any(target_os = "linux", target_os = "android", target_os = "illumos"))] mod sys { use std::convert::TryInto; use std::io; use std::os::unix::io::RawFd; use std::time::Duration; use nix::sys::epoll::{ epoll_create1, epoll_ctl, epoll_wait, EpollCreateFlags, EpollEvent, EpollFlags, EpollOp, }; use super::io_err; pub struct Reactor(RawFd); impl Reactor { pub fn new() -> io::Result<Reactor> { let epoll_fd = epoll_create1(EpollCreateFlags::EPOLL_CLOEXEC).map_err(io_err)?; Ok(Reactor(epoll_fd)) } pub fn register(&self, fd: RawFd, key: usize) -> io::Result<()> { let ev = &mut EpollEvent::new(EpollFlags::empty(), key as u64); epoll_ctl(self.0, EpollOp::EpollCtlAdd, fd, Some(ev)).map_err(io_err) } pub fn reregister(&self, fd: RawFd, key: usize, read: bool, write: bool) -> io::Result<()> { let mut flags = EpollFlags::EPOLLONESHOT; if read { flags |= read_flags(); } if write { flags |= write_flags(); } let ev = &mut EpollEvent::new(flags, key as u64); epoll_ctl(self.0, EpollOp::EpollCtlMod, fd, Some(ev)).map_err(io_err) } pub fn deregister(&self, fd: RawFd) -> io::Result<()> { epoll_ctl(self.0, EpollOp::EpollCtlDel, fd, None).map_err(io_err) } pub fn wait(&self, events: &mut Events, timeout: Option<Duration>) -> io::Result<usize> { let timeout_ms = timeout .map(|t| { if t == Duration::from_millis(0) { t } else { t.max(Duration::from_millis(1)) } }) .and_then(|t| t.as_millis().try_into().ok()) .unwrap_or(-1); events.len = epoll_wait(self.0, &mut events.list, timeout_ms).map_err(io_err)?; Ok(events.len) } } fn read_flags() -> EpollFlags { EpollFlags::EPOLLIN | EpollFlags::EPOLLRDHUP } fn write_flags() -> EpollFlags { EpollFlags::EPOLLOUT } pub struct Events { list: Box<[EpollEvent]>, len: usize, } impl Events { pub fn new() -> Events { let list = vec![EpollEvent::empty(); 1000].into_boxed_slice(); let len = 0; Events { list, len } } pub fn iter(&self) -> impl Iterator<Item = Event> + '_ { self.list[..self.len].iter().map(|ev| Event { readable: ev.events().intersects(read_flags()), writable: ev.events().intersects(write_flags()), key: ev.data() as usize, }) } } pub struct Event { pub readable: bool, pub writable: bool, pub key: usize, } } /// Raw bindings to kqueue (macOS, iOS, FreeBSD, NetBSD, OpenBSD, DragonFly BSD). #[cfg(any( target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", target_os = "dragonfly", ))] mod sys { use std::io; use std::os::unix::io::RawFd; use std::time::Duration; use nix::errno::Errno; use nix::fcntl::{fcntl, FcntlArg, FdFlag}; use nix::libc; use nix::sys::event::{kevent_ts, kqueue, EventFilter, EventFlag, FilterFlag, KEvent}; use super::io_err; pub struct Reactor(RawFd); impl Reactor { pub fn new() -> io::Result<Reactor> { let fd = kqueue().map_err(io_err)?; fcntl(fd, FcntlArg::F_SETFD(FdFlag::FD_CLOEXEC)).map_err(io_err)?; Ok(Reactor(fd)) } pub fn register(&self, _fd: RawFd, _key: usize) -> io::Result<()> { Ok(()) } pub fn reregister(&self, fd: RawFd, key: usize, read: bool, write: bool) -> io::Result<()> { let mut read_flags = EventFlag::EV_ONESHOT | EventFlag::EV_RECEIPT; let mut write_flags = EventFlag::EV_ONESHOT | EventFlag::EV_RECEIPT; if read { read_flags |= EventFlag::EV_ADD; } else { read_flags |= EventFlag::EV_DELETE; } if write { write_flags |= EventFlag::EV_ADD; } else { write_flags |= EventFlag::EV_DELETE; } let udata = key as _; let changelist = [ KEvent::new( fd as _, EventFilter::EVFILT_READ, read_flags, FFLAGS, 0, udata, ), KEvent::new( fd as _, EventFilter::EVFILT_WRITE, write_flags, FFLAGS, 0, udata, ), ]; let mut eventlist = changelist; kevent_ts(self.0, &changelist, &mut eventlist, None).map_err(io_err)?; for ev in &eventlist { // Explanation for ignoring EPIPE: https://github.com/tokio-rs/mio/issues/582 let (flags, data) = (ev.flags(), ev.data()); if flags.contains(EventFlag::EV_ERROR) && data != 0 && data != Errno::ENOENT as _ && data != Errno::EPIPE as _ { return Err(io::Error::from_raw_os_error(data as _)); } } Ok(()) } pub fn deregister(&self, fd: RawFd) -> io::Result<()> { let flags = EventFlag::EV_RECEIPT | EventFlag::EV_DELETE; let changelist = [ KEvent::new(fd as _, EventFilter::EVFILT_WRITE, flags, FFLAGS, 0, 0), KEvent::new(fd as _, EventFilter::EVFILT_READ, flags, FFLAGS, 0, 0), ]; let mut eventlist = changelist; kevent_ts(self.0, &changelist, &mut eventlist, None).map_err(io_err)?; for ev in &eventlist { let (flags, data) = (ev.flags(), ev.data()); if flags.contains(EventFlag::EV_ERROR) && data != 0 && data != Errno::ENOENT as _ { return Err(io::Error::from_raw_os_error(data as _)); } } Ok(()) } pub fn wait(&self, events: &mut Events, timeout: Option<Duration>) -> io::Result<usize> { let timeout = timeout.map(|t| libc::timespec { tv_sec: t.as_secs() as libc::time_t, tv_nsec: t.subsec_nanos() as libc::c_long, }); events.len = kevent_ts(self.0, &[], &mut events.list, timeout).map_err(io_err)?; Ok(events.len) } } const FFLAGS: FilterFlag = FilterFlag::empty(); pub struct Events { list: Box<[KEvent]>, len: usize, } impl Events { pub fn new() -> Events { let flags = EventFlag::empty(); let event = KEvent::new(0, EventFilter::EVFILT_USER, flags, FFLAGS, 0, 0); let list = vec![event; 1000].into_boxed_slice(); let len = 0; Events { list, len } } pub fn iter(&self) -> impl Iterator<Item = Event> + '_ { self.list[..self.len].iter().map(|ev| Event { readable: ev.filter() == EventFilter::EVFILT_READ, writable: ev.filter() == EventFilter::EVFILT_WRITE, key: ev.udata() as usize, }) } } pub struct Event { pub readable: bool, pub writable: bool, pub key: usize, } } /// Raw bindings to wepoll (Windows). #[cfg(target_os = "windows")] mod sys { use std::io; use std::os::windows::io::{AsRawSocket, RawSocket}; use std::time::Duration; use wepoll_binding::{Epoll, EventFlag}; pub struct Reactor(Epoll); impl Reactor { pub fn new() -> io::Result<Reactor> { Ok(Reactor(Epoll::new()?)) } pub fn register(&self, sock: RawSocket, key: usize) -> io::Result<()> { self.0.register(&As(sock), EventFlag::empty(), key as u64) } pub fn reregister( &self, sock: RawSocket, key: usize, read: bool, write: bool, ) -> io::Result<()> { let mut flags = EventFlag::ONESHOT; if read { flags |= read_flags(); } if write { flags |= write_flags(); } self.0.reregister(&As(sock), flags, key as u64) } pub fn deregister(&self, sock: RawSocket) -> io::Result<()> { self.0.deregister(&As(sock)) } pub fn wait(&self, events: &mut Events, timeout: Option<Duration>) -> io::Result<usize> { let timeout = timeout.map(|t| { if t == Duration::from_millis(0) { t } else { t.max(Duration::from_millis(1)) } }); events.0.clear(); self.0.poll(&mut events.0, timeout) } } struct As(RawSocket); impl AsRawSocket for As { fn as_raw_socket(&self) -> RawSocket { self.0 } } fn read_flags() -> EventFlag { EventFlag::IN | EventFlag::RDHUP } fn write_flags() -> EventFlag { EventFlag::OUT } pub struct Events(wepoll_binding::Events); impl Events { pub fn new() -> Events { Events(wepoll_binding::Events::with_capacity(1000)) } pub fn iter(&self) -> impl Iterator<Item = Event> + '_ { self.0.iter().map(|ev| Event { readable: ev.flags().intersects(read_flags()), writable: ev.flags().intersects(write_flags()), key: ev.data() as usize, }) } } pub struct Event { pub readable: bool, pub writable: bool, pub key: usize, } }
32.950685
100
0.513303
de1299dcfda130fdc57f4d298470b68337f7e74d
57,607
use std::fmt::{self, Write}; use std::mem; use bytes::{BytesMut}; use http::header::{self, Entry, HeaderName, HeaderValue}; use http::{HeaderMap, Method, StatusCode, Version}; use httparse; use error::Parse; use headers; use proto::{BodyLength, DecodedLength, MessageHead, RequestLine, RequestHead}; use proto::h1::{Encode, Encoder, Http1Transaction, ParseResult, ParseContext, ParsedMessage, date}; const MAX_HEADERS: usize = 100; const AVERAGE_HEADER_SIZE: usize = 30; // totally scientific macro_rules! header_name { ($bytes:expr) => ({ #[cfg(debug_assertions)] { match HeaderName::from_bytes($bytes) { Ok(name) => name, Err(_) => panic!("illegal header name from httparse: {:?}", ::bytes::Bytes::from($bytes)), } } #[cfg(not(debug_assertions))] { HeaderName::from_bytes($bytes) .expect("header name validated by httparse") } }); } macro_rules! header_value { ($bytes:expr) => ({ #[cfg(debug_assertions)] { let __hvb: ::bytes::Bytes = $bytes; match HeaderValue::from_shared(__hvb.clone()) { Ok(name) => name, Err(_) => panic!("illegal header value from httparse: {:?}", __hvb), } } #[cfg(not(debug_assertions))] { // Unsafe: httparse already validated header value unsafe { HeaderValue::from_shared_unchecked($bytes) } } }); } // There are 2 main roles, Client and Server. pub(crate) enum Client {} pub(crate) enum Server {} impl Http1Transaction for Server { type Incoming = RequestLine; type Outgoing = StatusCode; const LOG: &'static str = "{role=server}"; fn parse(buf: &mut BytesMut, ctx: ParseContext) -> ParseResult<RequestLine> { if buf.len() == 0 { return Ok(None); } let mut keep_alive; let is_http_11; let subject; let version; let len; let headers_len; // Unsafe: both headers_indices and headers are using unitialized memory, // but we *never* read any of it until after httparse has assigned // values into it. By not zeroing out the stack memory, this saves // a good ~5% on pipeline benchmarks. let mut headers_indices: [HeaderIndices; MAX_HEADERS] = unsafe { mem::uninitialized() }; { let mut headers: [httparse::Header; MAX_HEADERS] = unsafe { mem::uninitialized() }; trace!("Request.parse([Header; {}], [u8; {}])", headers.len(), buf.len()); let mut req = httparse::Request::new(&mut headers); let bytes = buf.as_ref(); match req.parse(bytes)? { httparse::Status::Complete(parsed_len) => { trace!("Request.parse Complete({})", parsed_len); len = parsed_len; subject = RequestLine( Method::from_bytes(req.method.unwrap().as_bytes())?, req.path.unwrap().parse()? ); version = if req.version.unwrap() == 1 { keep_alive = true; is_http_11 = true; Version::HTTP_11 } else { keep_alive = false; is_http_11 = false; Version::HTTP_10 }; record_header_indices(bytes, &req.headers, &mut headers_indices)?; headers_len = req.headers.len(); //(len, subject, version, headers_len) } httparse::Status::Partial => return Ok(None), } }; let slice = buf.split_to(len).freeze(); // According to https://tools.ietf.org/html/rfc7230#section-3.3.3 // 1. (irrelevant to Request) // 2. (irrelevant to Request) // 3. Transfer-Encoding: chunked has a chunked body. // 4. If multiple differing Content-Length headers or invalid, close connection. // 5. Content-Length header has a sized body. // 6. Length 0. // 7. (irrelevant to Request) let mut decoder = DecodedLength::ZERO; let mut expect_continue = false; let mut con_len = None; let mut is_te = false; let mut is_te_chunked = false; let mut wants_upgrade = subject.0 == Method::CONNECT; let mut headers = ctx.cached_headers .take() .unwrap_or_else(HeaderMap::new); headers.reserve(headers_len); for header in &headers_indices[..headers_len] { let name = header_name!(&slice[header.name.0..header.name.1]); let value = header_value!(slice.slice(header.value.0, header.value.1)); match name { header::TRANSFER_ENCODING => { // https://tools.ietf.org/html/rfc7230#section-3.3.3 // If Transfer-Encoding header is present, and 'chunked' is // not the final encoding, and this is a Request, then it is // mal-formed. A server should respond with 400 Bad Request. if !is_http_11 { debug!("HTTP/1.0 cannot have Transfer-Encoding header"); return Err(Parse::Header); } is_te = true; if headers::is_chunked_(&value) { is_te_chunked = true; decoder = DecodedLength::CHUNKED; } }, header::CONTENT_LENGTH => { if is_te { continue; } let len = value.to_str() .map_err(|_| Parse::Header) .and_then(|s| s.parse().map_err(|_| Parse::Header))?; if let Some(prev) = con_len { if prev != len { debug!( "multiple Content-Length headers with different values: [{}, {}]", prev, len, ); return Err(Parse::Header); } // we don't need to append this secondary length continue; } decoder = DecodedLength::checked_new(len)?; con_len = Some(len); }, header::CONNECTION => { // keep_alive was previously set to default for Version if keep_alive { // HTTP/1.1 keep_alive = !headers::connection_close(&value); } else { // HTTP/1.0 keep_alive = headers::connection_keep_alive(&value); } }, header::EXPECT => { expect_continue = value.as_bytes() == b"100-continue"; }, header::UPGRADE => { // Upgrades are only allowed with HTTP/1.1 wants_upgrade = is_http_11; }, _ => (), } headers.append(name, value); } if is_te && !is_te_chunked { debug!("request with transfer-encoding header, but not chunked, bad request"); return Err(Parse::Header); } *ctx.req_method = Some(subject.0.clone()); Ok(Some(ParsedMessage { head: MessageHead { version, subject, headers, }, decode: decoder, expect_continue, keep_alive, wants_upgrade, })) } fn encode(mut msg: Encode<Self::Outgoing>, mut dst: &mut Vec<u8>) -> ::Result<Encoder> { trace!( "Server::encode status={:?}, body={:?}, req_method={:?}", msg.head.subject, msg.body, msg.req_method ); debug_assert!(!msg.title_case_headers, "no server config for title case headers"); // hyper currently doesn't support returning 1xx status codes as a Response // This is because Service only allows returning a single Response, and // so if you try to reply with a e.g. 100 Continue, you have no way of // replying with the latter status code response. let is_upgrade = msg.head.subject == StatusCode::SWITCHING_PROTOCOLS || (msg.req_method == &Some(Method::CONNECT) && msg.head.subject.is_success()); let (ret, mut is_last) = if is_upgrade { (Ok(()), true) } else if msg.head.subject.is_informational() { warn!("response with 1xx status code not supported"); *msg.head = MessageHead::default(); msg.head.subject = StatusCode::INTERNAL_SERVER_ERROR; msg.body = None; (Err(::Error::new_user_unsupported_status_code()), true) } else { (Ok(()), !msg.keep_alive) }; // In some error cases, we don't know about the invalid message until already // pushing some bytes onto the `dst`. In those cases, we don't want to send // the half-pushed message, so rewind to before. let orig_len = dst.len(); let rewind = |dst: &mut Vec<u8>| { dst.truncate(orig_len); }; let init_cap = 30 + msg.head.headers.len() * AVERAGE_HEADER_SIZE; dst.reserve(init_cap); if msg.head.version == Version::HTTP_11 && msg.head.subject == StatusCode::OK { extend(dst, b"HTTP/1.1 200 OK\r\n"); } else { match msg.head.version { Version::HTTP_10 => extend(dst, b"HTTP/1.0 "), Version::HTTP_11 => extend(dst, b"HTTP/1.1 "), Version::HTTP_2 => { warn!("response with HTTP2 version coerced to HTTP/1.1"); extend(dst, b"HTTP/1.1 "); }, _ => unreachable!(), } extend(dst, msg.head.subject.as_str().as_bytes()); extend(dst, b" "); // a reason MUST be written, as many parsers will expect it. extend(dst, msg.head.subject.canonical_reason().unwrap_or("<none>").as_bytes()); extend(dst, b"\r\n"); } let mut encoder = Encoder::length(0); let mut wrote_len = false; let mut wrote_date = false; 'headers: for (name, mut values) in msg.head.headers.drain() { match name { header::CONTENT_LENGTH => { if wrote_len { warn!("transfer-encoding and content-length both found, canceling"); rewind(dst); return Err(::Error::new_header()); } match msg.body { Some(BodyLength::Known(known_len)) => { // The Payload claims to know a length, and // the headers are already set. For performance // reasons, we are just going to trust that // the values match. // // In debug builds, we'll assert they are the // same to help developers find bugs. encoder = Encoder::length(known_len); #[cfg(debug_assertions)] { let mut folded = None::<(u64, HeaderValue)>; for value in values { if let Some(len) = headers::content_length_parse(&value) { if let Some(fold) = folded { if fold.0 != len { panic!("multiple Content-Length values found: [{}, {}]", fold.0, len); } folded = Some(fold); } else { folded = Some((len, value)); } } else { panic!("illegal Content-Length value: {:?}", value); } } if let Some((len, value)) = folded { assert!( len == known_len, "payload claims content-length of {}, custom content-length header claims {}", known_len, len, ); extend(dst, b"content-length: "); extend(dst, value.as_bytes()); extend(dst, b"\r\n"); wrote_len = true; continue 'headers; } else { // No values in content-length... ignore? continue 'headers; } } }, Some(BodyLength::Unknown) => { // The Payload impl didn't know how long the // body is, but a length header was included. // We have to parse the value to return our // Encoder... let mut folded = None::<(u64, HeaderValue)>; for value in values { if let Some(len) = headers::content_length_parse(&value) { if let Some(fold) = folded { if fold.0 != len { warn!("multiple Content-Length values found: [{}, {}]", fold.0, len); rewind(dst); return Err(::Error::new_header()); } folded = Some(fold); } else { folded = Some((len, value)); } } else { warn!("illegal Content-Length value: {:?}", value); rewind(dst); return Err(::Error::new_header()); } } if let Some((len, value)) = folded { encoder = Encoder::length(len); extend(dst, b"content-length: "); extend(dst, value.as_bytes()); extend(dst, b"\r\n"); wrote_len = true; continue 'headers; } else { // No values in content-length... ignore? continue 'headers; } }, None => { // We have no body to actually send, // but the headers claim a content-length. // There's only 2 ways this makes sense: // // - The header says the length is `0`. // - This is a response to a `HEAD` request. if msg.req_method == &Some(Method::HEAD) { debug_assert_eq!(encoder, Encoder::length(0)); } else { for value in values { if value.as_bytes() != b"0" { warn!("content-length value found, but empty body provided: {:?}", value); } } continue 'headers; } } } wrote_len = true; }, header::TRANSFER_ENCODING => { if wrote_len { warn!("transfer-encoding and content-length both found, canceling"); rewind(dst); return Err(::Error::new_header()); } // check that we actually can send a chunked body... if msg.head.version == Version::HTTP_10 || !Server::can_chunked(msg.req_method, msg.head.subject) { continue; } wrote_len = true; encoder = Encoder::chunked(); extend(dst, b"transfer-encoding: "); let mut saw_chunked; if let Some(te) = values.next() { extend(dst, te.as_bytes()); saw_chunked = headers::is_chunked_(&te); for value in values { extend(dst, b", "); extend(dst, value.as_bytes()); saw_chunked = headers::is_chunked_(&value); } if !saw_chunked { extend(dst, b", chunked\r\n"); } else { extend(dst, b"\r\n"); } } else { // zero lines? add a chunked line then extend(dst, b"chunked\r\n"); } continue 'headers; }, header::CONNECTION => { if !is_last { for value in values { extend(dst, name.as_str().as_bytes()); extend(dst, b": "); extend(dst, value.as_bytes()); extend(dst, b"\r\n"); if headers::connection_close(&value) { is_last = true; } } continue 'headers; } }, header::DATE => { wrote_date = true; }, _ => (), } //TODO: this should perhaps instead combine them into //single lines, as RFC7230 suggests is preferable. for value in values { extend(dst, name.as_str().as_bytes()); extend(dst, b": "); extend(dst, value.as_bytes()); extend(dst, b"\r\n"); } } if !wrote_len { encoder = match msg.body { Some(BodyLength::Unknown) => { if msg.head.version == Version::HTTP_10 || !Server::can_chunked(msg.req_method, msg.head.subject) { Encoder::close_delimited() } else { extend(dst, b"transfer-encoding: chunked\r\n"); Encoder::chunked() } }, None | Some(BodyLength::Known(0)) => { extend(dst, b"content-length: 0\r\n"); Encoder::length(0) }, Some(BodyLength::Known(len)) => { extend(dst, b"content-length: "); let _ = ::itoa::write(&mut dst, len); extend(dst, b"\r\n"); Encoder::length(len) }, }; } if !Server::can_have_body(msg.req_method, msg.head.subject) { trace!( "server body forced to 0; method={:?}, status={:?}", msg.req_method, msg.head.subject ); encoder = Encoder::length(0); } // cached date is much faster than formatting every request if !wrote_date { dst.reserve(date::DATE_VALUE_LENGTH + 8); extend(dst, b"date: "); date::extend(dst); extend(dst, b"\r\n\r\n"); } else { extend(dst, b"\r\n"); } ret.map(|()| encoder.set_last(is_last)) } fn on_error(err: &::Error) -> Option<MessageHead<Self::Outgoing>> { use ::error::{Kind, Parse}; let status = match *err.kind() { Kind::Parse(Parse::Method) | Kind::Parse(Parse::Header) | Kind::Parse(Parse::Uri) | Kind::Parse(Parse::Version) => { StatusCode::BAD_REQUEST }, Kind::Parse(Parse::TooLarge) => { StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE }, _ => return None, }; debug!("sending automatic response ({}) for parse error", status); let mut msg = MessageHead::default(); msg.subject = status; Some(msg) } fn should_error_on_parse_eof() -> bool { false } fn should_read_first() -> bool { true } fn update_date() { date::update(); } } impl Server { fn can_have_body(method: &Option<Method>, status: StatusCode) -> bool { Server::can_chunked(method, status) } fn can_chunked(method: &Option<Method>, status: StatusCode) -> bool { if method == &Some(Method::HEAD) { false } else if method == &Some(Method::CONNECT) && status.is_success() { false } else { match status { // TODO: support for 1xx codes needs improvement everywhere // would be 100...199 => false StatusCode::SWITCHING_PROTOCOLS | StatusCode::NO_CONTENT | StatusCode::NOT_MODIFIED => false, _ => true, } } } } impl Http1Transaction for Client { type Incoming = StatusCode; type Outgoing = RequestLine; const LOG: &'static str = "{role=client}"; fn parse(buf: &mut BytesMut, ctx: ParseContext) -> ParseResult<StatusCode> { // Loop to skip information status code headers (100 Continue, etc). loop { if buf.len() == 0 { return Ok(None); } // Unsafe: see comment in Server Http1Transaction, above. let mut headers_indices: [HeaderIndices; MAX_HEADERS] = unsafe { mem::uninitialized() }; let (len, status, version, headers_len) = { let mut headers: [httparse::Header; MAX_HEADERS] = unsafe { mem::uninitialized() }; trace!("Response.parse([Header; {}], [u8; {}])", headers.len(), buf.len()); let mut res = httparse::Response::new(&mut headers); let bytes = buf.as_ref(); match res.parse(bytes)? { httparse::Status::Complete(len) => { trace!("Response.parse Complete({})", len); let status = StatusCode::from_u16(res.code.unwrap())?; let version = if res.version.unwrap() == 1 { Version::HTTP_11 } else { Version::HTTP_10 }; record_header_indices(bytes, &res.headers, &mut headers_indices)?; let headers_len = res.headers.len(); (len, status, version, headers_len) }, httparse::Status::Partial => return Ok(None), } }; let slice = buf.split_to(len).freeze(); let mut headers = ctx.cached_headers .take() .unwrap_or_else(HeaderMap::new); let mut keep_alive = version == Version::HTTP_11; headers.reserve(headers_len); for header in &headers_indices[..headers_len] { let name = header_name!(&slice[header.name.0..header.name.1]); let value = header_value!(slice.slice(header.value.0, header.value.1)); match name { header::CONNECTION => { // keep_alive was previously set to default for Version if keep_alive { // HTTP/1.1 keep_alive = !headers::connection_close(&value); } else { // HTTP/1.0 keep_alive = headers::connection_keep_alive(&value); } }, _ => (), } headers.append(name, value); } let head = MessageHead { version, subject: status, headers, }; if let Some((decode, is_upgrade)) = Client::decoder(&head, ctx.req_method)? { return Ok(Some(ParsedMessage { head, decode, expect_continue: false, // a client upgrade means the connection can't be used // again, as it is definitely upgrading. keep_alive: keep_alive && !is_upgrade, wants_upgrade: is_upgrade, })); } } } fn encode(msg: Encode<Self::Outgoing>, dst: &mut Vec<u8>) -> ::Result<Encoder> { trace!("Client::encode method={:?}, body={:?}", msg.head.subject.0, msg.body); *msg.req_method = Some(msg.head.subject.0.clone()); let body = Client::set_length(msg.head, msg.body); let init_cap = 30 + msg.head.headers.len() * AVERAGE_HEADER_SIZE; dst.reserve(init_cap); extend(dst, msg.head.subject.0.as_str().as_bytes()); extend(dst, b" "); //TODO: add API to http::Uri to encode without std::fmt let _ = write!(FastWrite(dst), "{} ", msg.head.subject.1); match msg.head.version { Version::HTTP_10 => extend(dst, b"HTTP/1.0"), Version::HTTP_11 => extend(dst, b"HTTP/1.1"), _ => unreachable!(), } extend(dst, b"\r\n"); if msg.title_case_headers { write_headers_title_case(&msg.head.headers, dst); } else { write_headers(&msg.head.headers, dst); } extend(dst, b"\r\n"); msg.head.headers.clear(); //TODO: remove when switching to drain() Ok(body) } fn on_error(_err: &::Error) -> Option<MessageHead<Self::Outgoing>> { // we can't tell the server about any errors it creates None } fn should_error_on_parse_eof() -> bool { true } fn should_read_first() -> bool { false } } impl Client { /// Returns Some(length, wants_upgrade) if successful. /// /// Returns None if this message head should be skipped (like a 100 status). fn decoder(inc: &MessageHead<StatusCode>, method: &mut Option<Method>) -> Result<Option<(DecodedLength, bool)>, Parse> { // According to https://tools.ietf.org/html/rfc7230#section-3.3.3 // 1. HEAD responses, and Status 1xx, 204, and 304 cannot have a body. // 2. Status 2xx to a CONNECT cannot have a body. // 3. Transfer-Encoding: chunked has a chunked body. // 4. If multiple differing Content-Length headers or invalid, close connection. // 5. Content-Length header has a sized body. // 6. (irrelevant to Response) // 7. Read till EOF. match inc.subject.as_u16() { 101 => { return Ok(Some((DecodedLength::ZERO, true))); }, 100...199 => { trace!("ignoring informational response: {}", inc.subject.as_u16()); return Ok(None); }, 204 | 304 => return Ok(Some((DecodedLength::ZERO, false))), _ => (), } match *method { Some(Method::HEAD) => { return Ok(Some((DecodedLength::ZERO, false))); } Some(Method::CONNECT) => match inc.subject.as_u16() { 200...299 => { return Ok(Some((DecodedLength::ZERO, true))); }, _ => {}, }, Some(_) => {}, None => { trace!("Client::decoder is missing the Method"); } } if inc.headers.contains_key(header::TRANSFER_ENCODING) { // https://tools.ietf.org/html/rfc7230#section-3.3.3 // If Transfer-Encoding header is present, and 'chunked' is // not the final encoding, and this is a Request, then it is // mal-formed. A server should respond with 400 Bad Request. if inc.version == Version::HTTP_10 { debug!("HTTP/1.0 cannot have Transfer-Encoding header"); Err(Parse::Header) } else if headers::transfer_encoding_is_chunked(&inc.headers) { Ok(Some((DecodedLength::CHUNKED, false))) } else { trace!("not chunked, read till eof"); Ok(Some((DecodedLength::CHUNKED, false))) } } else if let Some(len) = headers::content_length_parse_all(&inc.headers) { Ok(Some((DecodedLength::checked_new(len)?, false))) } else if inc.headers.contains_key(header::CONTENT_LENGTH) { debug!("illegal Content-Length header"); Err(Parse::Header) } else { trace!("neither Transfer-Encoding nor Content-Length"); Ok(Some((DecodedLength::CLOSE_DELIMITED, false))) } } } impl Client { fn set_length(head: &mut RequestHead, body: Option<BodyLength>) -> Encoder { if let Some(body) = body { let can_chunked = head.version == Version::HTTP_11 && (head.subject.0 != Method::HEAD) && (head.subject.0 != Method::GET) && (head.subject.0 != Method::CONNECT); set_length(&mut head.headers, body, can_chunked) } else { head.headers.remove(header::TRANSFER_ENCODING); Encoder::length(0) } } } fn set_length(headers: &mut HeaderMap, body: BodyLength, can_chunked: bool) -> Encoder { // If the user already set specific headers, we should respect them, regardless // of what the Payload knows about itself. They set them for a reason. // Because of the borrow checker, we can't check the for an existing // Content-Length header while holding an `Entry` for the Transfer-Encoding // header, so unfortunately, we must do the check here, first. let existing_con_len = headers::content_length_parse_all(headers); let mut should_remove_con_len = false; if can_chunked { // If the user set a transfer-encoding, respect that. Let's just // make sure `chunked` is the final encoding. let encoder = match headers.entry(header::TRANSFER_ENCODING) .expect("TRANSFER_ENCODING is valid HeaderName") { Entry::Occupied(te) => { should_remove_con_len = true; if headers::is_chunked(te.iter()) { Some(Encoder::chunked()) } else { warn!("user provided transfer-encoding does not end in 'chunked'"); // There's a Transfer-Encoding, but it doesn't end in 'chunked'! // An example that could trigger this: // // Transfer-Encoding: gzip // // This can be bad, depending on if this is a request or a // response. // // - A request is illegal if there is a `Transfer-Encoding` // but it doesn't end in `chunked`. // - A response that has `Transfer-Encoding` but doesn't // end in `chunked` isn't illegal, it just forces this // to be close-delimited. // // We can try to repair this, by adding `chunked` ourselves. headers::add_chunked(te); Some(Encoder::chunked()) } }, Entry::Vacant(te) => { if let Some(len) = existing_con_len { Some(Encoder::length(len)) } else if let BodyLength::Unknown = body { should_remove_con_len = true; te.insert(HeaderValue::from_static("chunked")); Some(Encoder::chunked()) } else { None } }, }; // This is because we need a second mutable borrow to remove // content-length header. if let Some(encoder) = encoder { if should_remove_con_len && existing_con_len.is_some() { headers.remove(header::CONTENT_LENGTH); } return encoder; } // User didn't set transfer-encoding, AND we know body length, // so we can just set the Content-Length automatically. let len = if let BodyLength::Known(len) = body { len } else { unreachable!("BodyLength::Unknown would set chunked"); }; set_content_length(headers, len) } else { // Chunked isn't legal, so if it is set, we need to remove it. // Also, if it *is* set, then we shouldn't replace with a length, // since the user tried to imply there isn't a length. let encoder = if headers.remove(header::TRANSFER_ENCODING).is_some() { trace!("removing illegal transfer-encoding header"); should_remove_con_len = true; Encoder::close_delimited() } else if let Some(len) = existing_con_len { Encoder::length(len) } else if let BodyLength::Known(len) = body { set_content_length(headers, len) } else { Encoder::close_delimited() }; if should_remove_con_len && existing_con_len.is_some() { headers.remove(header::CONTENT_LENGTH); } encoder } } fn set_content_length(headers: &mut HeaderMap, len: u64) -> Encoder { // At this point, there should not be a valid Content-Length // header. However, since we'll be indexing in anyways, we can // warn the user if there was an existing illegal header. // // Or at least, we can in theory. It's actually a little bit slower, // so perhaps only do that while the user is developing/testing. if cfg!(debug_assertions) { match headers.entry(header::CONTENT_LENGTH) .expect("CONTENT_LENGTH is valid HeaderName") { Entry::Occupied(mut cl) => { // Internal sanity check, we should have already determined // that the header was illegal before calling this function. debug_assert!(headers::content_length_parse_all_values(cl.iter()).is_none()); // Uh oh, the user set `Content-Length` headers, but set bad ones. // This would be an illegal message anyways, so let's try to repair // with our known good length. error!("user provided content-length header was invalid"); cl.insert(HeaderValue::from(len)); Encoder::length(len) }, Entry::Vacant(cl) => { cl.insert(HeaderValue::from(len)); Encoder::length(len) } } } else { headers.insert(header::CONTENT_LENGTH, HeaderValue::from(len)); Encoder::length(len) } } #[derive(Clone, Copy)] struct HeaderIndices { name: (usize, usize), value: (usize, usize), } fn record_header_indices( bytes: &[u8], headers: &[httparse::Header], indices: &mut [HeaderIndices] ) -> Result<(), ::error::Parse> { let bytes_ptr = bytes.as_ptr() as usize; // FIXME: This should be a single plain `for` loop. // Splitting it is a work-around for https://github.com/rust-lang/rust/issues/55105 macro_rules! split_loops_if { ( cfg($($cfg: tt)+) for $i: pat in ($iter: expr) { $body1: block $body2: block } ) => { for $i in $iter { $body1 #[cfg(not($($cfg)+))] $body2 } #[cfg($($cfg)+)] for $i in $iter { $body2 } } } split_loops_if! { cfg(all(target_arch = "arm", target_feature = "v7", target_feature = "neon")) for (header, indices) in (headers.iter().zip(indices.iter_mut())) { { if header.name.len() >= (1 << 16) { debug!("header name larger than 64kb: {:?}", header.name); return Err(::error::Parse::TooLarge); } let name_start = header.name.as_ptr() as usize - bytes_ptr; let name_end = name_start + header.name.len(); indices.name = (name_start, name_end); } { let value_start = header.value.as_ptr() as usize - bytes_ptr; let value_end = value_start + header.value.len(); indices.value = (value_start, value_end); } } } Ok(()) } // Write header names as title case. The header name is assumed to be ASCII, // therefore it is trivial to convert an ASCII character from lowercase to // uppercase. It is as simple as XORing the lowercase character byte with // space. fn title_case(dst: &mut Vec<u8>, name: &[u8]) { dst.reserve(name.len()); let mut iter = name.iter(); // Uppercase the first character if let Some(c) = iter.next() { if *c >= b'a' && *c <= b'z' { dst.push(*c ^ b' '); } else { dst.push(*c); } } while let Some(c) = iter.next() { dst.push(*c); if *c == b'-' { if let Some(c) = iter.next() { if *c >= b'a' && *c <= b'z' { dst.push(*c ^ b' '); } else { dst.push(*c); } } } } } fn write_headers_title_case(headers: &HeaderMap, dst: &mut Vec<u8>) { for (name, value) in headers { title_case(dst, name.as_str().as_bytes()); extend(dst, b": "); extend(dst, value.as_bytes()); extend(dst, b"\r\n"); } } fn write_headers(headers: &HeaderMap, dst: &mut Vec<u8>) { for (name, value) in headers { extend(dst, name.as_str().as_bytes()); extend(dst, b": "); extend(dst, value.as_bytes()); extend(dst, b"\r\n"); } } struct FastWrite<'a>(&'a mut Vec<u8>); impl<'a> fmt::Write for FastWrite<'a> { #[inline] fn write_str(&mut self, s: &str) -> fmt::Result { extend(self.0, s.as_bytes()); Ok(()) } #[inline] fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result { fmt::write(self, args) } } #[inline] fn extend(dst: &mut Vec<u8>, data: &[u8]) { dst.extend_from_slice(data); } #[cfg(test)] mod tests { use bytes::BytesMut; use super::*; #[test] fn test_parse_request() { extern crate pretty_env_logger; let _ = pretty_env_logger::try_init(); let mut raw = BytesMut::from(b"GET /echo HTTP/1.1\r\nHost: hyper.rs\r\n\r\n".to_vec()); let mut method = None; let msg = Server::parse(&mut raw, ParseContext { cached_headers: &mut None, req_method: &mut method, }).unwrap().unwrap(); assert_eq!(raw.len(), 0); assert_eq!(msg.head.subject.0, ::Method::GET); assert_eq!(msg.head.subject.1, "/echo"); assert_eq!(msg.head.version, ::Version::HTTP_11); assert_eq!(msg.head.headers.len(), 1); assert_eq!(msg.head.headers["Host"], "hyper.rs"); assert_eq!(method, Some(::Method::GET)); } #[test] fn test_parse_response() { extern crate pretty_env_logger; let _ = pretty_env_logger::try_init(); let mut raw = BytesMut::from(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n".to_vec()); let ctx = ParseContext { cached_headers: &mut None, req_method: &mut Some(::Method::GET), }; let msg = Client::parse(&mut raw, ctx).unwrap().unwrap(); assert_eq!(raw.len(), 0); assert_eq!(msg.head.subject, ::StatusCode::OK); assert_eq!(msg.head.version, ::Version::HTTP_11); assert_eq!(msg.head.headers.len(), 1); assert_eq!(msg.head.headers["Content-Length"], "0"); } #[test] fn test_parse_request_errors() { let mut raw = BytesMut::from(b"GET htt:p// HTTP/1.1\r\nHost: hyper.rs\r\n\r\n".to_vec()); let ctx = ParseContext { cached_headers: &mut None, req_method: &mut None, }; Server::parse(&mut raw, ctx).unwrap_err(); } #[test] fn test_decoder_request() { fn parse(s: &str) -> ParsedMessage<RequestLine> { let mut bytes = BytesMut::from(s); Server::parse(&mut bytes, ParseContext { cached_headers: &mut None, req_method: &mut None, }) .expect("parse ok") .expect("parse complete") } fn parse_err(s: &str, comment: &str) -> ::error::Parse { let mut bytes = BytesMut::from(s); Server::parse(&mut bytes, ParseContext { cached_headers: &mut None, req_method: &mut None, }) .expect_err(comment) } // no length or transfer-encoding means 0-length body assert_eq!(parse("\ GET / HTTP/1.1\r\n\ \r\n\ ").decode, DecodedLength::ZERO); assert_eq!(parse("\ POST / HTTP/1.1\r\n\ \r\n\ ").decode, DecodedLength::ZERO); // transfer-encoding: chunked assert_eq!(parse("\ POST / HTTP/1.1\r\n\ transfer-encoding: chunked\r\n\ \r\n\ ").decode, DecodedLength::CHUNKED); assert_eq!(parse("\ POST / HTTP/1.1\r\n\ transfer-encoding: gzip, chunked\r\n\ \r\n\ ").decode, DecodedLength::CHUNKED); assert_eq!(parse("\ POST / HTTP/1.1\r\n\ transfer-encoding: gzip\r\n\ transfer-encoding: chunked\r\n\ \r\n\ ").decode, DecodedLength::CHUNKED); // content-length assert_eq!(parse("\ POST / HTTP/1.1\r\n\ content-length: 10\r\n\ \r\n\ ").decode, DecodedLength::new(10)); // transfer-encoding and content-length = chunked assert_eq!(parse("\ POST / HTTP/1.1\r\n\ content-length: 10\r\n\ transfer-encoding: chunked\r\n\ \r\n\ ").decode, DecodedLength::CHUNKED); assert_eq!(parse("\ POST / HTTP/1.1\r\n\ transfer-encoding: chunked\r\n\ content-length: 10\r\n\ \r\n\ ").decode, DecodedLength::CHUNKED); assert_eq!(parse("\ POST / HTTP/1.1\r\n\ transfer-encoding: gzip\r\n\ content-length: 10\r\n\ transfer-encoding: chunked\r\n\ \r\n\ ").decode, DecodedLength::CHUNKED); // multiple content-lengths of same value are fine assert_eq!(parse("\ POST / HTTP/1.1\r\n\ content-length: 10\r\n\ content-length: 10\r\n\ \r\n\ ").decode, DecodedLength::new(10)); // multiple content-lengths with different values is an error parse_err("\ POST / HTTP/1.1\r\n\ content-length: 10\r\n\ content-length: 11\r\n\ \r\n\ ", "multiple content-lengths"); // transfer-encoding that isn't chunked is an error parse_err("\ POST / HTTP/1.1\r\n\ transfer-encoding: gzip\r\n\ \r\n\ ", "transfer-encoding but not chunked"); parse_err("\ POST / HTTP/1.1\r\n\ transfer-encoding: chunked, gzip\r\n\ \r\n\ ", "transfer-encoding doesn't end in chunked"); // http/1.0 assert_eq!(parse("\ POST / HTTP/1.0\r\n\ content-length: 10\r\n\ \r\n\ ").decode, DecodedLength::new(10)); // 1.0 doesn't understand chunked, so its an error parse_err("\ POST / HTTP/1.0\r\n\ transfer-encoding: chunked\r\n\ \r\n\ ", "1.0 chunked"); } #[test] fn test_decoder_response() { fn parse(s: &str) -> ParsedMessage<StatusCode> { parse_with_method(s, Method::GET) } fn parse_ignores(s: &str) { let mut bytes = BytesMut::from(s); assert!(Client::parse(&mut bytes, ParseContext { cached_headers: &mut None, req_method: &mut Some(Method::GET), }) .expect("parse ok") .is_none()) } fn parse_with_method(s: &str, m: Method) -> ParsedMessage<StatusCode> { let mut bytes = BytesMut::from(s); Client::parse(&mut bytes, ParseContext { cached_headers: &mut None, req_method: &mut Some(m), }) .expect("parse ok") .expect("parse complete") } fn parse_err(s: &str) -> ::error::Parse { let mut bytes = BytesMut::from(s); Client::parse(&mut bytes, ParseContext { cached_headers: &mut None, req_method: &mut Some(Method::GET), }) .expect_err("parse should err") } // no content-length or transfer-encoding means close-delimited assert_eq!(parse("\ HTTP/1.1 200 OK\r\n\ \r\n\ ").decode, DecodedLength::CLOSE_DELIMITED); // 204 and 304 never have a body assert_eq!(parse("\ HTTP/1.1 204 No Content\r\n\ \r\n\ ").decode, DecodedLength::ZERO); assert_eq!(parse("\ HTTP/1.1 304 Not Modified\r\n\ \r\n\ ").decode, DecodedLength::ZERO); // content-length assert_eq!(parse("\ HTTP/1.1 200 OK\r\n\ content-length: 8\r\n\ \r\n\ ").decode, DecodedLength::new(8)); assert_eq!(parse("\ HTTP/1.1 200 OK\r\n\ content-length: 8\r\n\ content-length: 8\r\n\ \r\n\ ").decode, DecodedLength::new(8)); parse_err("\ HTTP/1.1 200 OK\r\n\ content-length: 8\r\n\ content-length: 9\r\n\ \r\n\ "); // transfer-encoding assert_eq!(parse("\ HTTP/1.1 200 OK\r\n\ transfer-encoding: chunked\r\n\ \r\n\ ").decode, DecodedLength::CHUNKED); // transfer-encoding and content-length = chunked assert_eq!(parse("\ HTTP/1.1 200 OK\r\n\ content-length: 10\r\n\ transfer-encoding: chunked\r\n\ \r\n\ ").decode, DecodedLength::CHUNKED); // HEAD can have content-length, but not body assert_eq!(parse_with_method("\ HTTP/1.1 200 OK\r\n\ content-length: 8\r\n\ \r\n\ ", Method::HEAD).decode, DecodedLength::ZERO); // CONNECT with 200 never has body { let msg = parse_with_method("\ HTTP/1.1 200 OK\r\n\ \r\n\ ", Method::CONNECT); assert_eq!(msg.decode, DecodedLength::ZERO); assert!(!msg.keep_alive, "should be upgrade"); assert!(msg.wants_upgrade, "should be upgrade"); } // CONNECT receiving non 200 can have a body assert_eq!(parse_with_method("\ HTTP/1.1 400 Bad Request\r\n\ \r\n\ ", Method::CONNECT).decode, DecodedLength::CLOSE_DELIMITED); // 1xx status codes parse_ignores("\ HTTP/1.1 100 Continue\r\n\ \r\n\ "); parse_ignores("\ HTTP/1.1 103 Early Hints\r\n\ \r\n\ "); // 101 upgrade not supported yet { let msg = parse("\ HTTP/1.1 101 Switching Protocols\r\n\ \r\n\ "); assert_eq!(msg.decode, DecodedLength::ZERO); assert!(!msg.keep_alive, "should be last"); assert!(msg.wants_upgrade, "should be upgrade"); } // http/1.0 assert_eq!(parse("\ HTTP/1.0 200 OK\r\n\ \r\n\ ").decode, DecodedLength::CLOSE_DELIMITED); // 1.0 doesn't understand chunked parse_err("\ HTTP/1.0 200 OK\r\n\ transfer-encoding: chunked\r\n\ \r\n\ "); // keep-alive assert!(parse("\ HTTP/1.1 200 OK\r\n\ content-length: 0\r\n\ \r\n\ ").keep_alive, "HTTP/1.1 keep-alive is default"); assert!(!parse("\ HTTP/1.1 200 OK\r\n\ content-length: 0\r\n\ connection: foo, close, bar\r\n\ \r\n\ ").keep_alive, "connection close is always close"); assert!(!parse("\ HTTP/1.0 200 OK\r\n\ content-length: 0\r\n\ \r\n\ ").keep_alive, "HTTP/1.0 close is default"); assert!(parse("\ HTTP/1.0 200 OK\r\n\ content-length: 0\r\n\ connection: foo, keep-alive, bar\r\n\ \r\n\ ").keep_alive, "connection keep-alive is always keep-alive"); } #[test] fn test_client_request_encode_title_case() { use http::header::HeaderValue; use proto::BodyLength; let mut head = MessageHead::default(); head.headers.insert("content-length", HeaderValue::from_static("10")); head.headers.insert("content-type", HeaderValue::from_static("application/json")); head.headers.insert("*-*", HeaderValue::from_static("o_o")); let mut vec = Vec::new(); Client::encode(Encode { head: &mut head, body: Some(BodyLength::Known(10)), keep_alive: true, req_method: &mut None, title_case_headers: true, }, &mut vec).unwrap(); assert_eq!(vec, b"GET / HTTP/1.1\r\nContent-Length: 10\r\nContent-Type: application/json\r\n*-*: o_o\r\n\r\n".to_vec()); } #[test] fn test_server_encode_connect_method() { let mut head = MessageHead::default(); let mut vec = Vec::new(); let encoder = Server::encode(Encode { head: &mut head, body: None, keep_alive: true, req_method: &mut Some(Method::CONNECT), title_case_headers: false, }, &mut vec).unwrap(); assert!(encoder.is_last()); } #[test] fn parse_header_htabs() { let mut bytes = BytesMut::from("HTTP/1.1 200 OK\r\nserver: hello\tworld\r\n\r\n"); let parsed = Client::parse(&mut bytes, ParseContext { cached_headers: &mut None, req_method: &mut Some(Method::GET), }) .expect("parse ok") .expect("parse complete"); assert_eq!(parsed.head.headers["server"], "hello\tworld"); } #[cfg(feature = "nightly")] use test::Bencher; #[cfg(feature = "nightly")] #[bench] fn bench_parse_incoming(b: &mut Bencher) { let mut raw = BytesMut::from( b"GET /super_long_uri/and_whatever?what_should_we_talk_about/\ I_wonder/Hard_to_write_in_an_uri_after_all/you_have_to_make\ _up_the_punctuation_yourself/how_fun_is_that?test=foo&test1=\ foo1&test2=foo2&test3=foo3&test4=foo4 HTTP/1.1\r\nHost: \ hyper.rs\r\nAccept: a lot of things\r\nAccept-Charset: \ utf8\r\nAccept-Encoding: *\r\nAccess-Control-Allow-\ Credentials: None\r\nAccess-Control-Allow-Origin: None\r\n\ Access-Control-Allow-Methods: None\r\nAccess-Control-Allow-\ Headers: None\r\nContent-Encoding: utf8\r\nContent-Security-\ Policy: None\r\nContent-Type: text/html\r\nOrigin: hyper\ \r\nSec-Websocket-Extensions: It looks super important!\r\n\ Sec-Websocket-Origin: hyper\r\nSec-Websocket-Version: 4.3\r\ \nStrict-Transport-Security: None\r\nUser-Agent: hyper\r\n\ X-Content-Duration: None\r\nX-Content-Security-Policy: None\ \r\nX-DNSPrefetch-Control: None\r\nX-Frame-Options: \ Something important obviously\r\nX-Requested-With: Nothing\ \r\n\r\n".to_vec() ); let len = raw.len(); let mut headers = Some(HeaderMap::new()); b.bytes = len as u64; b.iter(|| { let mut msg = Server::parse(&mut raw, ParseContext { cached_headers: &mut headers, req_method: &mut None, }).unwrap().unwrap(); ::test::black_box(&msg); msg.head.headers.clear(); headers = Some(msg.head.headers); restart(&mut raw, len); }); fn restart(b: &mut BytesMut, len: usize) { b.reserve(1); unsafe { b.set_len(len); } } } #[cfg(feature = "nightly")] #[bench] fn bench_parse_short(b: &mut Bencher) { let s = &b"GET / HTTP/1.1\r\nHost: localhost:8080\r\n\r\n"[..]; let mut raw = BytesMut::from(s.to_vec()); let len = raw.len(); let mut headers = Some(HeaderMap::new()); b.bytes = len as u64; b.iter(|| { let mut msg = Server::parse(&mut raw, ParseContext { cached_headers: &mut headers, req_method: &mut None, }).unwrap().unwrap(); ::test::black_box(&msg); msg.head.headers.clear(); headers = Some(msg.head.headers); restart(&mut raw, len); }); fn restart(b: &mut BytesMut, len: usize) { b.reserve(1); unsafe { b.set_len(len); } } } #[cfg(feature = "nightly")] #[bench] fn bench_server_encode_headers_preset(b: &mut Bencher) { use http::header::HeaderValue; use proto::BodyLength; let len = 108; b.bytes = len as u64; let mut head = MessageHead::default(); let mut headers = HeaderMap::new(); headers.insert("content-length", HeaderValue::from_static("10")); headers.insert("content-type", HeaderValue::from_static("application/json")); b.iter(|| { let mut vec = Vec::new(); head.headers = headers.clone(); Server::encode(Encode { head: &mut head, body: Some(BodyLength::Known(10)), keep_alive: true, req_method: &mut Some(Method::GET), title_case_headers: false, }, &mut vec).unwrap(); assert_eq!(vec.len(), len); ::test::black_box(vec); }) } #[cfg(feature = "nightly")] #[bench] fn bench_server_encode_no_headers(b: &mut Bencher) { use proto::BodyLength; let len = 76; b.bytes = len as u64; let mut head = MessageHead::default(); let mut vec = Vec::with_capacity(128); b.iter(|| { Server::encode(Encode { head: &mut head, body: Some(BodyLength::Known(10)), keep_alive: true, req_method: &mut Some(Method::GET), title_case_headers: false, }, &mut vec).unwrap(); assert_eq!(vec.len(), len); ::test::black_box(&vec); vec.clear(); }) } }
36.162586
128
0.477702
230c1258185867f553e7722e29e8198234e5f2e6
1,749
//! CLI options and logging setup use lazy_static::lazy_static; use log::{info, trace, warn}; use serde_derive::Deserialize; use std::env::{set_var, var}; use structopt::StructOpt; /// deciduously-com backend #[derive(Debug, Deserialize, StructOpt)] #[structopt(name = "rollenspielsahce-svc")] pub struct Opt { /// Server address #[structopt(short, long, default_value = "127.0.0.1")] pub address: String, /// Server port 0-65535 #[structopt(short, long, default_value = "9292")] pub port: u16, } lazy_static! { pub static ref OPT: Opt = { let toml_opt = include_str!("config.toml"); if std::env::args().nth(2).is_some() { // If anything was passed, override config.toml Opt::from_args() } else { toml::from_str(toml_opt).unwrap() } }; } /// Start env_logger pub fn init_logging(level: u8) { // if RUST_BACKTRACE is set, ignore the arg given and set `trace` no matter what let mut overridden = false; let verbosity = if std::env::var("RUST_BACKTRACE").unwrap_or_else(|_| "0".into()) == "1" { overridden = true; "trace" } else { match level { 0 => "error", 1 => "warn", 2 => "info", 3 => "debug", _ => "trace", } }; set_var("RUST_LOG", verbosity); pretty_env_logger::init(); if overridden { warn!("RUST_BACKTRACE is set, overriding user verbosity level"); } else if verbosity == "trace" { set_var("RUST_BACKTRACE", "1"); trace!("RUST_BACKTRACE has been set"); }; info!( "Set verbosity to {}", var("RUST_LOG").expect("Should set RUST_LOG environment variable") ); }
27.761905
94
0.578045
6785ea55fca7f305d7c7209acc8ecb8b1ae17efa
73
mod Trigonometry; mod RegressionAnalysis; mod Conversions; mod Bases;
9.125
23
0.794521
720be1b14c7411ebb97b6a323dceb508b5997215
5,999
// Generated from definition io.k8s.api.apps.v1beta2.ReplicaSetSpec /// ReplicaSetSpec is the specification of a ReplicaSet. #[derive(Clone, Debug, Default, PartialEq)] pub struct ReplicaSetSpec { /// Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready) pub min_ready_seconds: Option<i32>, /// Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/#what-is-a-replicationcontroller pub replicas: Option<i32>, /// Selector is a label query over pods that should match the replica count. Label keys and values that must match in order to be controlled by this replica set. It must match the pod template's labels. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors pub selector: crate::v1_8::apimachinery::pkg::apis::meta::v1::LabelSelector, /// Template is the object that describes the pod that will be created if insufficient replicas are detected. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template pub template: Option<crate::v1_8::api::core::v1::PodTemplateSpec>, } impl<'de> serde::Deserialize<'de> for ReplicaSetSpec { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { #[allow(non_camel_case_types)] enum Field { Key_min_ready_seconds, Key_replicas, Key_selector, Key_template, Other, } impl<'de> serde::Deserialize<'de> for Field { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = Field; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "field identifier") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error { Ok(match v { "minReadySeconds" => Field::Key_min_ready_seconds, "replicas" => Field::Key_replicas, "selector" => Field::Key_selector, "template" => Field::Key_template, _ => Field::Other, }) } } deserializer.deserialize_identifier(Visitor) } } struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = ReplicaSetSpec; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "struct ReplicaSetSpec") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> { let mut value_min_ready_seconds: Option<i32> = None; let mut value_replicas: Option<i32> = None; let mut value_selector: Option<crate::v1_8::apimachinery::pkg::apis::meta::v1::LabelSelector> = None; let mut value_template: Option<crate::v1_8::api::core::v1::PodTemplateSpec> = None; while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? { match key { Field::Key_min_ready_seconds => value_min_ready_seconds = serde::de::MapAccess::next_value(&mut map)?, Field::Key_replicas => value_replicas = serde::de::MapAccess::next_value(&mut map)?, Field::Key_selector => value_selector = Some(serde::de::MapAccess::next_value(&mut map)?), Field::Key_template => value_template = serde::de::MapAccess::next_value(&mut map)?, Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; }, } } Ok(ReplicaSetSpec { min_ready_seconds: value_min_ready_seconds, replicas: value_replicas, selector: value_selector.ok_or_else(|| serde::de::Error::missing_field("selector"))?, template: value_template, }) } } deserializer.deserialize_struct( "ReplicaSetSpec", &[ "minReadySeconds", "replicas", "selector", "template", ], Visitor, ) } } impl serde::Serialize for ReplicaSetSpec { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer { let mut state = serializer.serialize_struct( "ReplicaSetSpec", 1 + self.min_ready_seconds.as_ref().map_or(0, |_| 1) + self.replicas.as_ref().map_or(0, |_| 1) + self.template.as_ref().map_or(0, |_| 1), )?; if let Some(value) = &self.min_ready_seconds { serde::ser::SerializeStruct::serialize_field(&mut state, "minReadySeconds", value)?; } if let Some(value) = &self.replicas { serde::ser::SerializeStruct::serialize_field(&mut state, "replicas", value)?; } serde::ser::SerializeStruct::serialize_field(&mut state, "selector", &self.selector)?; if let Some(value) = &self.template { serde::ser::SerializeStruct::serialize_field(&mut state, "template", value)?; } serde::ser::SerializeStruct::end(state) } }
47.992
307
0.57743
d7818046f29f5a5b0c2dd0ec09f5e1d4cb6990a9
226
pub fn square_of_sum(n: u32) -> u32 { let x = n * (n+1) / 2; x * x } pub fn sum_of_squares(n: u32) -> u32 { n * (n+1) * (2*n+1) / 6 } pub fn difference(n: u32) -> u32 { square_of_sum(n) - sum_of_squares(n) }
17.384615
40
0.526549
284f4b0d13d79e1cf03c1b84dd77cf8cda366c6e
95,041
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(clippy::unnecessary_wraps)] pub fn parse_add_profile_permission_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::AddProfilePermissionOutput, crate::error::AddProfilePermissionError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::AddProfilePermissionError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::AddProfilePermissionError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::AddProfilePermissionError { meta: generic, kind: crate::error::AddProfilePermissionErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_access_denied_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::AddProfilePermissionError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ConflictException" => crate::error::AddProfilePermissionError { meta: generic, kind: crate::error::AddProfilePermissionErrorKind::ConflictException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::conflict_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_conflict_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::AddProfilePermissionError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::AddProfilePermissionError { meta: generic, kind: crate::error::AddProfilePermissionErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::AddProfilePermissionError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => { crate::error::AddProfilePermissionError { meta: generic, kind: crate::error::AddProfilePermissionErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_resource_not_found_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::AddProfilePermissionError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), } } "ServiceLimitExceededException" => crate::error::AddProfilePermissionError { meta: generic, kind: crate::error::AddProfilePermissionErrorKind::ServiceLimitExceededException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::service_limit_exceeded_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_service_limit_exceeded_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::AddProfilePermissionError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TooManyRequestsException" => crate::error::AddProfilePermissionError { meta: generic, kind: crate::error::AddProfilePermissionErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::AddProfilePermissionError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ValidationException" => crate::error::AddProfilePermissionError { meta: generic, kind: crate::error::AddProfilePermissionErrorKind::ValidationException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::validation_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_validation_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::AddProfilePermissionError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::AddProfilePermissionError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_add_profile_permission_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::AddProfilePermissionOutput, crate::error::AddProfilePermissionError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::add_profile_permission_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_add_profile_permission( response.body().as_ref(), output, ) .map_err(crate::error::AddProfilePermissionError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_cancel_signing_profile_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::CancelSigningProfileOutput, crate::error::CancelSigningProfileError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::CancelSigningProfileError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::CancelSigningProfileError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::CancelSigningProfileError { meta: generic, kind: crate::error::CancelSigningProfileErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_access_denied_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::CancelSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::CancelSigningProfileError { meta: generic, kind: crate::error::CancelSigningProfileErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::CancelSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => { crate::error::CancelSigningProfileError { meta: generic, kind: crate::error::CancelSigningProfileErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_resource_not_found_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::CancelSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), } } "TooManyRequestsException" => crate::error::CancelSigningProfileError { meta: generic, kind: crate::error::CancelSigningProfileErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::CancelSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::CancelSigningProfileError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_cancel_signing_profile_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::CancelSigningProfileOutput, crate::error::CancelSigningProfileError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::cancel_signing_profile_output::Builder::default(); let _ = response; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_describe_signing_job_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::DescribeSigningJobOutput, crate::error::DescribeSigningJobError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::DescribeSigningJobError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::DescribeSigningJobError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::DescribeSigningJobError { meta: generic, kind: crate::error::DescribeSigningJobErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_access_denied_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::DescribeSigningJobError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::DescribeSigningJobError { meta: generic, kind: crate::error::DescribeSigningJobErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeSigningJobError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => { crate::error::DescribeSigningJobError { meta: generic, kind: crate::error::DescribeSigningJobErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_resource_not_found_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::DescribeSigningJobError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), } } "TooManyRequestsException" => crate::error::DescribeSigningJobError { meta: generic, kind: crate::error::DescribeSigningJobErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::DescribeSigningJobError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::DescribeSigningJobError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_describe_signing_job_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::DescribeSigningJobOutput, crate::error::DescribeSigningJobError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::describe_signing_job_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_describe_signing_job( response.body().as_ref(), output, ) .map_err(crate::error::DescribeSigningJobError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_get_signing_platform_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::GetSigningPlatformOutput, crate::error::GetSigningPlatformError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::GetSigningPlatformError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::GetSigningPlatformError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::GetSigningPlatformError { meta: generic, kind: crate::error::GetSigningPlatformErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_access_denied_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::GetSigningPlatformError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::GetSigningPlatformError { meta: generic, kind: crate::error::GetSigningPlatformErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::GetSigningPlatformError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => { crate::error::GetSigningPlatformError { meta: generic, kind: crate::error::GetSigningPlatformErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_resource_not_found_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::GetSigningPlatformError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), } } "TooManyRequestsException" => crate::error::GetSigningPlatformError { meta: generic, kind: crate::error::GetSigningPlatformErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::GetSigningPlatformError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::GetSigningPlatformError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_get_signing_platform_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::GetSigningPlatformOutput, crate::error::GetSigningPlatformError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::get_signing_platform_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_get_signing_platform( response.body().as_ref(), output, ) .map_err(crate::error::GetSigningPlatformError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_get_signing_profile_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::GetSigningProfileOutput, crate::error::GetSigningProfileError> { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::GetSigningProfileError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::GetSigningProfileError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::GetSigningProfileError { meta: generic, kind: crate::error::GetSigningProfileErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_access_denied_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::GetSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::GetSigningProfileError { meta: generic, kind: crate::error::GetSigningProfileErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::GetSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => { crate::error::GetSigningProfileError { meta: generic, kind: crate::error::GetSigningProfileErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_resource_not_found_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::GetSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), } } "TooManyRequestsException" => crate::error::GetSigningProfileError { meta: generic, kind: crate::error::GetSigningProfileErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::GetSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::GetSigningProfileError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_get_signing_profile_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::GetSigningProfileOutput, crate::error::GetSigningProfileError> { Ok({ #[allow(unused_mut)] let mut output = crate::output::get_signing_profile_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_get_signing_profile( response.body().as_ref(), output, ) .map_err(crate::error::GetSigningProfileError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_list_profile_permissions_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::ListProfilePermissionsOutput, crate::error::ListProfilePermissionsError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::ListProfilePermissionsError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => { return Err(crate::error::ListProfilePermissionsError::unhandled( generic, )) } }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::ListProfilePermissionsError { meta: generic, kind: crate::error::ListProfilePermissionsErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_access_denied_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::ListProfilePermissionsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::ListProfilePermissionsError { meta: generic, kind: crate::error::ListProfilePermissionsErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::ListProfilePermissionsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => { crate::error::ListProfilePermissionsError { meta: generic, kind: crate::error::ListProfilePermissionsErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_resource_not_found_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::ListProfilePermissionsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), } } "TooManyRequestsException" => crate::error::ListProfilePermissionsError { meta: generic, kind: crate::error::ListProfilePermissionsErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::ListProfilePermissionsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ValidationException" => crate::error::ListProfilePermissionsError { meta: generic, kind: crate::error::ListProfilePermissionsErrorKind::ValidationException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::validation_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_validation_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::ListProfilePermissionsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::ListProfilePermissionsError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_list_profile_permissions_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::ListProfilePermissionsOutput, crate::error::ListProfilePermissionsError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::list_profile_permissions_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_list_profile_permissions( response.body().as_ref(), output, ) .map_err(crate::error::ListProfilePermissionsError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_list_signing_jobs_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::ListSigningJobsOutput, crate::error::ListSigningJobsError> { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::ListSigningJobsError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::ListSigningJobsError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::ListSigningJobsError { meta: generic, kind: crate::error::ListSigningJobsErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_access_denied_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::ListSigningJobsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::ListSigningJobsError { meta: generic, kind: crate::error::ListSigningJobsErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::ListSigningJobsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TooManyRequestsException" => crate::error::ListSigningJobsError { meta: generic, kind: crate::error::ListSigningJobsErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::ListSigningJobsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ValidationException" => crate::error::ListSigningJobsError { meta: generic, kind: crate::error::ListSigningJobsErrorKind::ValidationException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::validation_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_validation_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::ListSigningJobsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::ListSigningJobsError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_list_signing_jobs_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::ListSigningJobsOutput, crate::error::ListSigningJobsError> { Ok({ #[allow(unused_mut)] let mut output = crate::output::list_signing_jobs_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_list_signing_jobs(response.body().as_ref(), output) .map_err(crate::error::ListSigningJobsError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_list_signing_platforms_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::ListSigningPlatformsOutput, crate::error::ListSigningPlatformsError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::ListSigningPlatformsError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::ListSigningPlatformsError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::ListSigningPlatformsError { meta: generic, kind: crate::error::ListSigningPlatformsErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_access_denied_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::ListSigningPlatformsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::ListSigningPlatformsError { meta: generic, kind: crate::error::ListSigningPlatformsErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::ListSigningPlatformsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TooManyRequestsException" => crate::error::ListSigningPlatformsError { meta: generic, kind: crate::error::ListSigningPlatformsErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::ListSigningPlatformsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ValidationException" => crate::error::ListSigningPlatformsError { meta: generic, kind: crate::error::ListSigningPlatformsErrorKind::ValidationException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::validation_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_validation_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::ListSigningPlatformsError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::ListSigningPlatformsError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_list_signing_platforms_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::ListSigningPlatformsOutput, crate::error::ListSigningPlatformsError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::list_signing_platforms_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_list_signing_platforms( response.body().as_ref(), output, ) .map_err(crate::error::ListSigningPlatformsError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_list_signing_profiles_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::ListSigningProfilesOutput, crate::error::ListSigningProfilesError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::ListSigningProfilesError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::ListSigningProfilesError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::ListSigningProfilesError { meta: generic, kind: crate::error::ListSigningProfilesErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_access_denied_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::ListSigningProfilesError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::ListSigningProfilesError { meta: generic, kind: crate::error::ListSigningProfilesErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::ListSigningProfilesError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TooManyRequestsException" => crate::error::ListSigningProfilesError { meta: generic, kind: crate::error::ListSigningProfilesErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::ListSigningProfilesError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::ListSigningProfilesError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_list_signing_profiles_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::ListSigningProfilesOutput, crate::error::ListSigningProfilesError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::list_signing_profiles_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_list_signing_profiles( response.body().as_ref(), output, ) .map_err(crate::error::ListSigningProfilesError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_list_tags_for_resource_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::ListTagsForResourceOutput, crate::error::ListTagsForResourceError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::ListTagsForResourceError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::ListTagsForResourceError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "BadRequestException" => crate::error::ListTagsForResourceError { meta: generic, kind: crate::error::ListTagsForResourceErrorKind::BadRequestException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::bad_request_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_bad_request_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::ListTagsForResourceError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::ListTagsForResourceError { meta: generic, kind: crate::error::ListTagsForResourceErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::ListTagsForResourceError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "NotFoundException" => crate::error::ListTagsForResourceError { meta: generic, kind: crate::error::ListTagsForResourceErrorKind::NotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_not_found_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::ListTagsForResourceError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TooManyRequestsException" => crate::error::ListTagsForResourceError { meta: generic, kind: crate::error::ListTagsForResourceErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::ListTagsForResourceError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::ListTagsForResourceError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_list_tags_for_resource_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::ListTagsForResourceOutput, crate::error::ListTagsForResourceError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::list_tags_for_resource_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_list_tags_for_resource( response.body().as_ref(), output, ) .map_err(crate::error::ListTagsForResourceError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_put_signing_profile_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::PutSigningProfileOutput, crate::error::PutSigningProfileError> { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::PutSigningProfileError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::PutSigningProfileError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::PutSigningProfileError { meta: generic, kind: crate::error::PutSigningProfileErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_access_denied_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::PutSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::PutSigningProfileError { meta: generic, kind: crate::error::PutSigningProfileErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::PutSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => { crate::error::PutSigningProfileError { meta: generic, kind: crate::error::PutSigningProfileErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_resource_not_found_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::PutSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), } } "TooManyRequestsException" => crate::error::PutSigningProfileError { meta: generic, kind: crate::error::PutSigningProfileErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::PutSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ValidationException" => crate::error::PutSigningProfileError { meta: generic, kind: crate::error::PutSigningProfileErrorKind::ValidationException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::validation_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_validation_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::PutSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::PutSigningProfileError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_put_signing_profile_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::PutSigningProfileOutput, crate::error::PutSigningProfileError> { Ok({ #[allow(unused_mut)] let mut output = crate::output::put_signing_profile_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_put_signing_profile( response.body().as_ref(), output, ) .map_err(crate::error::PutSigningProfileError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_remove_profile_permission_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::RemoveProfilePermissionOutput, crate::error::RemoveProfilePermissionError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::RemoveProfilePermissionError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => { return Err(crate::error::RemoveProfilePermissionError::unhandled( generic, )) } }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::RemoveProfilePermissionError { meta: generic, kind: crate::error::RemoveProfilePermissionErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_access_denied_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::RemoveProfilePermissionError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ConflictException" => crate::error::RemoveProfilePermissionError { meta: generic, kind: crate::error::RemoveProfilePermissionErrorKind::ConflictException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::conflict_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_conflict_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::RemoveProfilePermissionError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::RemoveProfilePermissionError { meta: generic, kind: crate::error::RemoveProfilePermissionErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::RemoveProfilePermissionError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => { crate::error::RemoveProfilePermissionError { meta: generic, kind: crate::error::RemoveProfilePermissionErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_resource_not_found_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::RemoveProfilePermissionError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), } } "TooManyRequestsException" => crate::error::RemoveProfilePermissionError { meta: generic, kind: crate::error::RemoveProfilePermissionErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::RemoveProfilePermissionError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ValidationException" => crate::error::RemoveProfilePermissionError { meta: generic, kind: crate::error::RemoveProfilePermissionErrorKind::ValidationException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::validation_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_validation_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::RemoveProfilePermissionError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::RemoveProfilePermissionError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_remove_profile_permission_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::RemoveProfilePermissionOutput, crate::error::RemoveProfilePermissionError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::remove_profile_permission_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_remove_profile_permission( response.body().as_ref(), output, ) .map_err(crate::error::RemoveProfilePermissionError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_revoke_signature_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::RevokeSignatureOutput, crate::error::RevokeSignatureError> { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::RevokeSignatureError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::RevokeSignatureError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::RevokeSignatureError { meta: generic, kind: crate::error::RevokeSignatureErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_access_denied_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::RevokeSignatureError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::RevokeSignatureError { meta: generic, kind: crate::error::RevokeSignatureErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::RevokeSignatureError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => { crate::error::RevokeSignatureError { meta: generic, kind: crate::error::RevokeSignatureErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_resource_not_found_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::RevokeSignatureError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), } } "TooManyRequestsException" => crate::error::RevokeSignatureError { meta: generic, kind: crate::error::RevokeSignatureErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::RevokeSignatureError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ValidationException" => crate::error::RevokeSignatureError { meta: generic, kind: crate::error::RevokeSignatureErrorKind::ValidationException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::validation_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_validation_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::RevokeSignatureError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::RevokeSignatureError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_revoke_signature_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::RevokeSignatureOutput, crate::error::RevokeSignatureError> { Ok({ #[allow(unused_mut)] let mut output = crate::output::revoke_signature_output::Builder::default(); let _ = response; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_revoke_signing_profile_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::RevokeSigningProfileOutput, crate::error::RevokeSigningProfileError, > { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::RevokeSigningProfileError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::RevokeSigningProfileError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::RevokeSigningProfileError { meta: generic, kind: crate::error::RevokeSigningProfileErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_access_denied_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::RevokeSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::RevokeSigningProfileError { meta: generic, kind: crate::error::RevokeSigningProfileErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::RevokeSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => { crate::error::RevokeSigningProfileError { meta: generic, kind: crate::error::RevokeSigningProfileErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_resource_not_found_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::RevokeSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), } } "TooManyRequestsException" => crate::error::RevokeSigningProfileError { meta: generic, kind: crate::error::RevokeSigningProfileErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::RevokeSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ValidationException" => crate::error::RevokeSigningProfileError { meta: generic, kind: crate::error::RevokeSigningProfileErrorKind::ValidationException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::validation_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_validation_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::RevokeSigningProfileError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::RevokeSigningProfileError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_revoke_signing_profile_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result< crate::output::RevokeSigningProfileOutput, crate::error::RevokeSigningProfileError, > { Ok({ #[allow(unused_mut)] let mut output = crate::output::revoke_signing_profile_output::Builder::default(); let _ = response; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_start_signing_job_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::StartSigningJobOutput, crate::error::StartSigningJobError> { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::StartSigningJobError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::StartSigningJobError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "AccessDeniedException" => crate::error::StartSigningJobError { meta: generic, kind: crate::error::StartSigningJobErrorKind::AccessDeniedException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::access_denied_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_access_denied_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::StartSigningJobError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::StartSigningJobError { meta: generic, kind: crate::error::StartSigningJobErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::StartSigningJobError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ResourceNotFoundException" => { crate::error::StartSigningJobError { meta: generic, kind: crate::error::StartSigningJobErrorKind::ResourceNotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::resource_not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_resource_not_found_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::StartSigningJobError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), } } "ThrottlingException" => crate::error::StartSigningJobError { meta: generic, kind: crate::error::StartSigningJobErrorKind::ThrottlingException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::throttling_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_throttling_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::StartSigningJobError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TooManyRequestsException" => crate::error::StartSigningJobError { meta: generic, kind: crate::error::StartSigningJobErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::StartSigningJobError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "ValidationException" => crate::error::StartSigningJobError { meta: generic, kind: crate::error::StartSigningJobErrorKind::ValidationException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::validation_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_validation_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::StartSigningJobError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::StartSigningJobError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_start_signing_job_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::StartSigningJobOutput, crate::error::StartSigningJobError> { Ok({ #[allow(unused_mut)] let mut output = crate::output::start_signing_job_output::Builder::default(); let _ = response; output = crate::json_deser::deser_operation_start_signing_job(response.body().as_ref(), output) .map_err(crate::error::StartSigningJobError::unhandled)?; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_tag_resource_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::TagResourceOutput, crate::error::TagResourceError> { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::TagResourceError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::TagResourceError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "BadRequestException" => crate::error::TagResourceError { meta: generic, kind: crate::error::TagResourceErrorKind::BadRequestException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::bad_request_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_bad_request_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::TagResourceError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::TagResourceError { meta: generic, kind: crate::error::TagResourceErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::TagResourceError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "NotFoundException" => crate::error::TagResourceError { meta: generic, kind: crate::error::TagResourceErrorKind::NotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_not_found_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::TagResourceError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TooManyRequestsException" => crate::error::TagResourceError { meta: generic, kind: crate::error::TagResourceErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::TagResourceError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::TagResourceError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_tag_resource_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::TagResourceOutput, crate::error::TagResourceError> { Ok({ #[allow(unused_mut)] let mut output = crate::output::tag_resource_output::Builder::default(); let _ = response; output.build() }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_untag_resource_error( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::UntagResourceOutput, crate::error::UntagResourceError> { let generic = crate::json_deser::parse_http_generic_error(response) .map_err(crate::error::UntagResourceError::unhandled)?; let error_code = match generic.code() { Some(code) => code, None => return Err(crate::error::UntagResourceError::unhandled(generic)), }; let _error_message = generic.message().map(|msg| msg.to_owned()); Err(match error_code { "BadRequestException" => crate::error::UntagResourceError { meta: generic, kind: crate::error::UntagResourceErrorKind::BadRequestException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::bad_request_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_bad_request_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::UntagResourceError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "InternalServiceErrorException" => crate::error::UntagResourceError { meta: generic, kind: crate::error::UntagResourceErrorKind::InternalServiceErrorException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::internal_service_error_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_internal_service_error_exceptionjson_err(response.body().as_ref(), output).map_err(crate::error::UntagResourceError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "NotFoundException" => crate::error::UntagResourceError { meta: generic, kind: crate::error::UntagResourceErrorKind::NotFoundException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::not_found_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_not_found_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::UntagResourceError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, "TooManyRequestsException" => crate::error::UntagResourceError { meta: generic, kind: crate::error::UntagResourceErrorKind::TooManyRequestsException({ #[allow(unused_mut)] let mut tmp = { #[allow(unused_mut)] let mut output = crate::error::too_many_requests_exception::Builder::default(); let _ = response; output = crate::json_deser::deser_structure_too_many_requests_exceptionjson_err( response.body().as_ref(), output, ) .map_err(crate::error::UntagResourceError::unhandled)?; output.build() }; if (&tmp.message).is_none() { tmp.message = _error_message; } tmp }), }, _ => crate::error::UntagResourceError::generic(generic), }) } #[allow(clippy::unnecessary_wraps)] pub fn parse_untag_resource_response( response: &http::Response<bytes::Bytes>, ) -> std::result::Result<crate::output::UntagResourceOutput, crate::error::UntagResourceError> { Ok({ #[allow(unused_mut)] let mut output = crate::output::untag_resource_output::Builder::default(); let _ = response; output.build() }) }
42.966094
203
0.523027
28f0b2c85decc89f6d40052fd99c93624e827ce4
263
//! Zcash global and per-network constants. pub mod mainnet; pub mod testnet; pub mod regtest; pub const SPROUT_CONSENSUS_BRANCH_ID: u32 = 0; pub const OVERWINTER_CONSENSUS_BRANCH_ID: u32 = 0x5ba8_1b19; pub const SAPLING_CONSENSUS_BRANCH_ID: u32 = 0x76b8_09bb;
26.3
60
0.802281
d7885ee359f940d8bd17226a2d071465c5912f46
1,769
use crate::import::structs::PrimitiveType; use std::{ borrow::Borrow, convert::AsRef, fmt, ops::Index, }; use ffi::aiFace; define_type_and_iterator! { /// Face type (not yet implemented) struct Face(&aiFace) /// Face iterator type. struct FaceIter } impl Face { /// The "kind" of this face - each mesh contains a bitset of all the primitive types that this mesh /// contains. For most applications you will want to call `Importer::triangulate(true)`, which will /// make Assimp automatically convert all faces to triangles. pub fn primitive_type(&self) -> PrimitiveType { match self.indices().len() { 0 => unreachable!(), 1 => PrimitiveType::Point, 2 => PrimitiveType::Line, 3 => PrimitiveType::Triangle, _ => PrimitiveType::Polygon, } } /// The list of indices into the parent mesh's vertex list used by this face. pub fn indices(&self) -> &[u32] { if self.mIndices.is_null() { &[] } else { unsafe { std::slice::from_raw_parts(self.mIndices, self.mNumIndices as usize) } } } } impl fmt::Debug for Face { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { #[derive(Debug)] struct Face<'a>(&'a [u32]); Face(self.indices()).fmt(f) } } impl AsRef<[u32]> for Face { fn as_ref(&self) -> &[u32] { self.indices() } } impl Borrow<[u32]> for Face { fn borrow(&self) -> &[u32] { self.indices() } } impl Index<usize> for Face { type Output = u32; fn index(&self, index: usize) -> &u32 { assert!(index < self.mNumIndices as usize); unsafe { &*self.mIndices.offset(index as isize) } } }
24.569444
103
0.574336
bf310183c976f85e4171df26d7b8228b6131ff5b
3,696
//! Contains [Chain] and implementations use crate::{error::Result, Block}; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; /// Representation of an Onft blockchain /// /// # Using /// /// You can, in high level terms, do the following directly to a blockchain: /// /// - Create an initial blockchain: [Chain::default] /// - Add some data inside a new block: [Chain::push_data] /// - Extend multiple new pieces of data inside new blocks: [Chain::extend_data] /// - Verify entire blockchain one-by-one: [Chain::verify] /// /// # Example /// /// ```rust /// use onft::prelude::*; /// /// // create /// let mut chain = Chain::default(); /// println!("Chain: {:?}", chain); /// /// // add block /// chain.push_data("Hello, world!").unwrap(); /// println!("Chain: {:?}", chain); /// /// // verify /// if let Ok(true) = chain.verify() { /// println!("Verified") /// } else { /// eprintln!("Not verified") /// } /// ``` #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Debug, Clone)] pub struct Chain(Vec<Block>); impl Chain { /// Verifies entire chain block-by-block from the first index. /// /// # Example /// /// ```rust /// use onft::prelude::*; /// /// // create /// let mut chain = Chain::default(); /// println!("Chain: {:?}", chain); /// /// // add block /// chain.push_data("Hello, world!").unwrap(); /// println!("Chain: {:?}", chain); /// /// // verify /// if let Ok(true) = chain.verify() { /// println!("Verified") /// } else { /// eprintln!("Not verified") /// } /// ``` /// /// # Performance /// /// This is a computationally heavy single-threaded task and ideally should /// just be done when needed block-by-block by verifying a [Block] manually /// using the [Block::verify] method if at all possible as the method simply /// links to this one. pub fn verify(&self) -> Result<bool> { let mut previous_hash = &self.0[0].hash; for block in self.0[1..].iter() { if !block.verify(previous_hash)? { return Ok(false); } previous_hash = &block.hash } Ok(true) } /// Adds a new single block to the chain via new data; chainable method. /// /// # Example /// /// ```rust /// use onft::prelude::*; /// /// let mut chain = Chain::default(); /// chain.push_data("Hello, world!").unwrap(); /// /// println!("Chain: {:?}", chain); /// ``` pub fn push_data(&mut self, data: impl Into<Vec<u8>>) -> Result<&mut Self> { let previous_block = self.0.last().unwrap(); let new_block = Block::new(&previous_block.hash, data)?; self.0.push(new_block); Ok(self) } /// Adds multiple blocks to the chain via an iterator of all the needed /// data; chainable method. /// /// # Example /// /// ```rust /// use onft::prelude::*; /// /// let data_vec = vec![ /// "Hello".as_bytes(), "world".as_bytes(), /// "multiple".as_bytes(), "data".as_bytes() /// ]; /// /// let mut chain = Chain::default(); /// chain.extend_data(data_vec).unwrap(); /// /// println!("Chain: {:?}", chain); /// ``` pub fn extend_data( &mut self, data_iter: impl IntoIterator<Item = impl Into<Vec<u8>>>, ) -> Result<&mut Self> { for data in data_iter.into_iter() { Self::push_data(self, data)?; } Ok(self) } // TODO: more vec-like interface } impl Default for Chain { fn default() -> Self { Self(vec![Block::default()]) } }
26.782609
80
0.535173
e62631414d5d9dfbfe5778969d21d1b37f56b322
102
pub const HSIZE_CHARS : u16 = 44; pub const VSIZE_CHARS : u16 = 37; pub mod display; pub mod render;
17
33
0.715686
e2da809f2d4579d546eeb16c4e9ac64033b6503c
4,922
use std::io::Read; use wai::*; use wast::WastDirective; macro_rules! wasm_test { ($func:ident, $path:expr) => { #[test] fn $func() -> anyhow::Result<()> { assert_wasm($path) } }; } wasm_test!(add, "./examples/wat/add.wat"); wasm_test!(fib, "./examples/wat/fib.wat"); wasm_test!(address, "./testsuite/address.wast"); wasm_test!(binary, "./testsuite/binary.wast"); wasm_test!(comments, "./testsuite/comments.wast"); wasm_test!(consts, "./testsuite/const.wast"); wasm_test!(custom, "./testsuite/custom.wast"); wasm_test!(data, "./testsuite/data.wast"); wasm_test!(_type, "./testsuite/type.wast"); // NOTE // これらはbr_tableに依存しているが、br_tableの実装がまだ終わっていないのでコメントアウトしている // wasm_test!(br, "./testsuite/br.wast"); // wasm_test!(call, "./testsuite/call.wast"); // wasm_test!(select, "./testsuite/select.wast"); // wasm_test!(_if, "./testsuite/if.wast"); // wasm_test!(block, "./testsuite/block.wast"); fn assert_wasm(filepath: &str) -> anyhow::Result<()> { let mut buf = vec![]; let mut file = std::fs::File::open(filepath)?; file.read_to_end(&mut buf)?; let wast = String::from_utf8(buf).unwrap(); let buf = wast::parser::ParseBuffer::new(&wast)?; let wast = wast::parser::parse::<wast::Wast>(&buf)?; let mut m = Module::default(); for directive in wast.directives { match directive { WastDirective::Module(mut module) => { let module_binary = module.encode()?; m = Module::from_byte(module_binary)?; } WastDirective::AssertReturn { exec, results, .. } => { let (name, args) = match exec { wast::WastExecute::Invoke(invoke) => (invoke.name, invoke.args), _ => unreachable!(), }; let args: Vec<RuntimeValue> = args.iter().map(args_to_runtime_value).collect(); let instance = Instance::new(m.clone()); println!("{}", name); let actual = match instance.invoke(&name, args.clone()) { Ok(v) => v, Err(e) => { // NOTE umimplementedエラーは読み飛ばす if e == RuntimeError::Unimplemented { continue; } panic!("\n====== failed assert {}==========\nerror: {}, ", name, e); } }; let expected: Vec<RuntimeValue> = results.iter().map(result_to_runtime_value).collect(); let actual = actual .iter() .map(to_zero_nan) .collect::<Vec<RuntimeValue>>(); let expected = expected .iter() .map(to_zero_nan) .collect::<Vec<RuntimeValue>>(); assert_eq!( expected, actual, "\n=====failed assert {}=====\nargs:{:#?}\nexpect {:#?}, return value {:#?}", name, args, expected, actual ); } _ => {} } } Ok(()) } fn to_zero_nan(v: &RuntimeValue) -> RuntimeValue { match v { RuntimeValue::F32(v) if v.is_nan() => RuntimeValue::F32(0.0), RuntimeValue::F64(v) if v.is_nan() => RuntimeValue::F64(0.0), v => *v, } } fn args_to_runtime_value(expr: &wast::Expression) -> RuntimeValue { match &expr.instrs[0] { wast::Instruction::I32Const(x) => RuntimeValue::I32(*x), wast::Instruction::I64Const(x) => RuntimeValue::I64(*x), wast::Instruction::F32Const(x) => RuntimeValue::F32(f32::from_bits(x.bits)), wast::Instruction::F64Const(x) => RuntimeValue::F64(f64::from_bits(x.bits)), _ => unreachable!("{:?}", expr), } } fn result_to_runtime_value(expr: &wast::AssertExpression) -> RuntimeValue { match expr { wast::AssertExpression::I32(x) => RuntimeValue::I32(*x), wast::AssertExpression::I64(x) => RuntimeValue::I64(*x), wast::AssertExpression::F32(x) => RuntimeValue::F32(to_f32(x)), wast::AssertExpression::F64(x) => RuntimeValue::F64(to_f64(x)), wast::AssertExpression::LegacyCanonicalNaN => RuntimeValue::F32(0.0), wast::AssertExpression::LegacyArithmeticNaN => RuntimeValue::F32(0.0), _ => unreachable!("{:?}", expr), } } fn to_f64(expr: &wast::NanPattern<wast::Float64>) -> f64 { match expr { &wast::NanPattern::CanonicalNan => 0.0, &wast::NanPattern::ArithmeticNan => 0.0, wast::NanPattern::Value(f) => f64::from_bits(f.bits), } } fn to_f32(expr: &wast::NanPattern<wast::Float32>) -> f32 { match expr { &wast::NanPattern::CanonicalNan => 0.0, &wast::NanPattern::ArithmeticNan => 0.0, wast::NanPattern::Value(f) => f32::from_bits(f.bits), } }
35.157143
97
0.536977
910aebd87e1ffe065f4f0d1e97366a8f561cca4f
2,587
use super::*; use sha2::{ Digest }; use rsa::{ PublicKey }; #[wasm_bindgen] #[derive(Debug, Clone)] pub struct RSAPublicKeyPair { n: String, e: String, public_instance: Option<RSAPublicKey> } #[wasm_bindgen] impl RSAPublicKeyPair { #[wasm_bindgen(constructor)] pub fn new() -> Self { RSAPublicKeyPair { n: "".to_string(), e: "".to_string(), public_instance: None } } pub fn create(&mut self, n: &str, e: &str) { utils::set_panic_hook(); let bn_e = BigUint::parse_bytes(e.as_bytes(), 16).expect("invalid e"); let bn_n = BigUint::parse_bytes(n.as_bytes(), 16).expect("invalid n"); let pub_keys = RSAPublicKey::new(bn_n, bn_e).expect("invalid create public instance"); self.n = pub_keys.n().to_str_radix(16); self.e = pub_keys.e().to_str_radix(16); self.public_instance = Some(pub_keys); } pub fn encrypt(&self, message: &str, random_seed: &str) -> String { utils::set_panic_hook(); let mut seed_array: [u8; 32] = [0; 32]; let decode_seed = hex::decode(random_seed).expect("invalid decode"); seed_array.copy_from_slice(&decode_seed.as_slice()); let mut rng: StdRng = SeedableRng::from_seed(seed_array); match &self.public_instance { Some(instance) => { let encrypt_message = match instance.encrypt( &mut rng, PaddingScheme::new_pkcs1v15_encrypt(), message.as_bytes() ) { Ok(res) => res, Err(e) => panic!("encrypt error {}", e) }; hex::encode(&encrypt_message) }, None => panic!("Instance not created") } } pub fn verify_message(&self, message: &str, signature: &str) -> bool { utils::set_panic_hook(); let decode_signature = hex::decode(signature).unwrap(); let hash_mess = Sha256::digest(message.as_bytes()); if let Some(instance) = &self.public_instance { return match instance.verify( PaddingScheme::new_pkcs1v15_sign(Some(Hash::SHA3_256)), &hash_mess, &decode_signature ) { Ok(_) => true, Err(_) => false } } panic!("Instance not created") } pub fn get_e(&self) -> String { self.e.to_string() } pub fn get_n(&self) -> String { self.n.to_string() } }
30.081395
94
0.535369
e928d91054b08b6544de799cc03fa0e15f818172
4,839
use super::*; use std::fmt; use colored::*; #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)] pub struct AttackRequestBuilder { path:String, parameters: Vec<RequestParameter>, auth: Authorization, method: Method, headers: Vec<MHeader>, } impl AttackRequestBuilder { pub fn uri(&mut self,base_url:&str,path:&str)->&mut Self{ self.path =format!("{}{}", base_url, path); self } pub fn auth(&mut self,auth:Authorization)->&mut Self{ self.auth = auth; self } pub fn method(&mut self,method:Method)->&mut Self{ self.method = method; self } pub fn headers(&mut self,headers:Vec<MHeader>)->&mut Self{ self.headers = headers; self } pub fn parameters(&mut self,parameters:Vec<RequestParameter>)->&mut Self{ self.parameters = parameters; self } pub fn build(&self)->AttackRequest{ AttackRequest { path:self.path.clone(), parameters:self.parameters.clone(), auth:self.auth.clone(), method:self.method.clone(), headers:self.headers.clone(), } } } impl std::fmt::Display for AttackRequest { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let (mut payload,query,path,headers) = self.params_to_payload(); if payload.trim().len() ==0{ payload = "NONE".to_string(); } write!(f, "{}: {}{}\t{}: {}\t{}: {}\t{}: {}","Path".green().bold(),path.magenta(),query.magenta(),"Method".green().bold(),self.method.to_string().magenta(),"Payload".green().bold(),payload.magenta(),"Headers".green().bold(),format!("{:?}",headers).magenta()) } } impl AttackRequest { pub fn builder()->AttackRequestBuilder{ AttackRequestBuilder::default() } pub fn params_to_payload(&self) -> (String, String, String, Vec<MHeader>) { let mut payload = String::from('{'); let mut query = String::from('?'); let mut path_ext = self.path.to_string(); let mut headers = vec![]; for param in self.parameters.iter() { match param.dm { QuePay::Payload => { payload.push_str(&format!("\"{}\":{},", param.name, param.value)) } QuePay::Query => query.push_str(&format!("{}={}&", param.name, param.value)), QuePay::Path => { path_ext = path_ext.replace(&format!("{}{}{}", '{', param.name, '}'), &param.value) } QuePay::Headers => { headers.push(MHeader { name: param.name.clone(), value: param.value.clone(), }); } _ => (), } } query.pop(); if payload.trim() == "{" { payload = String::new(); } else { payload.pop(); payload.push('}'); } (payload, query, path_ext, headers) } pub fn get_headers(&self,payload_headers: &[MHeader]) -> HashMap<String, String> { let mut new: Vec<MHeader> = self.headers .iter() .chain(payload_headers) .cloned() .collect(); if let Some(a) = self.auth.get_header() { new.push(a); } new.iter() .map(|h| (h.name.clone(), h.value.clone())) .collect() } pub async fn send_request(&self,print:bool) -> Result<AttackResponse,reqwest::Error> { let client = reqwest::Client::new(); let method1 = reqwest::Method::from_bytes(self.method.to_string().as_bytes()).unwrap(); let (req_payload, req_query, path, headers1) = self.params_to_payload(); let h = self.get_headers(&headers1); let req = client .request(method1, &format!("{}{}", path, req_query)) .body(req_payload.clone()) .headers((&h).try_into().expect("not valid headers")) .build() .unwrap(); match client.execute(req).await { Ok(res)=> { if print{ println!("{}: {}","Request".bright_blue().bold(),self); } Ok(AttackResponse { status: res.status().into(), headers: res .headers() .iter() .map(|(n, v)| (n.to_string(), format!("{:?}", v))) .collect(), payload: res.text().await.unwrap_or(String::new()), }) }, Err(e)=>{ println!("{}: {}","FAILED TO EXECUTE".red().bold().blink(),self); Err(e) } } } }
35.321168
266
0.492457
bf5769706501bc53e6735950780c40f733cf2d8f
5,367
use std::ffi::OsStr; use std::fs::{self, Permissions}; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; use std::process; use anyhow::{anyhow, Result}; use console::Style; use derive_getters::Getters; use serde::Serialize; use tempdir::TempDir; use crate::common::{EnvMap, DEPS_SCRIPT}; #[derive(Debug, Serialize)] pub(crate) struct JobSpec { pub name: String, pub provided_env: EnvMap, pub depends: Vec<String>, pub ask_for_vars: Vec<String>, pub has_deps_script: bool, } #[derive(Clone, Debug, Getters)] pub(crate) struct ReadyJob { name: String, env: EnvMap, depends: Vec<String>, has_deps_script: bool, } impl JobSpec { pub fn new( name: String, provided_env: EnvMap, depends: Vec<String>, ask_for_vars: Vec<String>, has_deps_script: bool, ) -> Self { Self { name, provided_env, depends, ask_for_vars, has_deps_script, } } #[inline] pub const fn get_ask_vars(&self) -> &Vec<String> { &self.ask_for_vars } } impl ReadyJob { pub fn new(name: String, env: EnvMap, depends: Vec<String>, has_deps_script: bool) -> Self { Self { name, env, depends, has_deps_script, } } #[inline] fn script_dir<P: AsRef<Path>>(&self, root: P) -> PathBuf { root.as_ref().join(&self.name) } fn create_proc_env<P: AsRef<Path>>(&self, root: P) -> Result<EnvMap> { let mut map = EnvMap::with_capacity(self.env.len()); for (k, v) in &self.env { map.insert(k.clone(), v.clone()); } map.insert( "HOME".into(), dirs::home_dir() .ok_or_else(|| anyhow!("Cannot find home dir"))? .display() .to_string(), ); map.insert("USER".into(), whoami::username()); map.insert("USERNAME".into(), whoami::username()); map.insert( "SCRIPT_DIR".into(), self.script_dir(root).display().to_string(), ); Ok(map) } pub fn report(&self, job_num: usize) -> String { let mut report = String::new(); report.push_str("Would run job "); report.push_str(&format!("{:03}", job_num)); report.push_str(": "); report.push_str(&job_style().apply_to(&self.name).to_string()); // report.push('\n'); for d in &self.depends { report.push('\n'); report.push_str(&info_style().apply_to(" Depends on: ").to_string()); report.push_str(&info_style().apply_to(d).to_string()); } if self.has_deps_script { report.push('\n'); report.push_str(&info_style().apply_to(" Deps.sh: yes").to_string()); }; for (k, v) in &self.env { report.push('\n'); report.push_str(&info_style().apply_to(" Env: ").to_string()); report.push_str(&info_style().apply_to(k).to_string()); report.push_str(&info_style().apply_to(" -> ").to_string()); report.push_str(&info_style().apply_to(v).to_string()); } report } fn run_process<P: AsRef<OsStr>>(&self, env: &EnvMap, runnable: P) -> Result<()> { debug!( "Executing runnable: {}", runnable.as_ref().to_string_lossy() ); ensure_executable(&runnable.as_ref())?; let tmp_dir = TempDir::new(&self.name)?; let status = process::Command::new(runnable) .envs(env) .env("TMP_DIR", tmp_dir.path()) .env("TEMP_DIR", tmp_dir.path()) .status()?; debug!("Dropping temp dir: {}", tmp_dir.path().display()); drop(tmp_dir); // Statically enforce that we didn't drop until here. if status.success() { Ok(()) } else { Err(anyhow!(format!( "Job '{}' failed with exit code {}", self.name, status.code().unwrap_or(-1) ))) } } fn find_runner<P: AsRef<Path>>(&self, root: P) -> Result<PathBuf> { let job_dir = root.as_ref().join(&self.name); let default = job_dir.join("run.sh"); if default.is_file() { return Ok(default); } let pattern = format!("{}/run.*", job_dir.display()); Ok(glob::glob(&pattern)? .next() .ok_or_else(|| anyhow!("No runner found"))??) } pub fn run<P: AsRef<Path>>(&self, root: P) -> Result<()> { let env = self.create_proc_env(&root)?; if self.has_deps_script { let deps_runnable = root.as_ref().join(&self.name).join(DEPS_SCRIPT); self.run_process(&env, deps_runnable)?; }; let runner = self.find_runner(root)?; self.run_process(&env, runner) } } fn ensure_executable<P: AsRef<Path>>(file: P) -> Result<()> { if is_executable::is_executable(&file) { return Ok(()); }; let mode: u32 = fs::metadata(&file)?.permissions().mode() | 100; fs::set_permissions(&file, Permissions::from_mode(mode))?; Ok(()) } #[inline] fn info_style() -> Style { Style::new().dim() } #[inline] fn job_style() -> Style { Style::new().blue().bold() }
29.327869
96
0.535122
ff89b70d578f2a4231c8c4672bdc5fa4064a0d00
6,564
//! RenderPass handling. use crate::format::Format; use crate::image; use crate::pso::PipelineStage; use std::ops::Range; use crate::Backend; /// Specifies the operation which will be applied at the beginning of a subpass. #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum AttachmentLoadOp { /// Preserve existing content in the attachment. Load, /// Clear the attachment. Clear, /// Attachment content will be undefined. DontCare, } /// #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum AttachmentStoreOp { /// Content written to the attachment will be preserved. Store, /// Attachment content will be undefined. DontCare, } /// Image layout of an attachment. pub type AttachmentLayout = image::Layout; /// Attachment operations. #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct AttachmentOps { /// Indicates how the data of the attachment will be loaded at first usage at /// the beginning of the subpass. pub load: AttachmentLoadOp, /// Whether or not data from the store operation will be preserved after the subpass. pub store: AttachmentStoreOp, } impl AttachmentOps { /// Specifies `DontCare` for both load and store op. pub const DONT_CARE: Self = AttachmentOps { load: AttachmentLoadOp::DontCare, store: AttachmentStoreOp::DontCare, }; /// Specifies `Load` for load op and `Store` for store op. pub const PRESERVE: Self = AttachmentOps { load: AttachmentLoadOp::Load, store: AttachmentStoreOp::Store, }; /// Convenience function to create a new `AttachmentOps`. pub fn new(load: AttachmentLoadOp, store: AttachmentStoreOp) -> Self { AttachmentOps { load, store } } /// A method to provide `AttachmentOps::DONT_CARE` to things that expect /// a default function rather than a value. #[cfg(feature = "serde")] fn whatever() -> Self { Self::DONT_CARE } } /// An `Attachment` is a description of a resource provided to a render subpass. /// It includes things such as render targets, images that were produced from /// previous subpasses, etc. #[derive(Clone, Debug, Hash, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Attachment { /// Attachment format /// /// In the most cases `format` is not `None`. It should be only used for /// creating dummy renderpasses, which are used as placeholder for compatible /// renderpasses. pub format: Option<Format>, /// Number of samples. pub samples: image::NumSamples, /// Load and store operations of the attachment pub ops: AttachmentOps, /// Load and store operations of the stencil aspect, if any #[cfg_attr(feature = "serde", serde(default = "AttachmentOps::whatever"))] pub stencil_ops: AttachmentOps, /// Initial and final image layouts of the renderpass. pub layouts: Range<AttachmentLayout>, } impl Attachment { /// Returns true if this attachment has some clear operations. This is useful /// when starting a render pass, since there has to be a clear value provided. pub fn has_clears(&self) -> bool { self.ops.load == AttachmentLoadOp::Clear || self.stencil_ops.load == AttachmentLoadOp::Clear } } /// Index of an attachment within a framebuffer/renderpass, pub type AttachmentId = usize; /// Reference to an attachment by index and expected image layout. pub type AttachmentRef = (AttachmentId, AttachmentLayout); /// Which other subpasses a particular subpass depends on. #[derive(Copy, Clone, Debug, Hash, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum SubpassRef { /// The subpass depends on something that was submitted to the /// queue before or after the render pass began. External, /// The subpass depends on another subpass with the given index, /// which must be less than or equal to the index of the current /// subpass. The index here refers to the corresponding /// `SubpassId` of a `Subpass`. Pass(usize), } /// Expresses a dependency between multiple subpasses. This is used /// both to describe a source or destination subpass; data either /// explicitly passes from this subpass to the next or from another /// subpass into this one. #[derive(Clone, Debug, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct SubpassDependency { /// Other subpasses this one depends on. pub passes: Range<SubpassRef>, /// Other pipeline stages this subpass depends on. pub stages: Range<PipelineStage>, /// Resource accesses this subpass depends on. pub accesses: Range<image::Access>, } /// Description of a subpass for renderpass creation. pub struct SubpassDesc<'a> { /// Which attachments will be used as color buffers. pub colors: &'a [AttachmentRef], /// Which attachments will be used as depth/stencil buffers. pub depth_stencil: Option<&'a AttachmentRef>, /// Which attachments will be used as input attachments. pub inputs: &'a [AttachmentRef], /// Which attachments will be used as resolve destinations. /// /// The number of resolve attachments may be zero or equal to the number of color attachments. /// At the end of a subpass the color attachment will be resolved to the corresponding /// resolve attachment. The resolve attachment must not be multisampled. pub resolves: &'a [AttachmentRef], /// Attachments that are not used by the subpass but must be preserved to be /// passed on to subsequent passes. pub preserves: &'a [AttachmentId], } /// Index of a subpass. pub type SubpassId = usize; /// A sub-pass borrow of a pass. #[derive(Debug)] pub struct Subpass<'a, B: Backend> { /// Index of the subpass pub index: SubpassId, /// Main pass borrow. pub main_pass: &'a B::RenderPass, } impl<'a, B: Backend> Clone for Subpass<'a, B> { fn clone(&self) -> Self { Subpass { index: self.index, main_pass: self.main_pass, } } } impl<'a, B: Backend> PartialEq for Subpass<'a, B> { fn eq(&self, other: &Self) -> bool { self.index == other.index && self.main_pass as *const _ == other.main_pass as *const _ } } impl<'a, B: Backend> Copy for Subpass<'a, B> {} impl<'a, B: Backend> Eq for Subpass<'a, B> {}
35.673913
100
0.686015
7246d0c59ba1ad20e192125bc638093b38e315d4
8,028
use crate::ast::{Enum, Field, Input, Struct, Variant}; use crate::attr::Attrs; use quote::ToTokens; use std::collections::BTreeSet as Set; use syn::{Error, GenericArgument, Member, PathArguments, Result, Type}; impl Input<'_> { pub(crate) fn validate(&self) -> Result<()> { match self { Input::Struct(input) => input.validate(), Input::Enum(input) => input.validate(), } } } impl Struct<'_> { fn validate(&self) -> Result<()> { check_non_field_attrs(&self.attrs)?; if let Some(transparent) = self.attrs.transparent { if self.fields.len() != 1 { return Err(Error::new_spanned( transparent.original, "#[error(transparent)] requires exactly one field", )); } if let Some(source) = self.fields.iter().find_map(|f| f.attrs.source) { return Err(Error::new_spanned( source, "transparent error struct can't contain #[source]", )); } } check_field_attrs(&self.fields)?; for field in &self.fields { field.validate()?; } Ok(()) } } impl Enum<'_> { fn validate(&self) -> Result<()> { check_non_field_attrs(&self.attrs)?; let has_display = self.has_display(); for variant in &self.variants { variant.validate()?; if has_display && variant.attrs.display.is_none() && variant.attrs.transparent.is_none() { return Err(Error::new_spanned( variant.original, "missing #[error(\"...\")] display attribute", )); } } let mut from_types = Set::new(); for variant in &self.variants { if let Some(from_field) = variant.from_field() { let repr = from_field.ty.to_token_stream().to_string(); if !from_types.insert(repr) { return Err(Error::new_spanned( from_field.original, "cannot derive From because another variant has the same source type", )); } } } Ok(()) } } impl Variant<'_> { fn validate(&self) -> Result<()> { check_non_field_attrs(&self.attrs)?; if self.attrs.transparent.is_some() { if self.fields.len() != 1 { return Err(Error::new_spanned( self.original, "#[error(transparent)] requires exactly one field", )); } if let Some(source) = self.fields.iter().find_map(|f| f.attrs.source) { return Err(Error::new_spanned( source, "transparent variant can't contain #[source]", )); } } check_field_attrs(&self.fields)?; for field in &self.fields { field.validate()?; } Ok(()) } } impl Field<'_> { fn validate(&self) -> Result<()> { if let Some(display) = &self.attrs.display { return Err(Error::new_spanned( display.original, "not expected here; the #[error(...)] attribute belongs on top of a struct or an enum variant", )); } Ok(()) } } fn check_non_field_attrs(attrs: &Attrs) -> Result<()> { if let Some(from) = &attrs.from { return Err(Error::new_spanned( from, "not expected here; the #[from] attribute belongs on a specific field", )); } if let Some(source) = &attrs.source { return Err(Error::new_spanned( source, "not expected here; the #[source] attribute belongs on a specific field", )); } if let Some(backtrace) = &attrs.backtrace { return Err(Error::new_spanned( backtrace, "not expected here; the #[backtrace] attribute belongs on a specific field", )); } if let Some(display) = &attrs.display { if attrs.transparent.is_some() { return Err(Error::new_spanned( display.original, "cannot have both #[error(transparent)] and a display attribute", )); } } Ok(()) } fn check_field_attrs(fields: &[Field]) -> Result<()> { let mut from_field = None; let mut source_field = None; let mut backtrace_field = None; let mut has_backtrace = false; for field in fields { if let Some(from) = field.attrs.from { if from_field.is_some() { return Err(Error::new_spanned(from, "duplicate #[from] attribute")); } from_field = Some(field); } if let Some(source) = field.attrs.source { if source_field.is_some() { return Err(Error::new_spanned(source, "duplicate #[source] attribute")); } source_field = Some(field); } if let Some(backtrace) = field.attrs.backtrace { if backtrace_field.is_some() { return Err(Error::new_spanned( backtrace, "duplicate #[backtrace] attribute", )); } backtrace_field = Some(field); has_backtrace = true; } if let Some(transparent) = field.attrs.transparent { return Err(Error::new_spanned( transparent.original, "#[error(transparent)] needs to go outside the enum or struct, not on an individual field", )); } has_backtrace |= field.is_backtrace(); } if let (Some(from_field), Some(source_field)) = (from_field, source_field) { if !same_member(from_field, source_field) { return Err(Error::new_spanned( from_field.attrs.from, "#[from] is only supported on the source field, not any other field", )); } } if let Some(from_field) = from_field { if fields.len() > 1 + has_backtrace as usize { return Err(Error::new_spanned( from_field.attrs.from, "deriving From requires no fields other than source and backtrace", )); } } if let Some(source_field) = source_field.or(from_field) { if contains_non_static_lifetime(&source_field.ty) { return Err(Error::new_spanned( &source_field.original.ty, "non-static lifetimes are not allowed in the source of an error, because std::error::Error requires the source is dyn Error + 'static", )); } } Ok(()) } fn same_member(one: &Field, two: &Field) -> bool { match (&one.member, &two.member) { (Member::Named(one), Member::Named(two)) => one == two, (Member::Unnamed(one), Member::Unnamed(two)) => one.index == two.index, _ => unreachable!(), } } fn contains_non_static_lifetime(ty: &Type) -> bool { match ty { Type::Path(ty) => { let bracketed = match &ty.path.segments.last().unwrap().arguments { PathArguments::AngleBracketed(bracketed) => bracketed, _ => return false, }; for arg in &bracketed.args { match arg { GenericArgument::Type(ty) if contains_non_static_lifetime(ty) => return true, GenericArgument::Lifetime(lifetime) if lifetime.ident != "static" => { return true } _ => {} } } false } Type::Reference(ty) => ty .lifetime .as_ref() .map_or(false, |lifetime| lifetime.ident != "static"), _ => false, // maybe implement later if there are common other cases } }
34.307692
151
0.514574
abce38a7a98cb4262195780d1e022027c2ed5cc6
4,042
use nu_test_support::fs::AbsolutePath; use nu_test_support::fs::Stub::FileWithContent; use nu_test_support::playground::{says, Playground}; use hamcrest2::assert_that; use hamcrest2::prelude::*; #[test] fn clearing_config_clears_config() { Playground::setup("environment_syncing_test_1", |dirs, nu| { let file = AbsolutePath::new(dirs.test().join("config.toml")); nu.with_config(&file); nu.with_files(vec![FileWithContent( "config.toml", r#" skip_welcome_message = true "#, )]); assert_that!( nu.pipeline("config clear | ignore; config get skip_welcome_message"), says().stdout("") ); let config_contents = std::fs::read_to_string(file).expect("Could not read file"); assert!(config_contents.is_empty()); }); } #[test] fn config_get_returns_value() { Playground::setup("environment_syncing_test_1", |dirs, nu| { let file = AbsolutePath::new(dirs.test().join("config.toml")); nu.with_config(&file); nu.with_files(vec![FileWithContent( "config.toml", r#" skip_welcome_message = true "#, )]); assert_that!( //Clears config nu.pipeline("config get skip_welcome_message"), says().stdout("true") ); }); } #[test] fn config_set_sets_value() { Playground::setup("environment_syncing_test_1", |dirs, nu| { let file = AbsolutePath::new(dirs.test().join("config.toml")); nu.with_config(&file); nu.with_files(vec![FileWithContent( "config.toml", r#" skip_welcome_message = true "#, )]); assert_that!( //Clears config nu.pipeline("config set key value | ignore; config get key"), says().stdout("value") ); let config_contents = std::fs::read_to_string(file).expect("Could not read file"); assert!(config_contents.contains("key = \"value\"")); }); } #[test] fn config_set_into_sets_value() { Playground::setup("environment_syncing_test_1", |dirs, nu| { let file = AbsolutePath::new(dirs.test().join("config.toml")); nu.with_config(&file); nu.with_files(vec![FileWithContent( "config.toml", r#" skip_welcome_message = true "#, )]); assert_that!( //Clears config nu.pipeline("echo value | config set_into key | ignore; config get key"), says().stdout("value") ); let config_contents = std::fs::read_to_string(file).expect("Could not read file"); assert!(config_contents.contains("key = \"value\"")); }); } #[test] fn config_rm_removes_value() { Playground::setup("environment_syncing_test_1", |dirs, nu| { let file = AbsolutePath::new(dirs.test().join("config.toml")); nu.with_config(&file); nu.with_files(vec![FileWithContent( "config.toml", r#" key = "value" skip_welcome_message = true "#, )]); assert_that!( nu.pipeline("config remove key | ignore; config get key"), says().stdout("") ); let config_contents = std::fs::read_to_string(file).expect("Could not read file"); assert!(!config_contents.contains("key = \"value\"")); }); } #[test] fn config_path_returns_correct_path() { Playground::setup("environment_syncing_test_1", |dirs, nu| { let file = AbsolutePath::new(dirs.test().join("config.toml")); nu.with_config(&file); nu.with_files(vec![FileWithContent( "config.toml", r#" skip_welcome_message = true "#, )]); assert_that!( nu.pipeline("config path"), says().stdout(&file.inner.to_string_lossy().to_string()) ); }); }
29.079137
90
0.556655
0af114ef48d8715a82c179d872ccc3158e5fee14
2,048
use crate::model::{id::Id, user::User}; use chrono::{DateTime, Utc}; use mime::Mime; use serde::{Deserialize, Serialize}; use url::Url; #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct DriveFileProperties { #[cfg(feature = "12-75-0")] #[cfg_attr(docsrs, doc(cfg(feature = "12-75-0")))] pub width: Option<u64>, #[cfg(feature = "12-75-0")] #[cfg_attr(docsrs, doc(cfg(feature = "12-75-0")))] pub height: Option<u64>, #[cfg(feature = "12-75-0")] #[cfg_attr(docsrs, doc(cfg(feature = "12-75-0")))] pub avg_color: Option<String>, #[cfg(not(feature = "12-75-0"))] #[cfg_attr(docsrs, doc(cfg(not(feature = "12-75-0"))))] #[serde(flatten)] pub properties: serde_json::Map<String, serde_json::Value>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct DriveFile { pub id: Id<DriveFile>, pub created_at: DateTime<Utc>, pub name: String, #[serde(rename = "type", with = "crate::serde::string")] pub type_: Mime, pub md5: String, pub size: u64, pub url: Option<Url>, pub folder_id: Option<Id<DriveFolder>>, #[cfg(feature = "12-48-0")] #[cfg_attr(docsrs, doc(cfg(feature = "12-48-0")))] pub comment: Option<String>, #[cfg(feature = "12-48-0")] #[cfg_attr(docsrs, doc(cfg(feature = "12-48-0")))] pub user_id: Option<Id<User>>, pub user: Option<User>, #[serde(default)] pub folder: Option<DriveFolder>, pub is_sensitive: bool, pub properties: DriveFileProperties, } impl_entity!(DriveFile); #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct DriveFolder { pub id: Id<DriveFolder>, pub created_at: DateTime<Utc>, pub name: String, #[serde(default)] pub folders_count: Option<u64>, #[serde(default)] pub files_count: Option<u64>, pub parent_id: Option<Id<DriveFolder>>, #[serde(default)] pub parent: Option<Box<DriveFolder>>, } impl_entity!(DriveFolder);
29.681159
63
0.636719
3ad01194efc141fae0c3341c4b9d60e604ffb2fb
3,691
use utils::{files, parse_field_unwrap}; fn main() { let filename = "src/input.txt"; let lines = files::read_in_lines(filename); let parsed: Vec<(Vec<String>, Vec<String>)> = lines.iter() .map( |s| { let (l, r) = parse_field_unwrap!(&s => String, " | " | String, ""); let v1 = l.split_whitespace().map(|s| String::from(s)).collect(); let v2 = r.split_whitespace().map(|s| String::from(s)).collect(); (v1, v2) }).collect(); println!("----- PART 1 -----"); let count_unique = |count, (_, r) : &(_, Vec<String>)| { count + r.iter() .filter(|s| s.len() == 2 || s.len() == 3 || s.len() == 4 || s.len() == 7) .count() }; let count = parsed.iter().fold(0, count_unique); println!("Part 1 Answer: {}", count); println!("\n\n----- PART 2 -----"); let sum = parsed.iter().fold(0, |count, input| count + decode_segments(input)); println!("Part 2 Answer: {}", sum); } fn decode_segments((l, r): &(Vec<String>, Vec<String>)) -> u32 { let one = l.iter().filter(|s| s.len() == 2).next().unwrap(); let four = l.iter().filter(|s| s.len() == 4).next().unwrap(); let seven = l.iter().filter(|s| s.len() == 3).next().unwrap(); let eight = l.iter().filter(|s| s.len() == 7).next().unwrap(); // ---- 0, 9 and 6 all light up 6 segments ---- // 9 contains all segments also lit up by 4 // 0 in remaining candidates contains all segments lit up by 1 // 6 is the one remaining let nine = l.iter().filter(|s| s.len() == 6) .filter(|s| contains_chars(s, four)) .next().unwrap(); let zero = l.iter().filter(|s| s.len() == 6) .filter(|s| s != &nine && contains_chars(s, one)) .next().unwrap(); let six = l.iter().filter(|s| s.len() == 6) .filter(|s| s != &nine && s != &zero) .next().unwrap(); // ---- 2, 3 and 5 all light up 5 segments ---- // 3 contains all segments lit up by 1 // 5 is contained by segments lit up by 6 // 2 is remaining let three = l.iter().filter(|s| s.len() == 5) .filter(|s| contains_chars(s, one)) .next().unwrap(); let five = l.iter().filter(|s| s.len() == 5) .filter(|s| contains_chars(six, s)) .next().unwrap(); let two = l.iter().filter(|s| s.len() == 5) .filter(|s| s != &three && s != &five) .next().unwrap(); // println!("0:{} 1:{} 2:{} 3:{} 4:{} 5:{} 6:{} 7:{} 8:{} 9:{}", // zero, one, two, three, four, five, six, seven, eight, nine); // Now calculate sum of output values let mut number = String::new(); for (i, s) in r.iter().enumerate() { number.push_str(if contains_chars(s, zero) && contains_chars(zero, s) { "0" } else if contains_chars(s, one) && contains_chars(one, s) { "1" } else if contains_chars(s, two) && contains_chars(two, s) { "2" } else if contains_chars(s, three) && contains_chars(three, s) { "3" } else if contains_chars(s, four) && contains_chars(four, s) { "4" } else if contains_chars(s, five) && contains_chars(five, s) { "5" } else if contains_chars(s, six) && contains_chars(six, s) { "6" } else if contains_chars(s, seven) && contains_chars(seven, s) { "7" } else if contains_chars(s, eight) && contains_chars(eight, s) { "8" } else if contains_chars(s, nine) && contains_chars(nine, s) { "9" } else { "" }); } // println!("OUTPUT {:?} -> {}", r, number); return number.parse::<u32>().unwrap(); } fn contains_chars(s: &str, chars: &str) -> bool { chars.chars().fold(true, |result, c| result & s.contains(c)) }
42.425287
85
0.530209
d952b8632fb1572f9ddb0fe91f6c3d4006f04de4
1,028
// Copyright 2020 The Vega Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use vega_derive::ExecutionFail; /// Common errors emitted by transactions during execution. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] #[derive(ExecutionFail)] pub enum Error { /// Wallet not found. WalletNotFound = 0, /// Wallet already exists. WalletAlreadyExists = 1, /// Wrong interface caller. WrongInterfaceCaller = 2, /// Issuer is not authorized. UnauthorizedIssuer = 3, }
34.266667
75
0.722763
9b9734bc78e6554cc48544c4ced6f1c10ee603ec
13,766
use std::{ borrow::Cow, fmt::{self, Formatter, Display}, str::FromStr, }; use indexmap::IndexMap; use regex::Regex; use once_cell::sync::Lazy; use serde::{ de::{Error as _, Deserialize, Deserializer}, ser::{Serialize, Serializer}, }; use codespan::Span; use crate::{ ast::{ArgumentValue, Literal}, hir, }; #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(tag = "version")] pub enum Document { #[serde(rename = "1")] V1 { image: Path, pipeline: IndexMap<String, Stage>, }, } impl Document { pub fn parse(yaml: &str) -> Result<Self, serde_yaml::Error> { serde_yaml::from_str(yaml) } pub fn write_as_yaml<W>(&self, writer: W) -> Result<(), serde_yaml::Error> where W: std::io::Write, { serde_yaml::to_writer(writer, self)?; Ok(()) } } impl FromStr for Document { type Err = serde_yaml::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { Document::parse(s) } } /// A specification for finding a dependency. /// /// The full syntax is `base@version#sub_path` where /// /// - `base` is a URL or the name of a repository on GitHub (e.g. `hotg-ai/rune` /// or `https://github.com/hotg-ai/rune`) /// - `version` is an optional field specifying the version (e.g. as a git tag) /// - `sub_path` is an optional field which is useful when pointing to /// repositories with multiple relevant items because it lets you specify /// which directory the specified item is in. #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct Path { pub base: String, pub sub_path: Option<String>, pub version: Option<String>, } impl Path { pub fn new( base: impl Into<String>, sub_path: impl Into<Option<String>>, version: impl Into<Option<String>>, ) -> Self { Path { base: base.into(), sub_path: sub_path.into(), version: version.into(), } } } impl From<Path> for crate::ast::Path { fn from(p: Path) -> crate::ast::Path { let Path { base, sub_path, version, } = p; crate::ast::Path::new(base, sub_path, version, Span::new(0, 0)) } } impl From<crate::ast::Path> for Path { fn from(p: crate::ast::Path) -> Path { let crate::ast::Path { base, sub_path, version, .. } = p; Path::new(base, sub_path, version) } } impl Display for Path { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { let Path { base, sub_path, version, } = self; write!(f, "{}", base)?; if let Some(sub) = sub_path { write!(f, "#{}", sub)?; } if let Some(version) = version { write!(f, "@{}", version)?; } Ok(()) } } impl FromStr for Path { type Err = PathParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { static PATTERN: Lazy<Regex> = Lazy::new(|| { Regex::new( r"(?x) (?P<base>[\w\d:/_.-]+) (?:@(?P<version>[\w\d./-]+))? (?:\#(?P<sub_path>[\w\d._/-]+))? ", ) .unwrap() }); let captures = PATTERN.captures(s).ok_or(PathParseError)?; let base = captures["base"].to_string(); let version = captures.name("version").map(|m| m.as_str().to_string()); let sub_path = captures.name("sub_path").map(|m| m.as_str().to_string()); Ok(Path { base, version, sub_path, }) } } impl Serialize for Path { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.to_string().serialize(serializer) } } impl<'de> Deserialize<'de> for Path { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let s = Cow::<'de, str>::deserialize(deserializer)?; s.parse().map_err(D::Error::custom) } } #[derive(Debug, Copy, Clone, PartialEq, Default)] pub struct PathParseError; impl Display for PathParseError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "Unable to parse the path") } } impl std::error::Error for PathParseError {} #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(untagged, rename_all = "kebab-case")] pub enum Stage { Model { model: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] inputs: Vec<Input>, #[serde(default, skip_serializing_if = "Vec::is_empty")] outputs: Vec<Type>, }, ProcBlock { #[serde(rename = "proc-block")] proc_block: Path, #[serde(default, skip_serializing_if = "Vec::is_empty")] inputs: Vec<Input>, #[serde(default, skip_serializing_if = "Vec::is_empty")] outputs: Vec<Type>, #[serde(default, skip_serializing_if = "IndexMap::is_empty")] args: IndexMap<String, Value>, }, Capability { capability: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] outputs: Vec<Type>, #[serde(default, skip_serializing_if = "IndexMap::is_empty")] args: IndexMap<String, Value>, }, Out { out: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] inputs: Vec<Input>, #[serde(default, skip_serializing_if = "IndexMap::is_empty")] args: IndexMap<String, Value>, }, } impl Stage { pub fn inputs(&self) -> &[Input] { match self { Stage::Model { inputs, .. } | Stage::ProcBlock { inputs, .. } | Stage::Out { inputs, .. } => inputs, Stage::Capability { .. } => &[], } } pub fn inputs_mut(&mut self) -> Option<&mut Vec<Input>> { match self { Stage::Model { inputs, .. } | Stage::ProcBlock { inputs, .. } | Stage::Out { inputs, .. } => Some(inputs), Stage::Capability { .. } => None, } } pub fn output_type(&self) -> Option<&Type> { match self.output_types() { [] => None, [output] => Some(output), _ => unimplemented!("Multiple outputs aren't supported yet"), } } pub fn output_types(&self) -> &[Type] { match self { Stage::Model { outputs, .. } | Stage::ProcBlock { outputs, .. } | Stage::Capability { outputs, .. } => outputs, Stage::Out { .. } => &[], } } pub fn span(&self) -> Span { // TODO: Get span from serde_yaml Span::new(0, 0) } } impl From<Stage> for hir::Stage { fn from(s: Stage) -> hir::Stage { match s { Stage::Model { model, .. } => hir::Stage::Model(hir::Model { model_file: model.into(), }), Stage::ProcBlock { proc_block, args, .. } => hir::Stage::ProcBlock(hir::ProcBlock { path: proc_block.into(), parameters: args .into_iter() .map(|(k, v)| (k.replace("-", "_"), v)) .collect(), }), Stage::Capability { capability, args, .. } => hir::Stage::Source(hir::Source { kind: capability.as_str().into(), parameters: args .into_iter() .map(|(k, v)| (k.replace("-", "_"), v)) .collect(), }), Stage::Out { out, .. } => hir::Stage::Sink(hir::Sink { kind: out.as_str().into(), }), } } } #[derive( Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, )] pub struct Type { #[serde(rename = "type")] pub name: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub dimensions: Vec<usize>, } #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[serde(rename = "kebab-case", untagged)] pub enum Value { Int(i32), Float(f32), String(String), List(Vec<Value>), } impl From<f32> for Value { fn from(f: f32) -> Value { Value::Float(f) } } impl From<i32> for Value { fn from(i: i32) -> Value { Value::Int(i) } } impl From<String> for Value { fn from(s: String) -> Value { Value::String(s) } } impl<'a> From<&'a str> for Value { fn from(s: &'a str) -> Value { Value::String(s.to_string()) } } impl From<Vec<Value>> for Value { fn from(list: Vec<Value>) -> Value { Value::List(list) } } impl From<Value> for ArgumentValue { fn from(v: Value) -> ArgumentValue { match v { Value::Int(i) => { ArgumentValue::Literal(Literal::new(i as i64, Span::new(0, 0))) }, Value::Float(f) => { ArgumentValue::Literal(Literal::new(f, Span::new(0, 0))) }, Value::String(s) => { ArgumentValue::Literal(Literal::new(s, Span::new(0, 0))) }, Value::List(list) => { let mut items = Vec::new(); for item in list { if let Value::String(s) = item { items.push(s.clone()); } else { unimplemented!(); } } ArgumentValue::List(items) }, } } } #[derive(Debug, Clone, PartialEq, Hash, Eq, Ord, PartialOrd)] pub struct Input { pub name: String, pub index: Option<usize>, } impl Input { pub fn new( name: impl Into<String>, index: impl Into<Option<usize>>, ) -> Self { Input { name: name.into(), index: index.into(), } } } impl FromStr for Input { type Err = Box<dyn std::error::Error>; fn from_str(s: &str) -> Result<Self, Self::Err> { static PATTERN: Lazy<Regex> = Lazy::new(|| { Regex::new(r"^(?P<name>[a-zA-Z_][\w-]*)(?:\.(?P<index>\d+))?$") .unwrap() }); let captures = PATTERN .captures(s) .ok_or("Expected something like \"fft\" or \"fft.2\"")?; let name = &captures["name"]; let index = captures.name("index").map(|m| { m.as_str() .parse::<usize>() .expect("Guaranteed by the regex") }); Ok(Input::new(name, index)) } } impl Display for Input { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self.index { Some(index) => write!(f, "{}.{}", self.name, index), None => write!(f, "{}", self.name), } } } impl Serialize for Input { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.collect_str(self) } } impl<'de> Deserialize<'de> for Input { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let raw = Cow::<str>::deserialize(deserializer)?; Input::from_str(&raw).map_err(|e| D::Error::custom(e.to_string())) } } #[cfg(test)] mod tests { use super::*; #[test] fn parse_normal_input_specifier() { let src = "audio"; let should_be = Input::new("audio", None); let got = Input::from_str(src).unwrap(); assert_eq!(got, should_be); assert_eq!(got.to_string(), src); } #[test] fn input_specifier_with_tuple() { let src = "audio.2"; let should_be = Input::new("audio", 2); let got = Input::from_str(src).unwrap(); assert_eq!(got, should_be); assert_eq!(got.to_string(), src); } #[test] fn parse_paths() { let inputs = vec![ ("asdf", Path::new("asdf", None, None)), ("runicos/base", Path::new("runicos/base", None, None)), ( "runicos/[email protected]", Path::new("runicos/base", None, Some(String::from("0.1.2"))), ), ( "runicos/base@latest", Path::new("runicos/base", None, Some(String::from("latest"))), ), ( "hotg-ai/rune#proc_blocks/normalize", Path::new( "hotg-ai/rune", Some(String::from("proc_blocks/normalize")), None, ), ), ( "https://github.com/hotg-ai/rune", Path::new("https://github.com/hotg-ai/rune", None, None), ), ( "https://github.com/hotg-ai/rune@2", Path::new( "https://github.com/hotg-ai/rune", None, Some(String::from("2")), ), ), ]; for (src, should_be) in inputs { let got: Path = src.parse().unwrap(); assert_eq!(got, should_be, "{}", src); } } #[test] fn parse_v1() { let src = "version: 1\nimage: asdf\npipeline: {}"; let got = Document::parse(src).unwrap(); assert!(matches!(got, Document::V1 { .. })); } #[test] #[should_panic = "unknown variant `2`"] fn other_versions_are_an_error() { let src = "image: asdf\nversion: 2\npipeline:"; let got = Document::parse(src).unwrap(); assert!(matches!(got, Document::V1 { .. })); } }
26.626692
80
0.499056
d9d0df2f408656cb72eb2cf9da021e51dda34997
693
// Copyright (C) 2018-2019 Boyu Yang // // 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 super::full_complete; #[test] fn count_nodes_by_leaves() { let test_data = vec![ (1, 1), (2, 3), (3, 5), (4, 7), (5, 9), (6, 11), (7, 13), (8, 15), ]; for (input, expected) in test_data { assert_eq!(expected, full_complete::count_nodes_by_leaves(input)); } }
25.666667
74
0.597403
03ce6d865c4095f03c0fe65b34526e9eb28816bc
92,319
#![doc = "generated by AutoRust"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[doc = "Profile for enabling a user to access a managed cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct AccessProfile { #[doc = "Base64-encoded Kubernetes configuration file."] #[serde(rename = "kubeConfig", default, skip_serializing_if = "Option::is_none")] pub kube_config: Option<String>, } impl AccessProfile { pub fn new() -> Self { Self::default() } } #[doc = "Agent Pool."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct AgentPool { #[serde(flatten)] pub sub_resource: SubResource, #[doc = "Properties for the container service agent pool profile."] #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ManagedClusterAgentPoolProfileProperties>, } impl AgentPool { pub fn new() -> Self { Self::default() } } #[doc = "The list of available versions for an agent pool."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AgentPoolAvailableVersions { #[doc = "Id of the agent pool available versions."] #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[doc = "Name of the agent pool available versions."] #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[doc = "Type of the agent pool available versions."] #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[doc = "The list of available agent pool versions."] pub properties: AgentPoolAvailableVersionsProperties, } impl AgentPoolAvailableVersions { pub fn new(properties: AgentPoolAvailableVersionsProperties) -> Self { Self { id: None, name: None, type_: None, properties, } } } #[doc = "The list of available agent pool versions."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct AgentPoolAvailableVersionsProperties { #[doc = "List of versions available for agent pool."] #[serde(rename = "agentPoolVersions", default, skip_serializing_if = "Vec::is_empty")] pub agent_pool_versions: Vec<serde_json::Value>, } impl AgentPoolAvailableVersionsProperties { pub fn new() -> Self { Self::default() } } #[doc = "The response from the List Agent Pools operation."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct AgentPoolListResult { #[doc = "The list of agent pools."] #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<AgentPool>, #[doc = "The URL to get the next set of agent pool results."] #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } impl AgentPoolListResult { pub fn new() -> Self { Self::default() } } #[doc = "AgentPoolMode represents mode of an agent pool."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AgentPoolMode { System, User, } #[doc = "AgentPoolType represents types of an agent pool."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AgentPoolType { VirtualMachineScaleSets, AvailabilitySet, } #[doc = "The list of available upgrades for an agent pool."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AgentPoolUpgradeProfile { #[doc = "Id of the agent pool upgrade profile."] #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[doc = "Name of the agent pool upgrade profile."] #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[doc = "Type of the agent pool upgrade profile."] #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[doc = "The list of available upgrade versions."] pub properties: AgentPoolUpgradeProfileProperties, } impl AgentPoolUpgradeProfile { pub fn new(properties: AgentPoolUpgradeProfileProperties) -> Self { Self { id: None, name: None, type_: None, properties, } } } #[doc = "The list of available upgrade versions."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AgentPoolUpgradeProfileProperties { #[doc = "Kubernetes version (major, minor, patch)."] #[serde(rename = "kubernetesVersion")] pub kubernetes_version: String, #[doc = "OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux."] #[serde(rename = "osType")] pub os_type: OsType, #[doc = "List of orchestrator types and versions available for upgrade."] #[serde(default, skip_serializing_if = "Vec::is_empty")] pub upgrades: Vec<serde_json::Value>, #[doc = "LatestNodeImageVersion is the latest AKS supported node image version."] #[serde(rename = "latestNodeImageVersion", default, skip_serializing_if = "Option::is_none")] pub latest_node_image_version: Option<String>, } impl AgentPoolUpgradeProfileProperties { pub fn new(kubernetes_version: String, os_type: OsType) -> Self { Self { kubernetes_version, os_type, upgrades: Vec::new(), latest_node_image_version: None, } } } #[doc = "Settings for upgrading an agentpool"] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct AgentPoolUpgradeSettings { #[doc = "Count or percentage of additional nodes to be added during upgrade. If empty uses AKS default"] #[serde(rename = "maxSurge", default, skip_serializing_if = "Option::is_none")] pub max_surge: Option<String>, } impl AgentPoolUpgradeSettings { pub fn new() -> Self { Self::default() } } #[doc = "An error response from the Container service."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct CloudError { #[doc = "An error response from the Container service."] #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<CloudErrorBody>, } impl CloudError { pub fn new() -> Self { Self::default() } } #[doc = "An error response from the Container service."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct CloudErrorBody { #[doc = "An identifier for the error. Codes are invariant and are intended to be consumed programmatically."] #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[doc = "A message describing the error, intended to be suitable for display in a user interface."] #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[doc = "The target of the particular error. For example, the name of the property in error."] #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, #[doc = "A list of additional details about the error."] #[serde(default, skip_serializing_if = "Vec::is_empty")] pub details: Vec<CloudErrorBody>, } impl CloudErrorBody { pub fn new() -> Self { Self::default() } } #[doc = "Container service."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerService { #[serde(flatten)] pub resource: Resource, #[doc = "Properties of the container service."] #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ContainerServiceProperties>, } impl ContainerService { pub fn new(resource: Resource) -> Self { Self { resource, properties: None, } } } #[doc = "Profile for the container service agent pool."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerServiceAgentPoolProfile { #[doc = "Unique name of the agent pool profile in the context of the subscription and resource group."] pub name: String, #[doc = "Number of agents (VMs) to host docker containers. Allowed values must be in the range of 1 to 100 (inclusive). The default value is 1. "] #[serde(default, skip_serializing_if = "Option::is_none")] pub count: Option<i32>, #[doc = "Size of agent VMs."] #[serde(rename = "vmSize")] pub vm_size: ContainerServiceVmSize, #[doc = "OS Disk Size in GB to be used to specify the disk size for every machine in this master/agent pool. If you specify 0, it will apply the default osDisk size according to the vmSize specified."] #[serde(rename = "osDiskSizeGB", default, skip_serializing_if = "Option::is_none")] pub os_disk_size_gb: Option<ContainerServiceOsDisk>, #[doc = "DNS prefix to be used to create the FQDN for the agent pool."] #[serde(rename = "dnsPrefix", default, skip_serializing_if = "Option::is_none")] pub dns_prefix: Option<String>, #[doc = "FQDN for the agent pool."] #[serde(default, skip_serializing_if = "Option::is_none")] pub fqdn: Option<String>, #[doc = "Ports number array used to expose on this agent pool. The default opened ports are different based on your choice of orchestrator."] #[serde(default, skip_serializing_if = "Vec::is_empty")] pub ports: Vec<i64>, #[doc = "Storage profile specifies what kind of storage used. Choose from StorageAccount and ManagedDisks. Leave it empty, we will choose for you based on the orchestrator choice."] #[serde(rename = "storageProfile", default, skip_serializing_if = "Option::is_none")] pub storage_profile: Option<ContainerServiceStorageProfile>, #[doc = "VNet SubnetID specifies the VNet's subnet identifier."] #[serde(rename = "vnetSubnetID", default, skip_serializing_if = "Option::is_none")] pub vnet_subnet_id: Option<ContainerServiceVnetSubnetId>, #[doc = "OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux."] #[serde(rename = "osType", default, skip_serializing_if = "Option::is_none")] pub os_type: Option<OsType>, } impl ContainerServiceAgentPoolProfile { pub fn new(name: String, vm_size: ContainerServiceVmSize) -> Self { Self { name, count: None, vm_size, os_disk_size_gb: None, dns_prefix: None, fqdn: None, ports: Vec::new(), storage_profile: None, vnet_subnet_id: None, os_type: None, } } } #[doc = "Properties to configure a custom container service cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerServiceCustomProfile { #[doc = "The name of the custom orchestrator to use."] pub orchestrator: String, } impl ContainerServiceCustomProfile { pub fn new(orchestrator: String) -> Self { Self { orchestrator } } } #[doc = "Profile for diagnostics on the container service cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerServiceDiagnosticsProfile { #[doc = "Profile for diagnostics on the container service VMs."] #[serde(rename = "vmDiagnostics")] pub vm_diagnostics: ContainerServiceVmDiagnostics, } impl ContainerServiceDiagnosticsProfile { pub fn new(vm_diagnostics: ContainerServiceVmDiagnostics) -> Self { Self { vm_diagnostics } } } #[doc = "Profile for Linux VMs in the container service cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerServiceLinuxProfile { #[doc = "The administrator username to use for Linux VMs."] #[serde(rename = "adminUsername")] pub admin_username: String, #[doc = "SSH configuration for Linux-based VMs running on Azure."] pub ssh: ContainerServiceSshConfiguration, } impl ContainerServiceLinuxProfile { pub fn new(admin_username: String, ssh: ContainerServiceSshConfiguration) -> Self { Self { admin_username, ssh } } } #[doc = "The response from the List Container Services operation."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct ContainerServiceListResult { #[doc = "The list of container services."] #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ContainerService>, #[doc = "The URL to get the next set of container service results."] #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } impl ContainerServiceListResult { pub fn new() -> Self { Self::default() } } #[doc = "Profile for the container service master."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerServiceMasterProfile { #[doc = "Number of masters (VMs) in the container service cluster. Allowed values are 1, 3, and 5. The default value is 1."] #[serde(default, skip_serializing_if = "Option::is_none")] pub count: Option<container_service_master_profile::Count>, #[doc = "DNS prefix to be used to create the FQDN for the master pool."] #[serde(rename = "dnsPrefix")] pub dns_prefix: String, #[doc = "Size of agent VMs."] #[serde(rename = "vmSize")] pub vm_size: ContainerServiceVmSize, #[doc = "OS Disk Size in GB to be used to specify the disk size for every machine in this master/agent pool. If you specify 0, it will apply the default osDisk size according to the vmSize specified."] #[serde(rename = "osDiskSizeGB", default, skip_serializing_if = "Option::is_none")] pub os_disk_size_gb: Option<ContainerServiceOsDisk>, #[doc = "VNet SubnetID specifies the VNet's subnet identifier."] #[serde(rename = "vnetSubnetID", default, skip_serializing_if = "Option::is_none")] pub vnet_subnet_id: Option<ContainerServiceVnetSubnetId>, #[doc = "FirstConsecutiveStaticIP used to specify the first static ip of masters."] #[serde(rename = "firstConsecutiveStaticIP", default, skip_serializing_if = "Option::is_none")] pub first_consecutive_static_ip: Option<String>, #[doc = "Storage profile specifies what kind of storage used. Choose from StorageAccount and ManagedDisks. Leave it empty, we will choose for you based on the orchestrator choice."] #[serde(rename = "storageProfile", default, skip_serializing_if = "Option::is_none")] pub storage_profile: Option<ContainerServiceStorageProfile>, #[doc = "FQDN for the master pool."] #[serde(default, skip_serializing_if = "Option::is_none")] pub fqdn: Option<String>, } impl ContainerServiceMasterProfile { pub fn new(dns_prefix: String, vm_size: ContainerServiceVmSize) -> Self { Self { count: None, dns_prefix, vm_size, os_disk_size_gb: None, vnet_subnet_id: None, first_consecutive_static_ip: None, storage_profile: None, fqdn: None, } } } pub mod container_service_master_profile { use super::*; #[doc = "Number of masters (VMs) in the container service cluster. Allowed values are 1, 3, and 5. The default value is 1."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Count {} } #[doc = "Profile of network configuration."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct ContainerServiceNetworkProfile { #[doc = "Network plugin used for building Kubernetes network."] #[serde(rename = "networkPlugin", default, skip_serializing_if = "Option::is_none")] pub network_plugin: Option<container_service_network_profile::NetworkPlugin>, #[doc = "Network policy used for building Kubernetes network."] #[serde(rename = "networkPolicy", default, skip_serializing_if = "Option::is_none")] pub network_policy: Option<container_service_network_profile::NetworkPolicy>, #[doc = "Network mode used for building Kubernetes network."] #[serde(rename = "networkMode", default, skip_serializing_if = "Option::is_none")] pub network_mode: Option<container_service_network_profile::NetworkMode>, #[doc = "A CIDR notation IP range from which to assign pod IPs when kubenet is used."] #[serde(rename = "podCidr", default, skip_serializing_if = "Option::is_none")] pub pod_cidr: Option<String>, #[doc = "A CIDR notation IP range from which to assign service cluster IPs. It must not overlap with any Subnet IP ranges."] #[serde(rename = "serviceCidr", default, skip_serializing_if = "Option::is_none")] pub service_cidr: Option<String>, #[doc = "An IP address assigned to the Kubernetes DNS service. It must be within the Kubernetes service address range specified in serviceCidr."] #[serde(rename = "dnsServiceIP", default, skip_serializing_if = "Option::is_none")] pub dns_service_ip: Option<String>, #[doc = "A CIDR notation IP range assigned to the Docker bridge network. It must not overlap with any Subnet IP ranges or the Kubernetes service address range."] #[serde(rename = "dockerBridgeCidr", default, skip_serializing_if = "Option::is_none")] pub docker_bridge_cidr: Option<String>, #[doc = "The outbound (egress) routing method."] #[serde(rename = "outboundType", default, skip_serializing_if = "Option::is_none")] pub outbound_type: Option<container_service_network_profile::OutboundType>, #[doc = "The load balancer sku for the managed cluster."] #[serde(rename = "loadBalancerSku", default, skip_serializing_if = "Option::is_none")] pub load_balancer_sku: Option<container_service_network_profile::LoadBalancerSku>, #[doc = "Profile of the managed cluster load balancer."] #[serde(rename = "loadBalancerProfile", default, skip_serializing_if = "Option::is_none")] pub load_balancer_profile: Option<ManagedClusterLoadBalancerProfile>, } impl ContainerServiceNetworkProfile { pub fn new() -> Self { Self::default() } } pub mod container_service_network_profile { use super::*; #[doc = "Network plugin used for building Kubernetes network."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum NetworkPlugin { #[serde(rename = "azure")] Azure, #[serde(rename = "kubenet")] Kubenet, } impl Default for NetworkPlugin { fn default() -> Self { Self::Kubenet } } #[doc = "Network policy used for building Kubernetes network."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum NetworkPolicy { #[serde(rename = "calico")] Calico, #[serde(rename = "azure")] Azure, } #[doc = "Network mode used for building Kubernetes network."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum NetworkMode { #[serde(rename = "transparent")] Transparent, #[serde(rename = "bridge")] Bridge, } #[doc = "The outbound (egress) routing method."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum OutboundType { #[serde(rename = "loadBalancer")] LoadBalancer, #[serde(rename = "userDefinedRouting")] UserDefinedRouting, } impl Default for OutboundType { fn default() -> Self { Self::LoadBalancer } } #[doc = "The load balancer sku for the managed cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum LoadBalancerSku { #[serde(rename = "standard")] Standard, #[serde(rename = "basic")] Basic, } } pub type ContainerServiceOsDisk = i32; #[doc = "Profile for the container service orchestrator."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerServiceOrchestratorProfile { #[doc = "The orchestrator to use to manage container service cluster resources. Valid values are Kubernetes, Swarm, DCOS, DockerCE and Custom."] #[serde(rename = "orchestratorType")] pub orchestrator_type: container_service_orchestrator_profile::OrchestratorType, #[doc = "The version of the orchestrator to use. You can specify the major.minor.patch part of the actual version.For example, you can specify version as \"1.6.11\"."] #[serde(rename = "orchestratorVersion", default, skip_serializing_if = "Option::is_none")] pub orchestrator_version: Option<String>, } impl ContainerServiceOrchestratorProfile { pub fn new(orchestrator_type: container_service_orchestrator_profile::OrchestratorType) -> Self { Self { orchestrator_type, orchestrator_version: None, } } } pub mod container_service_orchestrator_profile { use super::*; #[doc = "The orchestrator to use to manage container service cluster resources. Valid values are Kubernetes, Swarm, DCOS, DockerCE and Custom."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum OrchestratorType { Kubernetes, Swarm, #[serde(rename = "DCOS")] Dcos, #[serde(rename = "DockerCE")] DockerCe, Custom, } } #[doc = "Properties of the container service."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerServiceProperties { #[doc = "The current deployment or provisioning state, which only appears in the response."] #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[doc = "Profile for the container service orchestrator."] #[serde(rename = "orchestratorProfile")] pub orchestrator_profile: ContainerServiceOrchestratorProfile, #[doc = "Properties to configure a custom container service cluster."] #[serde(rename = "customProfile", default, skip_serializing_if = "Option::is_none")] pub custom_profile: Option<ContainerServiceCustomProfile>, #[doc = "Information about a service principal identity for the cluster to use for manipulating Azure APIs. Either secret or keyVaultSecretRef must be specified."] #[serde(rename = "servicePrincipalProfile", default, skip_serializing_if = "Option::is_none")] pub service_principal_profile: Option<ContainerServiceServicePrincipalProfile>, #[doc = "Profile for the container service master."] #[serde(rename = "masterProfile")] pub master_profile: ContainerServiceMasterProfile, #[doc = "Properties of the agent pool."] #[serde(rename = "agentPoolProfiles", default, skip_serializing_if = "Vec::is_empty")] pub agent_pool_profiles: Vec<ContainerServiceAgentPoolProfile>, #[doc = "Profile for Windows VMs in the container service cluster."] #[serde(rename = "windowsProfile", default, skip_serializing_if = "Option::is_none")] pub windows_profile: Option<ContainerServiceWindowsProfile>, #[doc = "Profile for Linux VMs in the container service cluster."] #[serde(rename = "linuxProfile")] pub linux_profile: ContainerServiceLinuxProfile, #[doc = "Profile for diagnostics on the container service cluster."] #[serde(rename = "diagnosticsProfile", default, skip_serializing_if = "Option::is_none")] pub diagnostics_profile: Option<ContainerServiceDiagnosticsProfile>, } impl ContainerServiceProperties { pub fn new( orchestrator_profile: ContainerServiceOrchestratorProfile, master_profile: ContainerServiceMasterProfile, linux_profile: ContainerServiceLinuxProfile, ) -> Self { Self { provisioning_state: None, orchestrator_profile, custom_profile: None, service_principal_profile: None, master_profile, agent_pool_profiles: Vec::new(), windows_profile: None, linux_profile, diagnostics_profile: None, } } } #[doc = "Information about a service principal identity for the cluster to use for manipulating Azure APIs. Either secret or keyVaultSecretRef must be specified."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerServiceServicePrincipalProfile { #[doc = "The ID for the service principal."] #[serde(rename = "clientId")] pub client_id: String, #[doc = "The secret password associated with the service principal in plain text."] #[serde(default, skip_serializing_if = "Option::is_none")] pub secret: Option<String>, #[doc = "Reference to a secret stored in Azure Key Vault."] #[serde(rename = "keyVaultSecretRef", default, skip_serializing_if = "Option::is_none")] pub key_vault_secret_ref: Option<KeyVaultSecretRef>, } impl ContainerServiceServicePrincipalProfile { pub fn new(client_id: String) -> Self { Self { client_id, secret: None, key_vault_secret_ref: None, } } } #[doc = "SSH configuration for Linux-based VMs running on Azure."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerServiceSshConfiguration { #[doc = "The list of SSH public keys used to authenticate with Linux-based VMs. Only expect one key specified."] #[serde(rename = "publicKeys")] pub public_keys: Vec<ContainerServiceSshPublicKey>, } impl ContainerServiceSshConfiguration { pub fn new(public_keys: Vec<ContainerServiceSshPublicKey>) -> Self { Self { public_keys } } } #[doc = "Contains information about SSH certificate public key data."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerServiceSshPublicKey { #[doc = "Certificate public key used to authenticate with VMs through SSH. The certificate must be in PEM format with or without headers."] #[serde(rename = "keyData")] pub key_data: String, } impl ContainerServiceSshPublicKey { pub fn new(key_data: String) -> Self { Self { key_data } } } #[doc = "Storage profile specifies what kind of storage used. Choose from StorageAccount and ManagedDisks. Leave it empty, we will choose for you based on the orchestrator choice."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ContainerServiceStorageProfile { StorageAccount, ManagedDisks, } #[doc = "Profile for diagnostics on the container service VMs."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerServiceVmDiagnostics { #[doc = "Whether the VM diagnostic agent is provisioned on the VM."] pub enabled: bool, #[doc = "The URI of the storage account where diagnostics are stored."] #[serde(rename = "storageUri", default, skip_serializing_if = "Option::is_none")] pub storage_uri: Option<String>, } impl ContainerServiceVmDiagnostics { pub fn new(enabled: bool) -> Self { Self { enabled, storage_uri: None, } } } #[doc = "Size of agent VMs."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ContainerServiceVmSize { #[serde(rename = "Standard_A1")] StandardA1, #[serde(rename = "Standard_A10")] StandardA10, #[serde(rename = "Standard_A11")] StandardA11, #[serde(rename = "Standard_A1_v2")] StandardA1V2, #[serde(rename = "Standard_A2")] StandardA2, #[serde(rename = "Standard_A2_v2")] StandardA2V2, #[serde(rename = "Standard_A2m_v2")] StandardA2mV2, #[serde(rename = "Standard_A3")] StandardA3, #[serde(rename = "Standard_A4")] StandardA4, #[serde(rename = "Standard_A4_v2")] StandardA4V2, #[serde(rename = "Standard_A4m_v2")] StandardA4mV2, #[serde(rename = "Standard_A5")] StandardA5, #[serde(rename = "Standard_A6")] StandardA6, #[serde(rename = "Standard_A7")] StandardA7, #[serde(rename = "Standard_A8")] StandardA8, #[serde(rename = "Standard_A8_v2")] StandardA8V2, #[serde(rename = "Standard_A8m_v2")] StandardA8mV2, #[serde(rename = "Standard_A9")] StandardA9, #[serde(rename = "Standard_B2ms")] StandardB2ms, #[serde(rename = "Standard_B2s")] StandardB2s, #[serde(rename = "Standard_B4ms")] StandardB4ms, #[serde(rename = "Standard_B8ms")] StandardB8ms, #[serde(rename = "Standard_D1")] StandardD1, #[serde(rename = "Standard_D11")] StandardD11, #[serde(rename = "Standard_D11_v2")] StandardD11V2, #[serde(rename = "Standard_D11_v2_Promo")] StandardD11V2Promo, #[serde(rename = "Standard_D12")] StandardD12, #[serde(rename = "Standard_D12_v2")] StandardD12V2, #[serde(rename = "Standard_D12_v2_Promo")] StandardD12V2Promo, #[serde(rename = "Standard_D13")] StandardD13, #[serde(rename = "Standard_D13_v2")] StandardD13V2, #[serde(rename = "Standard_D13_v2_Promo")] StandardD13V2Promo, #[serde(rename = "Standard_D14")] StandardD14, #[serde(rename = "Standard_D14_v2")] StandardD14V2, #[serde(rename = "Standard_D14_v2_Promo")] StandardD14V2Promo, #[serde(rename = "Standard_D15_v2")] StandardD15V2, #[serde(rename = "Standard_D16_v3")] StandardD16V3, #[serde(rename = "Standard_D16s_v3")] StandardD16sV3, #[serde(rename = "Standard_D1_v2")] StandardD1V2, #[serde(rename = "Standard_D2")] StandardD2, #[serde(rename = "Standard_D2_v2")] StandardD2V2, #[serde(rename = "Standard_D2_v2_Promo")] StandardD2V2Promo, #[serde(rename = "Standard_D2_v3")] StandardD2V3, #[serde(rename = "Standard_D2s_v3")] StandardD2sV3, #[serde(rename = "Standard_D3")] StandardD3, #[serde(rename = "Standard_D32_v3")] StandardD32V3, #[serde(rename = "Standard_D32s_v3")] StandardD32sV3, #[serde(rename = "Standard_D3_v2")] StandardD3V2, #[serde(rename = "Standard_D3_v2_Promo")] StandardD3V2Promo, #[serde(rename = "Standard_D4")] StandardD4, #[serde(rename = "Standard_D4_v2")] StandardD4V2, #[serde(rename = "Standard_D4_v2_Promo")] StandardD4V2Promo, #[serde(rename = "Standard_D4_v3")] StandardD4V3, #[serde(rename = "Standard_D4s_v3")] StandardD4sV3, #[serde(rename = "Standard_D5_v2")] StandardD5V2, #[serde(rename = "Standard_D5_v2_Promo")] StandardD5V2Promo, #[serde(rename = "Standard_D64_v3")] StandardD64V3, #[serde(rename = "Standard_D64s_v3")] StandardD64sV3, #[serde(rename = "Standard_D8_v3")] StandardD8V3, #[serde(rename = "Standard_D8s_v3")] StandardD8sV3, #[serde(rename = "Standard_DS1")] StandardDs1, #[serde(rename = "Standard_DS11")] StandardDs11, #[serde(rename = "Standard_DS11_v2")] StandardDs11V2, #[serde(rename = "Standard_DS11_v2_Promo")] StandardDs11V2Promo, #[serde(rename = "Standard_DS12")] StandardDs12, #[serde(rename = "Standard_DS12_v2")] StandardDs12V2, #[serde(rename = "Standard_DS12_v2_Promo")] StandardDs12V2Promo, #[serde(rename = "Standard_DS13")] StandardDs13, #[serde(rename = "Standard_DS13-2_v2")] StandardDs132V2, #[serde(rename = "Standard_DS13-4_v2")] StandardDs134V2, #[serde(rename = "Standard_DS13_v2")] StandardDs13V2, #[serde(rename = "Standard_DS13_v2_Promo")] StandardDs13V2Promo, #[serde(rename = "Standard_DS14")] StandardDs14, #[serde(rename = "Standard_DS14-4_v2")] StandardDs144V2, #[serde(rename = "Standard_DS14-8_v2")] StandardDs148V2, #[serde(rename = "Standard_DS14_v2")] StandardDs14V2, #[serde(rename = "Standard_DS14_v2_Promo")] StandardDs14V2Promo, #[serde(rename = "Standard_DS15_v2")] StandardDs15V2, #[serde(rename = "Standard_DS1_v2")] StandardDs1V2, #[serde(rename = "Standard_DS2")] StandardDs2, #[serde(rename = "Standard_DS2_v2")] StandardDs2V2, #[serde(rename = "Standard_DS2_v2_Promo")] StandardDs2V2Promo, #[serde(rename = "Standard_DS3")] StandardDs3, #[serde(rename = "Standard_DS3_v2")] StandardDs3V2, #[serde(rename = "Standard_DS3_v2_Promo")] StandardDs3V2Promo, #[serde(rename = "Standard_DS4")] StandardDs4, #[serde(rename = "Standard_DS4_v2")] StandardDs4V2, #[serde(rename = "Standard_DS4_v2_Promo")] StandardDs4V2Promo, #[serde(rename = "Standard_DS5_v2")] StandardDs5V2, #[serde(rename = "Standard_DS5_v2_Promo")] StandardDs5V2Promo, #[serde(rename = "Standard_E16_v3")] StandardE16V3, #[serde(rename = "Standard_E16s_v3")] StandardE16sV3, #[serde(rename = "Standard_E2_v3")] StandardE2V3, #[serde(rename = "Standard_E2s_v3")] StandardE2sV3, #[serde(rename = "Standard_E32-16s_v3")] StandardE3216sV3, #[serde(rename = "Standard_E32-8s_v3")] StandardE328sV3, #[serde(rename = "Standard_E32_v3")] StandardE32V3, #[serde(rename = "Standard_E32s_v3")] StandardE32sV3, #[serde(rename = "Standard_E4_v3")] StandardE4V3, #[serde(rename = "Standard_E4s_v3")] StandardE4sV3, #[serde(rename = "Standard_E64-16s_v3")] StandardE6416sV3, #[serde(rename = "Standard_E64-32s_v3")] StandardE6432sV3, #[serde(rename = "Standard_E64_v3")] StandardE64V3, #[serde(rename = "Standard_E64s_v3")] StandardE64sV3, #[serde(rename = "Standard_E8_v3")] StandardE8V3, #[serde(rename = "Standard_E8s_v3")] StandardE8sV3, #[serde(rename = "Standard_F1")] StandardF1, #[serde(rename = "Standard_F16")] StandardF16, #[serde(rename = "Standard_F16s")] StandardF16s, #[serde(rename = "Standard_F16s_v2")] StandardF16sV2, #[serde(rename = "Standard_F1s")] StandardF1s, #[serde(rename = "Standard_F2")] StandardF2, #[serde(rename = "Standard_F2s")] StandardF2s, #[serde(rename = "Standard_F2s_v2")] StandardF2sV2, #[serde(rename = "Standard_F32s_v2")] StandardF32sV2, #[serde(rename = "Standard_F4")] StandardF4, #[serde(rename = "Standard_F4s")] StandardF4s, #[serde(rename = "Standard_F4s_v2")] StandardF4sV2, #[serde(rename = "Standard_F64s_v2")] StandardF64sV2, #[serde(rename = "Standard_F72s_v2")] StandardF72sV2, #[serde(rename = "Standard_F8")] StandardF8, #[serde(rename = "Standard_F8s")] StandardF8s, #[serde(rename = "Standard_F8s_v2")] StandardF8sV2, #[serde(rename = "Standard_G1")] StandardG1, #[serde(rename = "Standard_G2")] StandardG2, #[serde(rename = "Standard_G3")] StandardG3, #[serde(rename = "Standard_G4")] StandardG4, #[serde(rename = "Standard_G5")] StandardG5, #[serde(rename = "Standard_GS1")] StandardGs1, #[serde(rename = "Standard_GS2")] StandardGs2, #[serde(rename = "Standard_GS3")] StandardGs3, #[serde(rename = "Standard_GS4")] StandardGs4, #[serde(rename = "Standard_GS4-4")] StandardGs44, #[serde(rename = "Standard_GS4-8")] StandardGs48, #[serde(rename = "Standard_GS5")] StandardGs5, #[serde(rename = "Standard_GS5-16")] StandardGs516, #[serde(rename = "Standard_GS5-8")] StandardGs58, #[serde(rename = "Standard_H16")] StandardH16, #[serde(rename = "Standard_H16m")] StandardH16m, #[serde(rename = "Standard_H16mr")] StandardH16mr, #[serde(rename = "Standard_H16r")] StandardH16r, #[serde(rename = "Standard_H8")] StandardH8, #[serde(rename = "Standard_H8m")] StandardH8m, #[serde(rename = "Standard_L16s")] StandardL16s, #[serde(rename = "Standard_L32s")] StandardL32s, #[serde(rename = "Standard_L4s")] StandardL4s, #[serde(rename = "Standard_L8s")] StandardL8s, #[serde(rename = "Standard_M128-32ms")] StandardM12832ms, #[serde(rename = "Standard_M128-64ms")] StandardM12864ms, #[serde(rename = "Standard_M128ms")] StandardM128ms, #[serde(rename = "Standard_M128s")] StandardM128s, #[serde(rename = "Standard_M64-16ms")] StandardM6416ms, #[serde(rename = "Standard_M64-32ms")] StandardM6432ms, #[serde(rename = "Standard_M64ms")] StandardM64ms, #[serde(rename = "Standard_M64s")] StandardM64s, #[serde(rename = "Standard_NC12")] StandardNc12, #[serde(rename = "Standard_NC12s_v2")] StandardNc12sV2, #[serde(rename = "Standard_NC12s_v3")] StandardNc12sV3, #[serde(rename = "Standard_NC24")] StandardNc24, #[serde(rename = "Standard_NC24r")] StandardNc24r, #[serde(rename = "Standard_NC24rs_v2")] StandardNc24rsV2, #[serde(rename = "Standard_NC24rs_v3")] StandardNc24rsV3, #[serde(rename = "Standard_NC24s_v2")] StandardNc24sV2, #[serde(rename = "Standard_NC24s_v3")] StandardNc24sV3, #[serde(rename = "Standard_NC6")] StandardNc6, #[serde(rename = "Standard_NC6s_v2")] StandardNc6sV2, #[serde(rename = "Standard_NC6s_v3")] StandardNc6sV3, #[serde(rename = "Standard_ND12s")] StandardNd12s, #[serde(rename = "Standard_ND24rs")] StandardNd24rs, #[serde(rename = "Standard_ND24s")] StandardNd24s, #[serde(rename = "Standard_ND6s")] StandardNd6s, #[serde(rename = "Standard_NV12")] StandardNv12, #[serde(rename = "Standard_NV24")] StandardNv24, #[serde(rename = "Standard_NV6")] StandardNv6, } pub type ContainerServiceVnetSubnetId = String; #[doc = "Profile for Windows VMs in the container service cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerServiceWindowsProfile { #[doc = "The administrator username to use for Windows VMs."] #[serde(rename = "adminUsername")] pub admin_username: String, #[doc = "The administrator password to use for Windows VMs."] #[serde(rename = "adminPassword")] pub admin_password: String, } impl ContainerServiceWindowsProfile { pub fn new(admin_username: String, admin_password: String) -> Self { Self { admin_username, admin_password, } } } #[doc = "The credential result response."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct CredentialResult { #[doc = "The name of the credential."] #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[doc = "Base64-encoded Kubernetes configuration file."] #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, } impl CredentialResult { pub fn new() -> Self { Self::default() } } #[doc = "The list of credential result response."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct CredentialResults { #[doc = "Base64-encoded Kubernetes configuration file."] #[serde(default, skip_serializing_if = "Vec::is_empty")] pub kubeconfigs: Vec<CredentialResult>, } impl CredentialResults { pub fn new() -> Self { Self::default() } } #[doc = "Reference to a secret stored in Azure Key Vault."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct KeyVaultSecretRef { #[doc = "Key vault identifier."] #[serde(rename = "vaultID")] pub vault_id: String, #[doc = "The secret name."] #[serde(rename = "secretName")] pub secret_name: String, #[doc = "The secret version."] #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, } impl KeyVaultSecretRef { pub fn new(vault_id: String, secret_name: String) -> Self { Self { vault_id, secret_name, version: None, } } } #[doc = "Managed cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagedCluster { #[serde(flatten)] pub resource: Resource, #[doc = "Properties of the managed cluster."] #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ManagedClusterProperties>, #[doc = "Identity for the managed cluster."] #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<ManagedClusterIdentity>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<ManagedClusterSku>, } impl ManagedCluster { pub fn new(resource: Resource) -> Self { Self { resource, properties: None, identity: None, sku: None, } } } #[doc = "AADProfile specifies attributes for Azure Active Directory integration."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct ManagedClusterAadProfile { #[doc = "Whether to enable managed AAD."] #[serde(default, skip_serializing_if = "Option::is_none")] pub managed: Option<bool>, #[doc = "AAD group object IDs that will have admin role of the cluster."] #[serde(rename = "adminGroupObjectIDs", default, skip_serializing_if = "Vec::is_empty")] pub admin_group_object_i_ds: Vec<String>, #[doc = "The client AAD application ID."] #[serde(rename = "clientAppID", default, skip_serializing_if = "Option::is_none")] pub client_app_id: Option<String>, #[doc = "The server AAD application ID."] #[serde(rename = "serverAppID", default, skip_serializing_if = "Option::is_none")] pub server_app_id: Option<String>, #[doc = "The server AAD application secret."] #[serde(rename = "serverAppSecret", default, skip_serializing_if = "Option::is_none")] pub server_app_secret: Option<String>, #[doc = "The AAD tenant ID to use for authentication. If not specified, will use the tenant of the deployment subscription."] #[serde(rename = "tenantID", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, } impl ManagedClusterAadProfile { pub fn new() -> Self { Self::default() } } #[doc = "Access profile for managed cluster API server."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct ManagedClusterApiServerAccessProfile { #[doc = "Authorized IP Ranges to kubernetes API server."] #[serde(rename = "authorizedIPRanges", default, skip_serializing_if = "Vec::is_empty")] pub authorized_ip_ranges: Vec<String>, #[doc = "Whether to create the cluster as a private cluster or not."] #[serde(rename = "enablePrivateCluster", default, skip_serializing_if = "Option::is_none")] pub enable_private_cluster: Option<bool>, } impl ManagedClusterApiServerAccessProfile { pub fn new() -> Self { Self::default() } } #[doc = "Managed cluster Access Profile."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagedClusterAccessProfile { #[serde(flatten)] pub resource: Resource, #[doc = "Profile for enabling a user to access a managed cluster."] #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AccessProfile>, } impl ManagedClusterAccessProfile { pub fn new(resource: Resource) -> Self { Self { resource, properties: None, } } } #[doc = "A Kubernetes add-on profile for a managed cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagedClusterAddonProfile { #[doc = "Whether the add-on is enabled or not."] pub enabled: bool, #[doc = "Key-value pairs for configuring an add-on."] #[serde(default, skip_serializing_if = "Option::is_none")] pub config: Option<serde_json::Value>, #[doc = "Information of user assigned identity used by this add-on."] #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<serde_json::Value>, } impl ManagedClusterAddonProfile { pub fn new(enabled: bool) -> Self { Self { enabled, config: None, identity: None, } } } #[doc = "Profile for the container service agent pool."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagedClusterAgentPoolProfile { #[serde(flatten)] pub managed_cluster_agent_pool_profile_properties: ManagedClusterAgentPoolProfileProperties, #[doc = "Unique name of the agent pool profile in the context of the subscription and resource group."] pub name: String, } impl ManagedClusterAgentPoolProfile { pub fn new(name: String) -> Self { Self { managed_cluster_agent_pool_profile_properties: ManagedClusterAgentPoolProfileProperties::default(), name, } } } #[doc = "Properties for the container service agent pool profile."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct ManagedClusterAgentPoolProfileProperties { #[doc = "Number of agents (VMs) to host docker containers. Allowed values must be in the range of 0 to 100 (inclusive) for user pools and in the range of 1 to 100 (inclusive) for system pools. The default value is 1."] #[serde(default, skip_serializing_if = "Option::is_none")] pub count: Option<i32>, #[doc = "Size of agent VMs."] #[serde(rename = "vmSize", default, skip_serializing_if = "Option::is_none")] pub vm_size: Option<ContainerServiceVmSize>, #[doc = "OS Disk Size in GB to be used to specify the disk size for every machine in this master/agent pool. If you specify 0, it will apply the default osDisk size according to the vmSize specified."] #[serde(rename = "osDiskSizeGB", default, skip_serializing_if = "Option::is_none")] pub os_disk_size_gb: Option<ContainerServiceOsDisk>, #[doc = "VNet SubnetID specifies the VNet's subnet identifier."] #[serde(rename = "vnetSubnetID", default, skip_serializing_if = "Option::is_none")] pub vnet_subnet_id: Option<ContainerServiceVnetSubnetId>, #[doc = "Maximum number of pods that can run on a node."] #[serde(rename = "maxPods", default, skip_serializing_if = "Option::is_none")] pub max_pods: Option<i32>, #[doc = "OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux."] #[serde(rename = "osType", default, skip_serializing_if = "Option::is_none")] pub os_type: Option<OsType>, #[doc = "Maximum number of nodes for auto-scaling"] #[serde(rename = "maxCount", default, skip_serializing_if = "Option::is_none")] pub max_count: Option<i32>, #[doc = "Minimum number of nodes for auto-scaling"] #[serde(rename = "minCount", default, skip_serializing_if = "Option::is_none")] pub min_count: Option<i32>, #[doc = "Whether to enable auto-scaler"] #[serde(rename = "enableAutoScaling", default, skip_serializing_if = "Option::is_none")] pub enable_auto_scaling: Option<bool>, #[doc = "AgentPoolType represents types of an agent pool."] #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<AgentPoolType>, #[doc = "AgentPoolMode represents mode of an agent pool."] #[serde(default, skip_serializing_if = "Option::is_none")] pub mode: Option<AgentPoolMode>, #[doc = "Version of orchestrator specified when creating the managed cluster."] #[serde(rename = "orchestratorVersion", default, skip_serializing_if = "Option::is_none")] pub orchestrator_version: Option<String>, #[doc = "Version of node image"] #[serde(rename = "nodeImageVersion", default, skip_serializing_if = "Option::is_none")] pub node_image_version: Option<String>, #[doc = "Settings for upgrading an agentpool"] #[serde(rename = "upgradeSettings", default, skip_serializing_if = "Option::is_none")] pub upgrade_settings: Option<AgentPoolUpgradeSettings>, #[doc = "The current deployment or provisioning state, which only appears in the response."] #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[doc = "Availability zones for nodes. Must use VirtualMachineScaleSets AgentPoolType."] #[serde(rename = "availabilityZones", default, skip_serializing_if = "Vec::is_empty")] pub availability_zones: Vec<String>, #[doc = "Enable public IP for nodes"] #[serde(rename = "enableNodePublicIP", default, skip_serializing_if = "Option::is_none")] pub enable_node_public_ip: Option<bool>, #[doc = "ScaleSetPriority to be used to specify virtual machine scale set priority. Default to regular."] #[serde(rename = "scaleSetPriority", default, skip_serializing_if = "Option::is_none")] pub scale_set_priority: Option<ScaleSetPriority>, #[doc = "ScaleSetEvictionPolicy to be used to specify eviction policy for Spot virtual machine scale set. Default to Delete."] #[serde(rename = "scaleSetEvictionPolicy", default, skip_serializing_if = "Option::is_none")] pub scale_set_eviction_policy: Option<ScaleSetEvictionPolicy>, #[doc = "SpotMaxPrice to be used to specify the maximum price you are willing to pay in US Dollars. Possible values are any decimal value greater than zero or -1 which indicates default price to be up-to on-demand."] #[serde(rename = "spotMaxPrice", default, skip_serializing_if = "Option::is_none")] pub spot_max_price: Option<SpotMaxPrice>, #[doc = "Agent pool tags to be persisted on the agent pool virtual machine scale set."] #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, #[doc = "Agent pool node labels to be persisted across all nodes in agent pool."] #[serde(rename = "nodeLabels", default, skip_serializing_if = "Option::is_none")] pub node_labels: Option<serde_json::Value>, #[doc = "Taints added to new nodes during node pool create and scale. For example, key=value:NoSchedule."] #[serde(rename = "nodeTaints", default, skip_serializing_if = "Vec::is_empty")] pub node_taints: Vec<String>, } impl ManagedClusterAgentPoolProfileProperties { pub fn new() -> Self { Self::default() } } #[doc = "Identity for the managed cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct ManagedClusterIdentity { #[doc = "The principal id of the system assigned identity which is used by master components."] #[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")] pub principal_id: Option<String>, #[doc = "The tenant id of the system assigned identity which is used by master components."] #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[doc = "The type of identity used for the managed cluster. Type 'SystemAssigned' will use an implicitly created identity in master components and an auto-created user assigned identity in MC_ resource group in agent nodes. Type 'None' will not use MSI for the managed cluster, service principal will be used instead."] #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<managed_cluster_identity::Type>, } impl ManagedClusterIdentity { pub fn new() -> Self { Self::default() } } pub mod managed_cluster_identity { use super::*; #[doc = "The type of identity used for the managed cluster. Type 'SystemAssigned' will use an implicitly created identity in master components and an auto-created user assigned identity in MC_ resource group in agent nodes. Type 'None' will not use MSI for the managed cluster, service principal will be used instead."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { SystemAssigned, None, } } #[doc = "The response from the List Managed Clusters operation."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct ManagedClusterListResult { #[doc = "The list of managed clusters."] #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ManagedCluster>, #[doc = "The URL to get the next set of managed cluster results."] #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } impl ManagedClusterListResult { pub fn new() -> Self { Self::default() } } #[doc = "Profile of the managed cluster load balancer."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct ManagedClusterLoadBalancerProfile { #[doc = "Desired managed outbound IPs for the cluster load balancer."] #[serde(rename = "managedOutboundIPs", default, skip_serializing_if = "Option::is_none")] pub managed_outbound_i_ps: Option<managed_cluster_load_balancer_profile::ManagedOutboundIPs>, #[doc = "Desired outbound IP Prefix resources for the cluster load balancer."] #[serde(rename = "outboundIPPrefixes", default, skip_serializing_if = "Option::is_none")] pub outbound_ip_prefixes: Option<managed_cluster_load_balancer_profile::OutboundIpPrefixes>, #[doc = "Desired outbound IP resources for the cluster load balancer."] #[serde(rename = "outboundIPs", default, skip_serializing_if = "Option::is_none")] pub outbound_i_ps: Option<managed_cluster_load_balancer_profile::OutboundIPs>, #[doc = "The effective outbound IP resources of the cluster load balancer."] #[serde(rename = "effectiveOutboundIPs", default, skip_serializing_if = "Vec::is_empty")] pub effective_outbound_i_ps: Vec<ResourceReference>, #[doc = "Desired number of allocated SNAT ports per VM. Allowed values must be in the range of 0 to 64000 (inclusive). The default value is 0 which results in Azure dynamically allocating ports."] #[serde(rename = "allocatedOutboundPorts", default, skip_serializing_if = "Option::is_none")] pub allocated_outbound_ports: Option<i32>, #[doc = "Desired outbound flow idle timeout in minutes. Allowed values must be in the range of 4 to 120 (inclusive). The default value is 30 minutes."] #[serde(rename = "idleTimeoutInMinutes", default, skip_serializing_if = "Option::is_none")] pub idle_timeout_in_minutes: Option<i32>, } impl ManagedClusterLoadBalancerProfile { pub fn new() -> Self { Self::default() } } pub mod managed_cluster_load_balancer_profile { use super::*; #[doc = "Desired managed outbound IPs for the cluster load balancer."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct ManagedOutboundIPs { #[doc = "Desired number of outbound IP created/managed by Azure for the cluster load balancer. Allowed values must be in the range of 1 to 100 (inclusive). The default value is 1. "] #[serde(default, skip_serializing_if = "Option::is_none")] pub count: Option<i32>, } impl ManagedOutboundIPs { pub fn new() -> Self { Self::default() } } #[doc = "Desired outbound IP Prefix resources for the cluster load balancer."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct OutboundIpPrefixes { #[doc = "A list of public IP prefix resources."] #[serde(rename = "publicIPPrefixes", default, skip_serializing_if = "Vec::is_empty")] pub public_ip_prefixes: Vec<ResourceReference>, } impl OutboundIpPrefixes { pub fn new() -> Self { Self::default() } } #[doc = "Desired outbound IP resources for the cluster load balancer."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct OutboundIPs { #[doc = "A list of public IP resources."] #[serde(rename = "publicIPs", default, skip_serializing_if = "Vec::is_empty")] pub public_i_ps: Vec<ResourceReference>, } impl OutboundIPs { pub fn new() -> Self { Self::default() } } } #[doc = "The list of available upgrade versions."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagedClusterPoolUpgradeProfile { #[doc = "Kubernetes version (major, minor, patch)."] #[serde(rename = "kubernetesVersion")] pub kubernetes_version: String, #[doc = "Pool name."] #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[doc = "OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux."] #[serde(rename = "osType")] pub os_type: OsType, #[doc = "List of orchestrator types and versions available for upgrade."] #[serde(default, skip_serializing_if = "Vec::is_empty")] pub upgrades: Vec<serde_json::Value>, } impl ManagedClusterPoolUpgradeProfile { pub fn new(kubernetes_version: String, os_type: OsType) -> Self { Self { kubernetes_version, name: None, os_type, upgrades: Vec::new(), } } } #[doc = "Properties of the managed cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct ManagedClusterProperties { #[doc = "The current deployment or provisioning state, which only appears in the response."] #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[doc = "The max number of agent pools for the managed cluster."] #[serde(rename = "maxAgentPools", default, skip_serializing_if = "Option::is_none")] pub max_agent_pools: Option<i32>, #[doc = "Version of Kubernetes specified when creating the managed cluster."] #[serde(rename = "kubernetesVersion", default, skip_serializing_if = "Option::is_none")] pub kubernetes_version: Option<String>, #[doc = "DNS prefix specified when creating the managed cluster."] #[serde(rename = "dnsPrefix", default, skip_serializing_if = "Option::is_none")] pub dns_prefix: Option<String>, #[doc = "FQDN for the master pool."] #[serde(default, skip_serializing_if = "Option::is_none")] pub fqdn: Option<String>, #[doc = "FQDN of private cluster."] #[serde(rename = "privateFQDN", default, skip_serializing_if = "Option::is_none")] pub private_fqdn: Option<String>, #[doc = "Properties of the agent pool."] #[serde(rename = "agentPoolProfiles", default, skip_serializing_if = "Vec::is_empty")] pub agent_pool_profiles: Vec<ManagedClusterAgentPoolProfile>, #[doc = "Profile for Linux VMs in the container service cluster."] #[serde(rename = "linuxProfile", default, skip_serializing_if = "Option::is_none")] pub linux_profile: Option<ContainerServiceLinuxProfile>, #[doc = "Profile for Windows VMs in the container service cluster."] #[serde(rename = "windowsProfile", default, skip_serializing_if = "Option::is_none")] pub windows_profile: Option<ManagedClusterWindowsProfile>, #[doc = "Information about a service principal identity for the cluster to use for manipulating Azure APIs."] #[serde(rename = "servicePrincipalProfile", default, skip_serializing_if = "Option::is_none")] pub service_principal_profile: Option<ManagedClusterServicePrincipalProfile>, #[doc = "Profile of managed cluster add-on."] #[serde(rename = "addonProfiles", default, skip_serializing_if = "Option::is_none")] pub addon_profiles: Option<serde_json::Value>, #[doc = "Name of the resource group containing agent pool nodes."] #[serde(rename = "nodeResourceGroup", default, skip_serializing_if = "Option::is_none")] pub node_resource_group: Option<String>, #[doc = "Whether to enable Kubernetes Role-Based Access Control."] #[serde(rename = "enableRBAC", default, skip_serializing_if = "Option::is_none")] pub enable_rbac: Option<bool>, #[doc = "(DEPRECATING) Whether to enable Kubernetes pod security policy (preview). This feature is set for removal on October 15th, 2020. Learn more at aka.ms/aks/azpodpolicy."] #[serde(rename = "enablePodSecurityPolicy", default, skip_serializing_if = "Option::is_none")] pub enable_pod_security_policy: Option<bool>, #[doc = "Profile of network configuration."] #[serde(rename = "networkProfile", default, skip_serializing_if = "Option::is_none")] pub network_profile: Option<ContainerServiceNetworkProfile>, #[doc = "AADProfile specifies attributes for Azure Active Directory integration."] #[serde(rename = "aadProfile", default, skip_serializing_if = "Option::is_none")] pub aad_profile: Option<ManagedClusterAadProfile>, #[doc = "Parameters to be applied to the cluster-autoscaler when enabled"] #[serde(rename = "autoScalerProfile", default, skip_serializing_if = "Option::is_none")] pub auto_scaler_profile: Option<managed_cluster_properties::AutoScalerProfile>, #[doc = "Access profile for managed cluster API server."] #[serde(rename = "apiServerAccessProfile", default, skip_serializing_if = "Option::is_none")] pub api_server_access_profile: Option<ManagedClusterApiServerAccessProfile>, #[doc = "ResourceId of the disk encryption set to use for enabling encryption at rest."] #[serde(rename = "diskEncryptionSetID", default, skip_serializing_if = "Option::is_none")] pub disk_encryption_set_id: Option<String>, #[doc = "Identities associated with the cluster."] #[serde(rename = "identityProfile", default, skip_serializing_if = "Option::is_none")] pub identity_profile: Option<serde_json::Value>, } impl ManagedClusterProperties { pub fn new() -> Self { Self::default() } } pub mod managed_cluster_properties { use super::*; #[doc = "Parameters to be applied to the cluster-autoscaler when enabled"] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct AutoScalerProfile { #[serde(rename = "balance-similar-node-groups", default, skip_serializing_if = "Option::is_none")] pub balance_similar_node_groups: Option<String>, #[serde(rename = "scan-interval", default, skip_serializing_if = "Option::is_none")] pub scan_interval: Option<String>, #[serde(rename = "scale-down-delay-after-add", default, skip_serializing_if = "Option::is_none")] pub scale_down_delay_after_add: Option<String>, #[serde(rename = "scale-down-delay-after-delete", default, skip_serializing_if = "Option::is_none")] pub scale_down_delay_after_delete: Option<String>, #[serde(rename = "scale-down-delay-after-failure", default, skip_serializing_if = "Option::is_none")] pub scale_down_delay_after_failure: Option<String>, #[serde(rename = "scale-down-unneeded-time", default, skip_serializing_if = "Option::is_none")] pub scale_down_unneeded_time: Option<String>, #[serde(rename = "scale-down-unready-time", default, skip_serializing_if = "Option::is_none")] pub scale_down_unready_time: Option<String>, #[serde(rename = "scale-down-utilization-threshold", default, skip_serializing_if = "Option::is_none")] pub scale_down_utilization_threshold: Option<String>, #[serde(rename = "max-graceful-termination-sec", default, skip_serializing_if = "Option::is_none")] pub max_graceful_termination_sec: Option<String>, } impl AutoScalerProfile { pub fn new() -> Self { Self::default() } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct ManagedClusterSku { #[doc = "Name of a managed cluster SKU."] #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<managed_cluster_sku::Name>, #[doc = "Tier of a managed cluster SKU."] #[serde(default, skip_serializing_if = "Option::is_none")] pub tier: Option<managed_cluster_sku::Tier>, } impl ManagedClusterSku { pub fn new() -> Self { Self::default() } } pub mod managed_cluster_sku { use super::*; #[doc = "Name of a managed cluster SKU."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { Basic, } #[doc = "Tier of a managed cluster SKU."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Tier { Paid, Free, } } #[doc = "Information about a service principal identity for the cluster to use for manipulating Azure APIs."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagedClusterServicePrincipalProfile { #[doc = "The ID for the service principal."] #[serde(rename = "clientId")] pub client_id: String, #[doc = "The secret password associated with the service principal in plain text."] #[serde(default, skip_serializing_if = "Option::is_none")] pub secret: Option<String>, } impl ManagedClusterServicePrincipalProfile { pub fn new(client_id: String) -> Self { Self { client_id, secret: None } } } #[doc = "The list of available upgrades for compute pools."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagedClusterUpgradeProfile { #[doc = "Id of upgrade profile."] #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[doc = "Name of upgrade profile."] #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[doc = "Type of upgrade profile."] #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[doc = "Control plane and agent pool upgrade profiles."] pub properties: ManagedClusterUpgradeProfileProperties, } impl ManagedClusterUpgradeProfile { pub fn new(properties: ManagedClusterUpgradeProfileProperties) -> Self { Self { id: None, name: None, type_: None, properties, } } } #[doc = "Control plane and agent pool upgrade profiles."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagedClusterUpgradeProfileProperties { #[doc = "The list of available upgrade versions."] #[serde(rename = "controlPlaneProfile")] pub control_plane_profile: ManagedClusterPoolUpgradeProfile, #[doc = "The list of available upgrade versions for agent pools."] #[serde(rename = "agentPoolProfiles")] pub agent_pool_profiles: Vec<ManagedClusterPoolUpgradeProfile>, } impl ManagedClusterUpgradeProfileProperties { pub fn new( control_plane_profile: ManagedClusterPoolUpgradeProfile, agent_pool_profiles: Vec<ManagedClusterPoolUpgradeProfile>, ) -> Self { Self { control_plane_profile, agent_pool_profiles, } } } #[doc = "Profile for Windows VMs in the container service cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagedClusterWindowsProfile { #[doc = "Specifies the name of the administrator account. <br><br> **restriction:** Cannot end in \".\" <br><br> **Disallowed values:** \"administrator\", \"admin\", \"user\", \"user1\", \"test\", \"user2\", \"test1\", \"user3\", \"admin1\", \"1\", \"123\", \"a\", \"actuser\", \"adm\", \"admin2\", \"aspnet\", \"backup\", \"console\", \"david\", \"guest\", \"john\", \"owner\", \"root\", \"server\", \"sql\", \"support\", \"support_388945a0\", \"sys\", \"test2\", \"test3\", \"user4\", \"user5\". <br><br> **Minimum-length:** 1 character <br><br> **Max-length:** 20 characters"] #[serde(rename = "adminUsername")] pub admin_username: String, #[doc = "Specifies the password of the administrator account. <br><br> **Minimum-length:** 8 characters <br><br> **Max-length:** 123 characters <br><br> **Complexity requirements:** 3 out of 4 conditions below need to be fulfilled <br> Has lower characters <br>Has upper characters <br> Has a digit <br> Has a special character (Regex match [\\W_]) <br><br> **Disallowed values:** \"abc@123\", \"P@$$w0rd\", \"P@ssw0rd\", \"P@ssword123\", \"Pa$$word\", \"pass@word1\", \"Password!\", \"Password1\", \"Password22\", \"iloveyou!\""] #[serde(rename = "adminPassword", default, skip_serializing_if = "Option::is_none")] pub admin_password: Option<String>, } impl ManagedClusterWindowsProfile { pub fn new(admin_username: String) -> Self { Self { admin_username, admin_password: None, } } } #[doc = "Represents the OpenShift networking configuration"] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct NetworkProfile { #[doc = "CIDR for the OpenShift Vnet."] #[serde(rename = "vnetCidr", default, skip_serializing_if = "Option::is_none")] pub vnet_cidr: Option<String>, #[doc = "CIDR of the Vnet to peer."] #[serde(rename = "peerVnetId", default, skip_serializing_if = "Option::is_none")] pub peer_vnet_id: Option<String>, #[doc = "ID of the Vnet created for OSA cluster."] #[serde(rename = "vnetId", default, skip_serializing_if = "Option::is_none")] pub vnet_id: Option<String>, } impl NetworkProfile { pub fn new() -> Self { Self::default() } } #[doc = "OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum OsType { Linux, Windows, } impl Default for OsType { fn default() -> Self { Self::Linux } } #[doc = "OpenShiftAgentPoolProfileRole represents the role of the AgentPoolProfile."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum OpenShiftAgentPoolProfileRole { #[serde(rename = "compute")] Compute, #[serde(rename = "infra")] Infra, } #[doc = "Size of OpenShift VMs."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum OpenShiftContainerServiceVmSize { #[serde(rename = "Standard_D2s_v3")] StandardD2sV3, #[serde(rename = "Standard_D4s_v3")] StandardD4sV3, #[serde(rename = "Standard_D8s_v3")] StandardD8sV3, #[serde(rename = "Standard_D16s_v3")] StandardD16sV3, #[serde(rename = "Standard_D32s_v3")] StandardD32sV3, #[serde(rename = "Standard_D64s_v3")] StandardD64sV3, #[serde(rename = "Standard_DS4_v2")] StandardDs4V2, #[serde(rename = "Standard_DS5_v2")] StandardDs5V2, #[serde(rename = "Standard_F8s_v2")] StandardF8sV2, #[serde(rename = "Standard_F16s_v2")] StandardF16sV2, #[serde(rename = "Standard_F32s_v2")] StandardF32sV2, #[serde(rename = "Standard_F64s_v2")] StandardF64sV2, #[serde(rename = "Standard_F72s_v2")] StandardF72sV2, #[serde(rename = "Standard_F8s")] StandardF8s, #[serde(rename = "Standard_F16s")] StandardF16s, #[serde(rename = "Standard_E4s_v3")] StandardE4sV3, #[serde(rename = "Standard_E8s_v3")] StandardE8sV3, #[serde(rename = "Standard_E16s_v3")] StandardE16sV3, #[serde(rename = "Standard_E20s_v3")] StandardE20sV3, #[serde(rename = "Standard_E32s_v3")] StandardE32sV3, #[serde(rename = "Standard_E64s_v3")] StandardE64sV3, #[serde(rename = "Standard_GS2")] StandardGs2, #[serde(rename = "Standard_GS3")] StandardGs3, #[serde(rename = "Standard_GS4")] StandardGs4, #[serde(rename = "Standard_GS5")] StandardGs5, #[serde(rename = "Standard_DS12_v2")] StandardDs12V2, #[serde(rename = "Standard_DS13_v2")] StandardDs13V2, #[serde(rename = "Standard_DS14_v2")] StandardDs14V2, #[serde(rename = "Standard_DS15_v2")] StandardDs15V2, #[serde(rename = "Standard_L4s")] StandardL4s, #[serde(rename = "Standard_L8s")] StandardL8s, #[serde(rename = "Standard_L16s")] StandardL16s, #[serde(rename = "Standard_L32s")] StandardL32s, } #[doc = "OpenShift Managed cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OpenShiftManagedCluster { #[serde(flatten)] pub resource: Resource, #[doc = "Used for establishing the purchase context of any 3rd Party artifact through MarketPlace."] #[serde(default, skip_serializing_if = "Option::is_none")] pub plan: Option<PurchasePlan>, #[doc = "Properties of the OpenShift managed cluster."] #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<OpenShiftManagedClusterProperties>, } impl OpenShiftManagedCluster { pub fn new(resource: Resource) -> Self { Self { resource, plan: None, properties: None, } } } #[doc = "Defines the Identity provider for MS AAD."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OpenShiftManagedClusterAadIdentityProvider { #[serde(flatten)] pub open_shift_managed_cluster_base_identity_provider: OpenShiftManagedClusterBaseIdentityProvider, #[doc = "The clientId password associated with the provider."] #[serde(rename = "clientId", default, skip_serializing_if = "Option::is_none")] pub client_id: Option<String>, #[doc = "The secret password associated with the provider."] #[serde(default, skip_serializing_if = "Option::is_none")] pub secret: Option<String>, #[doc = "The tenantId associated with the provider."] #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[doc = "The groupId to be granted cluster admin role."] #[serde(rename = "customerAdminGroupId", default, skip_serializing_if = "Option::is_none")] pub customer_admin_group_id: Option<String>, } impl OpenShiftManagedClusterAadIdentityProvider { pub fn new(open_shift_managed_cluster_base_identity_provider: OpenShiftManagedClusterBaseIdentityProvider) -> Self { Self { open_shift_managed_cluster_base_identity_provider, client_id: None, secret: None, tenant_id: None, customer_admin_group_id: None, } } } #[doc = "Defines the configuration of the OpenShift cluster VMs."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OpenShiftManagedClusterAgentPoolProfile { #[doc = "Unique name of the pool profile in the context of the subscription and resource group."] pub name: String, #[doc = "Number of agents (VMs) to host docker containers."] pub count: i32, #[doc = "Size of OpenShift VMs."] #[serde(rename = "vmSize")] pub vm_size: OpenShiftContainerServiceVmSize, #[doc = "Subnet CIDR for the peering."] #[serde(rename = "subnetCidr", default, skip_serializing_if = "Option::is_none")] pub subnet_cidr: Option<String>, #[doc = "OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux."] #[serde(rename = "osType", default, skip_serializing_if = "Option::is_none")] pub os_type: Option<OsType>, #[doc = "OpenShiftAgentPoolProfileRole represents the role of the AgentPoolProfile."] #[serde(default, skip_serializing_if = "Option::is_none")] pub role: Option<OpenShiftAgentPoolProfileRole>, } impl OpenShiftManagedClusterAgentPoolProfile { pub fn new(name: String, count: i32, vm_size: OpenShiftContainerServiceVmSize) -> Self { Self { name, count, vm_size, subnet_cidr: None, os_type: None, role: None, } } } #[doc = "Defines all possible authentication profiles for the OpenShift cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct OpenShiftManagedClusterAuthProfile { #[doc = "Type of authentication profile to use."] #[serde(rename = "identityProviders", default, skip_serializing_if = "Vec::is_empty")] pub identity_providers: Vec<OpenShiftManagedClusterIdentityProvider>, } impl OpenShiftManagedClusterAuthProfile { pub fn new() -> Self { Self::default() } } #[doc = "Structure for any Identity provider."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OpenShiftManagedClusterBaseIdentityProvider { #[doc = "The kind of the provider."] pub kind: String, } impl OpenShiftManagedClusterBaseIdentityProvider { pub fn new(kind: String) -> Self { Self { kind } } } #[doc = "Defines the configuration of the identity providers to be used in the OpenShift cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct OpenShiftManagedClusterIdentityProvider { #[doc = "Name of the provider."] #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[doc = "Structure for any Identity provider."] #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<OpenShiftManagedClusterBaseIdentityProvider>, } impl OpenShiftManagedClusterIdentityProvider { pub fn new() -> Self { Self::default() } } #[doc = "The response from the List OpenShift Managed Clusters operation."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct OpenShiftManagedClusterListResult { #[doc = "The list of OpenShift managed clusters."] #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<OpenShiftManagedCluster>, #[doc = "The URL to get the next set of OpenShift managed cluster results."] #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } impl OpenShiftManagedClusterListResult { pub fn new() -> Self { Self::default() } } #[doc = "OpenShiftManagedClusterMaterPoolProfile contains configuration for OpenShift master VMs."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OpenShiftManagedClusterMasterPoolProfile { #[doc = "Unique name of the master pool profile in the context of the subscription and resource group."] #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[doc = "Number of masters (VMs) to host docker containers. The default value is 3."] pub count: i32, #[doc = "Size of OpenShift VMs."] #[serde(rename = "vmSize")] pub vm_size: OpenShiftContainerServiceVmSize, #[doc = "Subnet CIDR for the peering."] #[serde(rename = "subnetCidr", default, skip_serializing_if = "Option::is_none")] pub subnet_cidr: Option<String>, #[doc = "OsType to be used to specify os type. Choose from Linux and Windows. Default to Linux."] #[serde(rename = "osType", default, skip_serializing_if = "Option::is_none")] pub os_type: Option<OsType>, } impl OpenShiftManagedClusterMasterPoolProfile { pub fn new(count: i32, vm_size: OpenShiftContainerServiceVmSize) -> Self { Self { name: None, count, vm_size, subnet_cidr: None, os_type: None, } } } #[doc = "Properties of the OpenShift managed cluster."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OpenShiftManagedClusterProperties { #[doc = "The current deployment or provisioning state, which only appears in the response."] #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[doc = "Version of OpenShift specified when creating the cluster."] #[serde(rename = "openShiftVersion")] pub open_shift_version: String, #[doc = "Version of OpenShift specified when creating the cluster."] #[serde(rename = "clusterVersion", default, skip_serializing_if = "Option::is_none")] pub cluster_version: Option<String>, #[doc = "Service generated FQDN for OpenShift API server."] #[serde(rename = "publicHostname", default, skip_serializing_if = "Option::is_none")] pub public_hostname: Option<String>, #[doc = "Service generated FQDN for OpenShift API server loadbalancer internal hostname."] #[serde(default, skip_serializing_if = "Option::is_none")] pub fqdn: Option<String>, #[doc = "Represents the OpenShift networking configuration"] #[serde(rename = "networkProfile", default, skip_serializing_if = "Option::is_none")] pub network_profile: Option<NetworkProfile>, #[doc = "Configuration for OpenShift router(s)."] #[serde(rename = "routerProfiles", default, skip_serializing_if = "Vec::is_empty")] pub router_profiles: Vec<OpenShiftRouterProfile>, #[doc = "OpenShiftManagedClusterMaterPoolProfile contains configuration for OpenShift master VMs."] #[serde(rename = "masterPoolProfile", default, skip_serializing_if = "Option::is_none")] pub master_pool_profile: Option<OpenShiftManagedClusterMasterPoolProfile>, #[doc = "Configuration of OpenShift cluster VMs."] #[serde(rename = "agentPoolProfiles", default, skip_serializing_if = "Vec::is_empty")] pub agent_pool_profiles: Vec<OpenShiftManagedClusterAgentPoolProfile>, #[doc = "Defines all possible authentication profiles for the OpenShift cluster."] #[serde(rename = "authProfile", default, skip_serializing_if = "Option::is_none")] pub auth_profile: Option<OpenShiftManagedClusterAuthProfile>, } impl OpenShiftManagedClusterProperties { pub fn new(open_shift_version: String) -> Self { Self { provisioning_state: None, open_shift_version, cluster_version: None, public_hostname: None, fqdn: None, network_profile: None, router_profiles: Vec::new(), master_pool_profile: None, agent_pool_profiles: Vec::new(), auth_profile: None, } } } #[doc = "Represents an OpenShift router"] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct OpenShiftRouterProfile { #[doc = "Name of the router profile."] #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[doc = "DNS subdomain for OpenShift router."] #[serde(rename = "publicSubdomain", default, skip_serializing_if = "Option::is_none")] pub public_subdomain: Option<String>, #[doc = "Auto-allocated FQDN for the OpenShift router."] #[serde(default, skip_serializing_if = "Option::is_none")] pub fqdn: Option<String>, } impl OpenShiftRouterProfile { pub fn new() -> Self { Self::default() } } #[doc = "The List Compute Operation operation response."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct OperationListResult { #[doc = "The list of compute operations"] #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<OperationValue>, } impl OperationListResult { pub fn new() -> Self { Self::default() } } #[doc = "Describes the properties of a Compute Operation value."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct OperationValue { #[doc = "The origin of the compute operation."] #[serde(default, skip_serializing_if = "Option::is_none")] pub origin: Option<String>, #[doc = "The name of the compute operation."] #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[doc = "Describes the properties of a Compute Operation Value Display."] #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<OperationValueDisplay>, } impl OperationValue { pub fn new() -> Self { Self::default() } } #[doc = "Describes the properties of a Compute Operation Value Display."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct OperationValueDisplay { #[doc = "The display name of the compute operation."] #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[doc = "The display name of the resource the operation applies to."] #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[doc = "The description of the operation."] #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[doc = "The resource provider for the operation."] #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, } impl OperationValueDisplay { pub fn new() -> Self { Self::default() } } #[doc = "Contains information about orchestrator."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OrchestratorProfile { #[doc = "Orchestrator type."] #[serde(rename = "orchestratorType", default, skip_serializing_if = "Option::is_none")] pub orchestrator_type: Option<String>, #[doc = "Orchestrator version (major, minor, patch)."] #[serde(rename = "orchestratorVersion")] pub orchestrator_version: String, #[doc = "Whether Kubernetes version is currently in preview."] #[serde(rename = "isPreview", default, skip_serializing_if = "Option::is_none")] pub is_preview: Option<bool>, } impl OrchestratorProfile { pub fn new(orchestrator_version: String) -> Self { Self { orchestrator_type: None, orchestrator_version, is_preview: None, } } } #[doc = "The profile of an orchestrator and its available versions."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OrchestratorVersionProfile { #[doc = "Orchestrator type."] #[serde(rename = "orchestratorType")] pub orchestrator_type: String, #[doc = "Orchestrator version (major, minor, patch)."] #[serde(rename = "orchestratorVersion")] pub orchestrator_version: String, #[doc = "Installed by default if version is not specified."] #[serde(default, skip_serializing_if = "Option::is_none")] pub default: Option<bool>, #[doc = "Whether Kubernetes version is currently in preview."] #[serde(rename = "isPreview", default, skip_serializing_if = "Option::is_none")] pub is_preview: Option<bool>, #[doc = "The list of available upgrade versions."] #[serde(default, skip_serializing_if = "Vec::is_empty")] pub upgrades: Vec<OrchestratorProfile>, } impl OrchestratorVersionProfile { pub fn new(orchestrator_type: String, orchestrator_version: String) -> Self { Self { orchestrator_type, orchestrator_version, default: None, is_preview: None, upgrades: Vec::new(), } } } #[doc = "The list of versions for supported orchestrators."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OrchestratorVersionProfileListResult { #[doc = "Id of the orchestrator version profile list result."] #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[doc = "Name of the orchestrator version profile list result."] #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[doc = "Type of the orchestrator version profile list result."] #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[doc = "The properties of an orchestrator version profile."] pub properties: OrchestratorVersionProfileProperties, } impl OrchestratorVersionProfileListResult { pub fn new(properties: OrchestratorVersionProfileProperties) -> Self { Self { id: None, name: None, type_: None, properties, } } } #[doc = "The properties of an orchestrator version profile."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OrchestratorVersionProfileProperties { #[doc = "List of orchestrator version profiles."] pub orchestrators: Vec<OrchestratorVersionProfile>, } impl OrchestratorVersionProfileProperties { pub fn new(orchestrators: Vec<OrchestratorVersionProfile>) -> Self { Self { orchestrators } } } #[doc = "Used for establishing the purchase context of any 3rd Party artifact through MarketPlace."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct PurchasePlan { #[doc = "The plan ID."] #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[doc = "Specifies the product of the image from the marketplace. This is the same value as Offer under the imageReference element."] #[serde(default, skip_serializing_if = "Option::is_none")] pub product: Option<String>, #[doc = "The promotion code."] #[serde(rename = "promotionCode", default, skip_serializing_if = "Option::is_none")] pub promotion_code: Option<String>, #[doc = "The plan ID."] #[serde(default, skip_serializing_if = "Option::is_none")] pub publisher: Option<String>, } impl PurchasePlan { pub fn new() -> Self { Self::default() } } #[doc = "The Resource model definition."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[doc = "Resource Id"] #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[doc = "Resource name"] #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[doc = "Resource type"] #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[doc = "Resource location"] pub location: String, #[doc = "Resource tags"] #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } impl Resource { pub fn new(location: String) -> Self { Self { id: None, name: None, type_: None, location, tags: None, } } } #[doc = "A reference to an Azure resource."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct ResourceReference { #[doc = "The fully qualified Azure resource id."] #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, } impl ResourceReference { pub fn new() -> Self { Self::default() } } #[doc = "ScaleSetEvictionPolicy to be used to specify eviction policy for Spot virtual machine scale set. Default to Delete."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ScaleSetEvictionPolicy { Delete, Deallocate, } impl Default for ScaleSetEvictionPolicy { fn default() -> Self { Self::Delete } } #[doc = "ScaleSetPriority to be used to specify virtual machine scale set priority. Default to regular."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ScaleSetPriority { Spot, Regular, } impl Default for ScaleSetPriority { fn default() -> Self { Self::Regular } } pub type SpotMaxPrice = f64; #[doc = "Reference to another subresource."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct SubResource { #[doc = "Resource ID."] #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[doc = "The name of the resource that is unique within a resource group. This name can be used to access the resource."] #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[doc = "Resource type"] #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } impl SubResource { pub fn new() -> Self { Self::default() } } #[doc = "Tags object for patch operations."] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct TagsObject { #[doc = "Resource tags."] #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } impl TagsObject { pub fn new() -> Self { Self::default() } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)] pub struct UserAssignedIdentity { #[doc = "The resource id of the user assigned identity."] #[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")] pub resource_id: Option<String>, #[doc = "The client id of the user assigned identity."] #[serde(rename = "clientId", default, skip_serializing_if = "Option::is_none")] pub client_id: Option<String>, #[doc = "The object id of the user assigned identity."] #[serde(rename = "objectId", default, skip_serializing_if = "Option::is_none")] pub object_id: Option<String>, } impl UserAssignedIdentity { pub fn new() -> Self { Self::default() } }
42.562932
583
0.683705
e65bcb8b593fed9ad9e8e7e0a0b313aa9cc966a9
39,945
// Generated from definition io.k8s.api.autoscaling.v1.Scale /// Scale represents a scaling request for a resource. #[derive(Clone, Debug, Default, PartialEq)] pub struct Scale { /// Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata. pub metadata: crate::apimachinery::pkg::apis::meta::v1::ObjectMeta, /// defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status. pub spec: Option<crate::api::autoscaling::v1::ScaleSpec>, /// current status of the scale. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#spec-and-status. Read-only. pub status: Option<crate::api::autoscaling::v1::ScaleStatus>, } // Begin autoscaling/v1/Scale // Generated from operation patchAppsV1NamespacedDeploymentScale impl Scale { /// partially update scale of the specified Deployment /// /// Use the returned [`crate::ResponseBody`]`<`[`crate::PatchResponse`]`<Self>>` constructor, or [`crate::PatchResponse`]`<Self>` directly, to parse the HTTP response. /// /// # Arguments /// /// * `name` /// /// name of the Scale /// /// * `namespace` /// /// object name and auth scope, such as for teams and projects /// /// * `body` /// /// * `optional` /// /// Optional parameters. Use `Default::default()` to not pass any. #[cfg(feature = "api")] pub fn patch_namespaced_deployment_scale( name: &str, namespace: &str, body: &crate::apimachinery::pkg::apis::meta::v1::Patch, optional: crate::PatchOptional<'_>, ) -> Result<(http::Request<Vec<u8>>, fn(http::StatusCode) -> crate::ResponseBody<crate::PatchResponse<Self>>), crate::RequestError> { let __url = format!("/apis/apps/v1/namespaces/{namespace}/deployments/{name}/scale?", name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), ); let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url); optional.__serialize(&mut __query_pairs); let __url = __query_pairs.finish(); let __request = http::Request::patch(__url); let __body = serde_json::to_vec(body).map_err(crate::RequestError::Json)?; let __request = __request.header(http::header::CONTENT_TYPE, http::header::HeaderValue::from_static(match body { crate::apimachinery::pkg::apis::meta::v1::Patch::Json(_) => "application/json-patch+json", crate::apimachinery::pkg::apis::meta::v1::Patch::Merge(_) => "application/merge-patch+json", crate::apimachinery::pkg::apis::meta::v1::Patch::StrategicMerge(_) => "application/strategic-merge-patch+json", })); match __request.body(__body) { Ok(request) => Ok((request, crate::ResponseBody::new)), Err(err) => Err(crate::RequestError::Http(err)), } } } // Generated from operation patchAppsV1NamespacedReplicaSetScale impl Scale { /// partially update scale of the specified ReplicaSet /// /// Use the returned [`crate::ResponseBody`]`<`[`crate::PatchResponse`]`<Self>>` constructor, or [`crate::PatchResponse`]`<Self>` directly, to parse the HTTP response. /// /// # Arguments /// /// * `name` /// /// name of the Scale /// /// * `namespace` /// /// object name and auth scope, such as for teams and projects /// /// * `body` /// /// * `optional` /// /// Optional parameters. Use `Default::default()` to not pass any. #[cfg(feature = "api")] pub fn patch_namespaced_replica_set_scale( name: &str, namespace: &str, body: &crate::apimachinery::pkg::apis::meta::v1::Patch, optional: crate::PatchOptional<'_>, ) -> Result<(http::Request<Vec<u8>>, fn(http::StatusCode) -> crate::ResponseBody<crate::PatchResponse<Self>>), crate::RequestError> { let __url = format!("/apis/apps/v1/namespaces/{namespace}/replicasets/{name}/scale?", name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), ); let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url); optional.__serialize(&mut __query_pairs); let __url = __query_pairs.finish(); let __request = http::Request::patch(__url); let __body = serde_json::to_vec(body).map_err(crate::RequestError::Json)?; let __request = __request.header(http::header::CONTENT_TYPE, http::header::HeaderValue::from_static(match body { crate::apimachinery::pkg::apis::meta::v1::Patch::Json(_) => "application/json-patch+json", crate::apimachinery::pkg::apis::meta::v1::Patch::Merge(_) => "application/merge-patch+json", crate::apimachinery::pkg::apis::meta::v1::Patch::StrategicMerge(_) => "application/strategic-merge-patch+json", })); match __request.body(__body) { Ok(request) => Ok((request, crate::ResponseBody::new)), Err(err) => Err(crate::RequestError::Http(err)), } } } // Generated from operation patchAppsV1NamespacedStatefulSetScale impl Scale { /// partially update scale of the specified StatefulSet /// /// Use the returned [`crate::ResponseBody`]`<`[`crate::PatchResponse`]`<Self>>` constructor, or [`crate::PatchResponse`]`<Self>` directly, to parse the HTTP response. /// /// # Arguments /// /// * `name` /// /// name of the Scale /// /// * `namespace` /// /// object name and auth scope, such as for teams and projects /// /// * `body` /// /// * `optional` /// /// Optional parameters. Use `Default::default()` to not pass any. #[cfg(feature = "api")] pub fn patch_namespaced_stateful_set_scale( name: &str, namespace: &str, body: &crate::apimachinery::pkg::apis::meta::v1::Patch, optional: crate::PatchOptional<'_>, ) -> Result<(http::Request<Vec<u8>>, fn(http::StatusCode) -> crate::ResponseBody<crate::PatchResponse<Self>>), crate::RequestError> { let __url = format!("/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}/scale?", name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), ); let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url); optional.__serialize(&mut __query_pairs); let __url = __query_pairs.finish(); let __request = http::Request::patch(__url); let __body = serde_json::to_vec(body).map_err(crate::RequestError::Json)?; let __request = __request.header(http::header::CONTENT_TYPE, http::header::HeaderValue::from_static(match body { crate::apimachinery::pkg::apis::meta::v1::Patch::Json(_) => "application/json-patch+json", crate::apimachinery::pkg::apis::meta::v1::Patch::Merge(_) => "application/merge-patch+json", crate::apimachinery::pkg::apis::meta::v1::Patch::StrategicMerge(_) => "application/strategic-merge-patch+json", })); match __request.body(__body) { Ok(request) => Ok((request, crate::ResponseBody::new)), Err(err) => Err(crate::RequestError::Http(err)), } } } // Generated from operation patchCoreV1NamespacedReplicationControllerScale impl Scale { /// partially update scale of the specified ReplicationController /// /// Use the returned [`crate::ResponseBody`]`<`[`crate::PatchResponse`]`<Self>>` constructor, or [`crate::PatchResponse`]`<Self>` directly, to parse the HTTP response. /// /// # Arguments /// /// * `name` /// /// name of the Scale /// /// * `namespace` /// /// object name and auth scope, such as for teams and projects /// /// * `body` /// /// * `optional` /// /// Optional parameters. Use `Default::default()` to not pass any. #[cfg(feature = "api")] pub fn patch_namespaced_replication_controller_scale( name: &str, namespace: &str, body: &crate::apimachinery::pkg::apis::meta::v1::Patch, optional: crate::PatchOptional<'_>, ) -> Result<(http::Request<Vec<u8>>, fn(http::StatusCode) -> crate::ResponseBody<crate::PatchResponse<Self>>), crate::RequestError> { let __url = format!("/api/v1/namespaces/{namespace}/replicationcontrollers/{name}/scale?", name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), ); let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url); optional.__serialize(&mut __query_pairs); let __url = __query_pairs.finish(); let __request = http::Request::patch(__url); let __body = serde_json::to_vec(body).map_err(crate::RequestError::Json)?; let __request = __request.header(http::header::CONTENT_TYPE, http::header::HeaderValue::from_static(match body { crate::apimachinery::pkg::apis::meta::v1::Patch::Json(_) => "application/json-patch+json", crate::apimachinery::pkg::apis::meta::v1::Patch::Merge(_) => "application/merge-patch+json", crate::apimachinery::pkg::apis::meta::v1::Patch::StrategicMerge(_) => "application/strategic-merge-patch+json", })); match __request.body(__body) { Ok(request) => Ok((request, crate::ResponseBody::new)), Err(err) => Err(crate::RequestError::Http(err)), } } } // Generated from operation readAppsV1NamespacedDeploymentScale impl Scale { /// read scale of the specified Deployment /// /// Use the returned [`crate::ResponseBody`]`<`[`ReadNamespacedDeploymentScaleResponse`]`>` constructor, or [`ReadNamespacedDeploymentScaleResponse`] directly, to parse the HTTP response. /// /// # Arguments /// /// * `name` /// /// name of the Scale /// /// * `namespace` /// /// object name and auth scope, such as for teams and projects /// /// * `optional` /// /// Optional parameters. Use `Default::default()` to not pass any. #[cfg(feature = "api")] pub fn read_namespaced_deployment_scale( name: &str, namespace: &str, optional: ReadNamespacedDeploymentScaleOptional<'_>, ) -> Result<(http::Request<Vec<u8>>, fn(http::StatusCode) -> crate::ResponseBody<ReadNamespacedDeploymentScaleResponse>), crate::RequestError> { let ReadNamespacedDeploymentScaleOptional { pretty, } = optional; let __url = format!("/apis/apps/v1/namespaces/{namespace}/deployments/{name}/scale?", name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), ); let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url); if let Some(pretty) = pretty { __query_pairs.append_pair("pretty", pretty); } let __url = __query_pairs.finish(); let __request = http::Request::get(__url); let __body = vec![]; match __request.body(__body) { Ok(request) => Ok((request, crate::ResponseBody::new)), Err(err) => Err(crate::RequestError::Http(err)), } } } /// Optional parameters of [`Scale::read_namespaced_deployment_scale`] #[cfg(feature = "api")] #[derive(Clone, Copy, Debug, Default)] pub struct ReadNamespacedDeploymentScaleOptional<'a> { /// If 'true', then the output is pretty printed. pub pretty: Option<&'a str>, } /// Use `<ReadNamespacedDeploymentScaleResponse as Response>::try_from_parts` to parse the HTTP response body of [`Scale::read_namespaced_deployment_scale`] #[cfg(feature = "api")] #[derive(Debug)] pub enum ReadNamespacedDeploymentScaleResponse { Ok(crate::api::autoscaling::v1::Scale), Other(Result<Option<serde_json::Value>, serde_json::Error>), } #[cfg(feature = "api")] impl crate::Response for ReadNamespacedDeploymentScaleResponse { fn try_from_parts(status_code: http::StatusCode, buf: &[u8]) -> Result<(Self, usize), crate::ResponseError> { match status_code { http::StatusCode::OK => { let result = match serde_json::from_slice(buf) { Ok(value) => value, Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData), Err(err) => return Err(crate::ResponseError::Json(err)), }; Ok((ReadNamespacedDeploymentScaleResponse::Ok(result), buf.len())) }, _ => { let (result, read) = if buf.is_empty() { (Ok(None), 0) } else { match serde_json::from_slice(buf) { Ok(value) => (Ok(Some(value)), buf.len()), Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData), Err(err) => (Err(err), 0), } }; Ok((ReadNamespacedDeploymentScaleResponse::Other(result), read)) }, } } } // Generated from operation readAppsV1NamespacedReplicaSetScale impl Scale { /// read scale of the specified ReplicaSet /// /// Use the returned [`crate::ResponseBody`]`<`[`ReadNamespacedReplicaSetScaleResponse`]`>` constructor, or [`ReadNamespacedReplicaSetScaleResponse`] directly, to parse the HTTP response. /// /// # Arguments /// /// * `name` /// /// name of the Scale /// /// * `namespace` /// /// object name and auth scope, such as for teams and projects /// /// * `optional` /// /// Optional parameters. Use `Default::default()` to not pass any. #[cfg(feature = "api")] pub fn read_namespaced_replica_set_scale( name: &str, namespace: &str, optional: ReadNamespacedReplicaSetScaleOptional<'_>, ) -> Result<(http::Request<Vec<u8>>, fn(http::StatusCode) -> crate::ResponseBody<ReadNamespacedReplicaSetScaleResponse>), crate::RequestError> { let ReadNamespacedReplicaSetScaleOptional { pretty, } = optional; let __url = format!("/apis/apps/v1/namespaces/{namespace}/replicasets/{name}/scale?", name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), ); let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url); if let Some(pretty) = pretty { __query_pairs.append_pair("pretty", pretty); } let __url = __query_pairs.finish(); let __request = http::Request::get(__url); let __body = vec![]; match __request.body(__body) { Ok(request) => Ok((request, crate::ResponseBody::new)), Err(err) => Err(crate::RequestError::Http(err)), } } } /// Optional parameters of [`Scale::read_namespaced_replica_set_scale`] #[cfg(feature = "api")] #[derive(Clone, Copy, Debug, Default)] pub struct ReadNamespacedReplicaSetScaleOptional<'a> { /// If 'true', then the output is pretty printed. pub pretty: Option<&'a str>, } /// Use `<ReadNamespacedReplicaSetScaleResponse as Response>::try_from_parts` to parse the HTTP response body of [`Scale::read_namespaced_replica_set_scale`] #[cfg(feature = "api")] #[derive(Debug)] pub enum ReadNamespacedReplicaSetScaleResponse { Ok(crate::api::autoscaling::v1::Scale), Other(Result<Option<serde_json::Value>, serde_json::Error>), } #[cfg(feature = "api")] impl crate::Response for ReadNamespacedReplicaSetScaleResponse { fn try_from_parts(status_code: http::StatusCode, buf: &[u8]) -> Result<(Self, usize), crate::ResponseError> { match status_code { http::StatusCode::OK => { let result = match serde_json::from_slice(buf) { Ok(value) => value, Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData), Err(err) => return Err(crate::ResponseError::Json(err)), }; Ok((ReadNamespacedReplicaSetScaleResponse::Ok(result), buf.len())) }, _ => { let (result, read) = if buf.is_empty() { (Ok(None), 0) } else { match serde_json::from_slice(buf) { Ok(value) => (Ok(Some(value)), buf.len()), Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData), Err(err) => (Err(err), 0), } }; Ok((ReadNamespacedReplicaSetScaleResponse::Other(result), read)) }, } } } // Generated from operation readAppsV1NamespacedStatefulSetScale impl Scale { /// read scale of the specified StatefulSet /// /// Use the returned [`crate::ResponseBody`]`<`[`ReadNamespacedStatefulSetScaleResponse`]`>` constructor, or [`ReadNamespacedStatefulSetScaleResponse`] directly, to parse the HTTP response. /// /// # Arguments /// /// * `name` /// /// name of the Scale /// /// * `namespace` /// /// object name and auth scope, such as for teams and projects /// /// * `optional` /// /// Optional parameters. Use `Default::default()` to not pass any. #[cfg(feature = "api")] pub fn read_namespaced_stateful_set_scale( name: &str, namespace: &str, optional: ReadNamespacedStatefulSetScaleOptional<'_>, ) -> Result<(http::Request<Vec<u8>>, fn(http::StatusCode) -> crate::ResponseBody<ReadNamespacedStatefulSetScaleResponse>), crate::RequestError> { let ReadNamespacedStatefulSetScaleOptional { pretty, } = optional; let __url = format!("/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}/scale?", name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), ); let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url); if let Some(pretty) = pretty { __query_pairs.append_pair("pretty", pretty); } let __url = __query_pairs.finish(); let __request = http::Request::get(__url); let __body = vec![]; match __request.body(__body) { Ok(request) => Ok((request, crate::ResponseBody::new)), Err(err) => Err(crate::RequestError::Http(err)), } } } /// Optional parameters of [`Scale::read_namespaced_stateful_set_scale`] #[cfg(feature = "api")] #[derive(Clone, Copy, Debug, Default)] pub struct ReadNamespacedStatefulSetScaleOptional<'a> { /// If 'true', then the output is pretty printed. pub pretty: Option<&'a str>, } /// Use `<ReadNamespacedStatefulSetScaleResponse as Response>::try_from_parts` to parse the HTTP response body of [`Scale::read_namespaced_stateful_set_scale`] #[cfg(feature = "api")] #[derive(Debug)] pub enum ReadNamespacedStatefulSetScaleResponse { Ok(crate::api::autoscaling::v1::Scale), Other(Result<Option<serde_json::Value>, serde_json::Error>), } #[cfg(feature = "api")] impl crate::Response for ReadNamespacedStatefulSetScaleResponse { fn try_from_parts(status_code: http::StatusCode, buf: &[u8]) -> Result<(Self, usize), crate::ResponseError> { match status_code { http::StatusCode::OK => { let result = match serde_json::from_slice(buf) { Ok(value) => value, Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData), Err(err) => return Err(crate::ResponseError::Json(err)), }; Ok((ReadNamespacedStatefulSetScaleResponse::Ok(result), buf.len())) }, _ => { let (result, read) = if buf.is_empty() { (Ok(None), 0) } else { match serde_json::from_slice(buf) { Ok(value) => (Ok(Some(value)), buf.len()), Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData), Err(err) => (Err(err), 0), } }; Ok((ReadNamespacedStatefulSetScaleResponse::Other(result), read)) }, } } } // Generated from operation readCoreV1NamespacedReplicationControllerScale impl Scale { /// read scale of the specified ReplicationController /// /// Use the returned [`crate::ResponseBody`]`<`[`ReadNamespacedReplicationControllerScaleResponse`]`>` constructor, or [`ReadNamespacedReplicationControllerScaleResponse`] directly, to parse the HTTP response. /// /// # Arguments /// /// * `name` /// /// name of the Scale /// /// * `namespace` /// /// object name and auth scope, such as for teams and projects /// /// * `optional` /// /// Optional parameters. Use `Default::default()` to not pass any. #[cfg(feature = "api")] pub fn read_namespaced_replication_controller_scale( name: &str, namespace: &str, optional: ReadNamespacedReplicationControllerScaleOptional<'_>, ) -> Result<(http::Request<Vec<u8>>, fn(http::StatusCode) -> crate::ResponseBody<ReadNamespacedReplicationControllerScaleResponse>), crate::RequestError> { let ReadNamespacedReplicationControllerScaleOptional { pretty, } = optional; let __url = format!("/api/v1/namespaces/{namespace}/replicationcontrollers/{name}/scale?", name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), ); let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url); if let Some(pretty) = pretty { __query_pairs.append_pair("pretty", pretty); } let __url = __query_pairs.finish(); let __request = http::Request::get(__url); let __body = vec![]; match __request.body(__body) { Ok(request) => Ok((request, crate::ResponseBody::new)), Err(err) => Err(crate::RequestError::Http(err)), } } } /// Optional parameters of [`Scale::read_namespaced_replication_controller_scale`] #[cfg(feature = "api")] #[derive(Clone, Copy, Debug, Default)] pub struct ReadNamespacedReplicationControllerScaleOptional<'a> { /// If 'true', then the output is pretty printed. pub pretty: Option<&'a str>, } /// Use `<ReadNamespacedReplicationControllerScaleResponse as Response>::try_from_parts` to parse the HTTP response body of [`Scale::read_namespaced_replication_controller_scale`] #[cfg(feature = "api")] #[derive(Debug)] pub enum ReadNamespacedReplicationControllerScaleResponse { Ok(crate::api::autoscaling::v1::Scale), Other(Result<Option<serde_json::Value>, serde_json::Error>), } #[cfg(feature = "api")] impl crate::Response for ReadNamespacedReplicationControllerScaleResponse { fn try_from_parts(status_code: http::StatusCode, buf: &[u8]) -> Result<(Self, usize), crate::ResponseError> { match status_code { http::StatusCode::OK => { let result = match serde_json::from_slice(buf) { Ok(value) => value, Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData), Err(err) => return Err(crate::ResponseError::Json(err)), }; Ok((ReadNamespacedReplicationControllerScaleResponse::Ok(result), buf.len())) }, _ => { let (result, read) = if buf.is_empty() { (Ok(None), 0) } else { match serde_json::from_slice(buf) { Ok(value) => (Ok(Some(value)), buf.len()), Err(ref err) if err.is_eof() => return Err(crate::ResponseError::NeedMoreData), Err(err) => (Err(err), 0), } }; Ok((ReadNamespacedReplicationControllerScaleResponse::Other(result), read)) }, } } } // Generated from operation replaceAppsV1NamespacedDeploymentScale impl Scale { /// replace scale of the specified Deployment /// /// Use the returned [`crate::ResponseBody`]`<`[`crate::ReplaceResponse`]`<Self>>` constructor, or [`crate::ReplaceResponse`]`<Self>` directly, to parse the HTTP response. /// /// # Arguments /// /// * `name` /// /// name of the Scale /// /// * `namespace` /// /// object name and auth scope, such as for teams and projects /// /// * `body` /// /// * `optional` /// /// Optional parameters. Use `Default::default()` to not pass any. #[cfg(feature = "api")] pub fn replace_namespaced_deployment_scale( name: &str, namespace: &str, body: &crate::api::autoscaling::v1::Scale, optional: crate::ReplaceOptional<'_>, ) -> Result<(http::Request<Vec<u8>>, fn(http::StatusCode) -> crate::ResponseBody<crate::ReplaceResponse<Self>>), crate::RequestError> { let __url = format!("/apis/apps/v1/namespaces/{namespace}/deployments/{name}/scale?", name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), ); let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url); optional.__serialize(&mut __query_pairs); let __url = __query_pairs.finish(); let __request = http::Request::put(__url); let __body = serde_json::to_vec(body).map_err(crate::RequestError::Json)?; let __request = __request.header(http::header::CONTENT_TYPE, http::header::HeaderValue::from_static("application/json")); match __request.body(__body) { Ok(request) => Ok((request, crate::ResponseBody::new)), Err(err) => Err(crate::RequestError::Http(err)), } } } // Generated from operation replaceAppsV1NamespacedReplicaSetScale impl Scale { /// replace scale of the specified ReplicaSet /// /// Use the returned [`crate::ResponseBody`]`<`[`crate::ReplaceResponse`]`<Self>>` constructor, or [`crate::ReplaceResponse`]`<Self>` directly, to parse the HTTP response. /// /// # Arguments /// /// * `name` /// /// name of the Scale /// /// * `namespace` /// /// object name and auth scope, such as for teams and projects /// /// * `body` /// /// * `optional` /// /// Optional parameters. Use `Default::default()` to not pass any. #[cfg(feature = "api")] pub fn replace_namespaced_replica_set_scale( name: &str, namespace: &str, body: &crate::api::autoscaling::v1::Scale, optional: crate::ReplaceOptional<'_>, ) -> Result<(http::Request<Vec<u8>>, fn(http::StatusCode) -> crate::ResponseBody<crate::ReplaceResponse<Self>>), crate::RequestError> { let __url = format!("/apis/apps/v1/namespaces/{namespace}/replicasets/{name}/scale?", name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), ); let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url); optional.__serialize(&mut __query_pairs); let __url = __query_pairs.finish(); let __request = http::Request::put(__url); let __body = serde_json::to_vec(body).map_err(crate::RequestError::Json)?; let __request = __request.header(http::header::CONTENT_TYPE, http::header::HeaderValue::from_static("application/json")); match __request.body(__body) { Ok(request) => Ok((request, crate::ResponseBody::new)), Err(err) => Err(crate::RequestError::Http(err)), } } } // Generated from operation replaceAppsV1NamespacedStatefulSetScale impl Scale { /// replace scale of the specified StatefulSet /// /// Use the returned [`crate::ResponseBody`]`<`[`crate::ReplaceResponse`]`<Self>>` constructor, or [`crate::ReplaceResponse`]`<Self>` directly, to parse the HTTP response. /// /// # Arguments /// /// * `name` /// /// name of the Scale /// /// * `namespace` /// /// object name and auth scope, such as for teams and projects /// /// * `body` /// /// * `optional` /// /// Optional parameters. Use `Default::default()` to not pass any. #[cfg(feature = "api")] pub fn replace_namespaced_stateful_set_scale( name: &str, namespace: &str, body: &crate::api::autoscaling::v1::Scale, optional: crate::ReplaceOptional<'_>, ) -> Result<(http::Request<Vec<u8>>, fn(http::StatusCode) -> crate::ResponseBody<crate::ReplaceResponse<Self>>), crate::RequestError> { let __url = format!("/apis/apps/v1/namespaces/{namespace}/statefulsets/{name}/scale?", name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), ); let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url); optional.__serialize(&mut __query_pairs); let __url = __query_pairs.finish(); let __request = http::Request::put(__url); let __body = serde_json::to_vec(body).map_err(crate::RequestError::Json)?; let __request = __request.header(http::header::CONTENT_TYPE, http::header::HeaderValue::from_static("application/json")); match __request.body(__body) { Ok(request) => Ok((request, crate::ResponseBody::new)), Err(err) => Err(crate::RequestError::Http(err)), } } } // Generated from operation replaceCoreV1NamespacedReplicationControllerScale impl Scale { /// replace scale of the specified ReplicationController /// /// Use the returned [`crate::ResponseBody`]`<`[`crate::ReplaceResponse`]`<Self>>` constructor, or [`crate::ReplaceResponse`]`<Self>` directly, to parse the HTTP response. /// /// # Arguments /// /// * `name` /// /// name of the Scale /// /// * `namespace` /// /// object name and auth scope, such as for teams and projects /// /// * `body` /// /// * `optional` /// /// Optional parameters. Use `Default::default()` to not pass any. #[cfg(feature = "api")] pub fn replace_namespaced_replication_controller_scale( name: &str, namespace: &str, body: &crate::api::autoscaling::v1::Scale, optional: crate::ReplaceOptional<'_>, ) -> Result<(http::Request<Vec<u8>>, fn(http::StatusCode) -> crate::ResponseBody<crate::ReplaceResponse<Self>>), crate::RequestError> { let __url = format!("/api/v1/namespaces/{namespace}/replicationcontrollers/{name}/scale?", name = crate::percent_encoding::percent_encode(name.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), namespace = crate::percent_encoding::percent_encode(namespace.as_bytes(), crate::percent_encoding2::PATH_SEGMENT_ENCODE_SET), ); let mut __query_pairs = crate::url::form_urlencoded::Serializer::new(__url); optional.__serialize(&mut __query_pairs); let __url = __query_pairs.finish(); let __request = http::Request::put(__url); let __body = serde_json::to_vec(body).map_err(crate::RequestError::Json)?; let __request = __request.header(http::header::CONTENT_TYPE, http::header::HeaderValue::from_static("application/json")); match __request.body(__body) { Ok(request) => Ok((request, crate::ResponseBody::new)), Err(err) => Err(crate::RequestError::Http(err)), } } } // End autoscaling/v1/Scale impl crate::Resource for Scale { const API_VERSION: &'static str = "autoscaling/v1"; const GROUP: &'static str = "autoscaling"; const KIND: &'static str = "Scale"; const VERSION: &'static str = "v1"; } impl crate::Metadata for Scale { type Ty = crate::apimachinery::pkg::apis::meta::v1::ObjectMeta; fn metadata(&self) -> &<Self as crate::Metadata>::Ty { &self.metadata } fn metadata_mut(&mut self) -> &mut<Self as crate::Metadata>::Ty { &mut self.metadata } } impl<'de> serde::Deserialize<'de> for Scale { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { #[allow(non_camel_case_types)] enum Field { Key_api_version, Key_kind, Key_metadata, Key_spec, Key_status, Other, } impl<'de> serde::Deserialize<'de> for Field { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = Field; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("field identifier") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error { Ok(match v { "apiVersion" => Field::Key_api_version, "kind" => Field::Key_kind, "metadata" => Field::Key_metadata, "spec" => Field::Key_spec, "status" => Field::Key_status, _ => Field::Other, }) } } deserializer.deserialize_identifier(Visitor) } } struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = Scale; fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(<Self::Value as crate::Resource>::KIND) } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> { let mut value_metadata: Option<crate::apimachinery::pkg::apis::meta::v1::ObjectMeta> = None; let mut value_spec: Option<crate::api::autoscaling::v1::ScaleSpec> = None; let mut value_status: Option<crate::api::autoscaling::v1::ScaleStatus> = None; while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? { match key { Field::Key_api_version => { let value_api_version: String = serde::de::MapAccess::next_value(&mut map)?; if value_api_version != <Self::Value as crate::Resource>::API_VERSION { return Err(serde::de::Error::invalid_value(serde::de::Unexpected::Str(&value_api_version), &<Self::Value as crate::Resource>::API_VERSION)); } }, Field::Key_kind => { let value_kind: String = serde::de::MapAccess::next_value(&mut map)?; if value_kind != <Self::Value as crate::Resource>::KIND { return Err(serde::de::Error::invalid_value(serde::de::Unexpected::Str(&value_kind), &<Self::Value as crate::Resource>::KIND)); } }, Field::Key_metadata => value_metadata = Some(serde::de::MapAccess::next_value(&mut map)?), Field::Key_spec => value_spec = serde::de::MapAccess::next_value(&mut map)?, Field::Key_status => value_status = serde::de::MapAccess::next_value(&mut map)?, Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; }, } } Ok(Scale { metadata: value_metadata.ok_or_else(|| serde::de::Error::missing_field("metadata"))?, spec: value_spec, status: value_status, }) } } deserializer.deserialize_struct( <Self as crate::Resource>::KIND, &[ "apiVersion", "kind", "metadata", "spec", "status", ], Visitor, ) } } impl serde::Serialize for Scale { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer { let mut state = serializer.serialize_struct( <Self as crate::Resource>::KIND, 3 + self.spec.as_ref().map_or(0, |_| 1) + self.status.as_ref().map_or(0, |_| 1), )?; serde::ser::SerializeStruct::serialize_field(&mut state, "apiVersion", <Self as crate::Resource>::API_VERSION)?; serde::ser::SerializeStruct::serialize_field(&mut state, "kind", <Self as crate::Resource>::KIND)?; serde::ser::SerializeStruct::serialize_field(&mut state, "metadata", &self.metadata)?; if let Some(value) = &self.spec { serde::ser::SerializeStruct::serialize_field(&mut state, "spec", value)?; } if let Some(value) = &self.status { serde::ser::SerializeStruct::serialize_field(&mut state, "status", value)?; } serde::ser::SerializeStruct::end(state) } }
43.277356
213
0.598223
08a58bdffc0db618bbb99a201b22f435efc4f294
85
// pub mod hosting { // pub fn add_to_waitlist() {} // } pub mod hosting;
14.166667
35
0.541176
f7d91f01066ec842c0221f28d7e0b028f3ed6174
14,626
// < begin copyright > // Copyright Ryan Marcus 2020 // // See root directory of this project for license terms. // // < end copyright > #![allow(clippy::needless_return)] #[macro_use] mod load; use load::{load_data, DataType}; use rmi_lib::{train, train_bounded}; use rmi_lib::KeyType; use rmi_lib::optimizer; use json::*; use log::*; use std::f64; use std::fs::File; use std::io::BufWriter; use std::fs; use std::path::Path; use rayon::prelude::*; use indicatif::{ProgressBar, ProgressStyle}; use clap::{App, Arg}; fn main() { env_logger::init(); let matches = App::new("RMI Learner") .version("0.1") .author("Ryan Marcus <[email protected]>") .about("Learns recursive model indexes") .arg(Arg::with_name("input") .help("Path to input file containing data") .index(1).required(true)) .arg(Arg::with_name("namespace") .help("Namespace to use in generated code") .index(2).required(false)) .arg(Arg::with_name("models") .help("Comma-separated list of model layers, e.g. linear,linear") .index(3).required(false)) .arg(Arg::with_name("branching factor") .help("Branching factor between each model level") .index(4).required(false)) .arg(Arg::with_name("no-code") .long("no-code") .help("Skip code generation")) .arg(Arg::with_name("dump-ll-model-data") .long("dump-ll-model-data") .value_name("model_index") .help("dump the data used to train the last-level model at index")) .arg(Arg::with_name("dump-ll-errors") .long("dump-ll-errors") .help("dump the errors of each last-level model to ll_errors.json")) .arg(Arg::with_name("stats-file") .long("stats-file") .short("s") .value_name("file") .help("dump statistics about the learned model into the specified file")) .arg(Arg::with_name("param-grid") .long("param-grid") .value_name("file") .help("train the RMIs specified in the JSON file and report their errors")) .arg(Arg::with_name("data-path") .long("data-path") .short("d") .value_name("dir") .help("exports parameters to files in this directory (default: rmi_data)")) .arg(Arg::with_name("no-errors") .long("no-errors") .help("do not save last-level errors, and modify the RMI function signature")) .arg(Arg::with_name("threads") .long("threads") .short("t") .value_name("count") .help("number of threads to use for optimization, default = 4")) .arg(Arg::with_name("bounded") .long("bounded") .value_name("line_size") .help("construct an error-bounded RMI using the cachefix method for the given line size")) .arg(Arg::with_name("max-size") .long("max-size") .value_name("BYTES") .help("uses the optimizer fo find an RMI with a size less than specified")) .arg(Arg::with_name("disable-parallel-training") .long("disable-parallel-training") .help("disables training multiple RMIs in parallel")) .arg(Arg::with_name("zero-build-time") .long("zero-build-time") .help("zero out the model build time field")) .arg(Arg::with_name("optimize") .long("optimize") .value_name("file") .help("Search for Pareto efficient RMI configurations. Specify the name of the output file.")) .get_matches(); // set the max number of threads to 4 by default, otherwise Rayon goes // crazy on larger machines and allocates too many workers for folds / reduces let num_threads = matches.value_of("threads") .map(|x| x.parse::<usize>().unwrap()) .unwrap_or(4); rayon::ThreadPoolBuilder::new().num_threads(num_threads).build_global().unwrap(); let fp = matches.value_of("input").unwrap(); let data_dir = matches.value_of("data-path").unwrap_or("rmi_data"); if matches.value_of("namespace").is_some() && matches.value_of("param-grid").is_some() { panic!("Can only specify one of namespace or param-grid"); } info!("Reading {}...", fp); let mut key_type = KeyType::U64; let (num_rows, data) = if fp.contains("uint64") { load_data(&fp, DataType::UINT64) } else if fp.contains("uint32") { key_type = KeyType::U32; load_data(&fp, DataType::UINT32) } else if fp.contains("uint128") { key_type = KeyType::U128; load_data(&fp, DataType::UINT128) } else if fp.contains("uint512") { key_type = KeyType::U512; load_data(&fp, DataType::UINT512) }else if fp.contains("f64") { key_type = KeyType::F64; load_data(&fp, DataType::FLOAT64) } else { panic!("Data file must contain uint64, uint32, uint128, uint512, or f64."); }; if matches.is_present("optimize") { let results = dynamic!(optimizer::find_pareto_efficient_configs, data, 10); optimizer::RMIStatistics::display_table(&results); let nmspc_prefix = if matches.value_of("namespace").is_some() { matches.value_of("namespace").unwrap() } else { let path = Path::new(fp); path.file_name().map(|s| s.to_str()).unwrap_or(Some("rmi")).unwrap() }; let grid_specs: Vec<JsonValue> = results.into_iter() .enumerate() .map(|(idx, v)| { let nmspc = format!("{}_{}", nmspc_prefix, idx); v.to_grid_spec(&nmspc) }).collect(); let grid_specs_json = object!("configs" => grid_specs); let fp = matches.value_of("optimize").unwrap(); let f = File::create(fp) .expect("Could not write optimization results file"); let mut bw = BufWriter::new(f); grid_specs_json.write(&mut bw).unwrap(); return; } // if we aren't optimizing, we should make sure the RMI data directory exists. if !Path::new(data_dir).exists() { info!("The RMI data directory specified {} does not exist. Creating it.", data_dir); std::fs::create_dir_all(data_dir) .expect("The RMI data directory did not exist, and it could not be created."); } if let Some(param_grid) = matches.value_of("param-grid").map(|x| x.to_string()) { let pg = { let raw_json = fs::read_to_string(param_grid.clone()).unwrap(); let mut as_json = json::parse(raw_json.as_str()).unwrap(); as_json["configs"].take() }; let mut to_test = Vec::new(); if let JsonValue::Array(v) = pg { for el in v { let layers = String::from(el["layers"].as_str().unwrap()); let branching = el["branching factor"].as_u64().unwrap(); let namespace = match el["namespace"].as_str() { Some(s) => Some(String::from(s)), None => None }; to_test.push((layers, branching, namespace)); } trace!("# RMIs to train: {}", to_test.len()); let pbar = ProgressBar::new(to_test.len() as u64); pbar.set_style(ProgressStyle::default_bar() .template("{pos} / {len} ({msg}) {wide_bar} {eta}")); let train_func = |(models, branch_factor, namespace): &(String, u64, Option<String>)| { trace!("Training RMI {} with branching factor {}", models, *branch_factor); let loc_data = data.soft_copy(); let mut trained_model = dynamic!(train, loc_data, models, *branch_factor); let size_bs = rmi_lib::rmi_size(&trained_model); let result_obj = object! { "layers" => models.clone(), "branching factor" => *branch_factor, "average error" => trained_model.model_avg_error as f64, "average error %" => trained_model.model_max_error as f64 / num_rows as f64 * 100.0, "average l2 error" => trained_model.model_avg_l2_error as f64, "average log2 error" => trained_model.model_avg_log2_error, "max error" => trained_model.model_max_error, "max error %" => trained_model.model_max_error as f64 / num_rows as f64 * 100.0, "max log2 error" => trained_model.model_max_log2_error, "size binary search" => size_bs, "namespace" => namespace.clone() }; if matches.is_present("zero-build-time") { trained_model.build_time = 0; } if let Some(nmspc) = namespace { rmi_lib::output_rmi( &nmspc, trained_model, data_dir, key_type, true).unwrap(); } pbar.inc(1); return result_obj; }; let results: Vec<JsonValue> = if matches.is_present("disable-parallel-training") { trace!("Training models sequentially"); to_test.iter().map(train_func).collect() } else { trace!("Training models in parallel"); to_test.par_iter().map(train_func).collect() }; //let results: Vec<JsonValue> = to_test //.par_iter().map( pbar.finish(); let f = File::create(format!("{}_results", param_grid)).expect("Could not write results file"); let mut bw = BufWriter::new(f); let json_results = object! { "results" => results }; json_results.write(&mut bw).unwrap(); } else { panic!("Configs must have an array as its value"); } } else if matches.value_of("namespace").is_some() { let namespace = matches.value_of("namespace").unwrap().to_string(); let mut trained_model = match matches.value_of("max-size") { None => { // assume they gave a model spec let models = matches.value_of("models").unwrap(); let branch_factor = matches .value_of("branching factor") .unwrap() .parse::<u64>() .unwrap(); let trained_model = match matches.value_of("bounded") { None => dynamic!(train, data, models, branch_factor), Some(s) => { let line_size = s.parse::<usize>() .expect("Line size must be a positive integer."); let d_u64 = data.into_u64() .expect("Can only construct a bounded RMI on u64 data."); train_bounded(&d_u64, models, branch_factor, line_size) } }; trained_model } Some(max_size_str) => { let max_size = max_size_str.parse::<usize>().unwrap(); info!("Constructing RMI with size less than {}", max_size); let trained_model = dynamic!(rmi_lib::train_for_size, data, max_size); trained_model } }; let no_errors = matches.is_present("no-errors"); info!("Model build time: {} ms", trained_model.build_time / 1_000_000); info!( "Average model error: {} ({}%)", trained_model.model_avg_error as f64, trained_model.model_avg_error / num_rows as f64 * 100.0 ); info!( "Average model L2 error: {}", trained_model.model_avg_l2_error ); info!( "Average model log2 error: {}", trained_model.model_avg_log2_error ); info!( "Max model log2 error: {}", trained_model.model_max_log2_error ); info!( "Max model error on model {}: {} ({}%)", trained_model.model_max_error_idx, trained_model.model_max_error, trained_model.model_max_error as f64 / num_rows as f64 * 100.0 ); if true { println!("Model build time: {} ms", trained_model.build_time / 1_000_000); println!( "Average model error: {} ({}%)", trained_model.model_avg_error as f64, trained_model.model_avg_error / num_rows as f64 * 100.0 ); println!( "Average model L2 error: {}", trained_model.model_avg_l2_error ); println!( "Average model log2 error: {}", trained_model.model_avg_log2_error ); println!( "Max model log2 error: {}", trained_model.model_max_log2_error ); println!( "Max model error on model {}: {} ({}%)", trained_model.model_max_error_idx, trained_model.model_max_error, trained_model.model_max_error as f64 / num_rows as f64 * 100.0 ); } if !matches.is_present("no-code") { if matches.is_present("zero-build-time") { trained_model.build_time = 0; } rmi_lib::output_rmi( &namespace, trained_model, data_dir, key_type, !no_errors).unwrap(); } else { trace!("Skipping code generation due to CLI flag"); } } else { trace!("Must specify either a name space or a parameter grid."); } }
38.795756
107
0.51511
0ac9266c0d95669826f03f77962e581866c3ffa1
1,070
/* * Ory APIs * * Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. * * The version of the OpenAPI document: v0.0.1-alpha.187 * Contact: [email protected] * Generated by: https://openapi-generator.tech */ #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "method")] pub enum SubmitSelfServiceRecoveryFlowBody { #[serde(rename="link")] SubmitSelfServiceRecoveryFlowWithLinkMethodBody { /// Sending the anti-csrf token is only required for browser login flows. #[serde(rename = "csrf_token", skip_serializing_if = "Option::is_none")] csrf_token: Option<String>, /// Email to Recover Needs to be set when initiating the flow. If the email is a registered recovery email, a recovery link will be sent. If the email is not known, a email with details on what happened will be sent instead. format: email #[serde(rename = "email")] email: String, }, }
35.666667
248
0.705607
019dc9c80de5a0cd2d0addd0a131d0fe6cd12b6e
88
pub use client::*; pub use daemon::*; mod discord; mod daemon; mod client; mod lastfm;
11
18
0.693182
ff91f93def3b866621fb8d154affea16ce875e80
7,894
use std::collections::HashMap; use std::env; use std::fmt::Write; use std::fs; use std::path::PathBuf; fn main() { let chip_name = match env::vars() .map(|(a, _)| a) .filter(|x| x.starts_with("CARGO_FEATURE_STM32")) .get_one() { Ok(x) => x, Err(GetOneError::None) => panic!("No stm32xx Cargo feature enabled"), Err(GetOneError::Multiple) => panic!("Multiple stm32xx Cargo features enabled"), } .strip_prefix("CARGO_FEATURE_") .unwrap() .to_ascii_lowercase(); struct Peripheral { kind: String, name: String, version: String, } let mut peripheral_version_mapping = HashMap::<String, String>::new(); stm32_metapac::peripheral_versions!( ($peri:ident, $version:ident) => { peripheral_version_mapping.insert(stringify!($peri).to_string(), stringify!($version).to_string()); println!("cargo:rustc-cfg={}", stringify!($peri)); println!("cargo:rustc-cfg={}_{}", stringify!($peri), stringify!($version)); }; ); let mut peripherals: Vec<Peripheral> = Vec::new(); stm32_metapac::peripherals!( ($kind:ident, $name:ident) => { peripherals.push(Peripheral{ kind: stringify!($kind).to_string(), name: stringify!($name).to_string(), version: peripheral_version_mapping[&stringify!($kind).to_ascii_lowercase()].clone() }); }; ); // ======== // Generate singletons let mut singletons: Vec<String> = Vec::new(); for p in peripherals { match p.kind.as_str() { // Generate singletons per pin, not per port "gpio" => { println!("{}", p.name); let port_letter = p.name.strip_prefix("GPIO").unwrap(); for pin_num in 0..16 { singletons.push(format!("P{}{}", port_letter, pin_num)); } } // No singleton for these, the HAL handles them specially. "exti" => {} // We *shouldn't* have singletons for these, but the HAL currently requires // singletons, for using with RccPeripheral to enable/disable clocks to them. "rcc" => { if p.version == "h7" { singletons.push("MCO1".to_string()); singletons.push("MCO2".to_string()); } singletons.push(p.name.clone()); } //"dbgmcu" => {} //"syscfg" => {} //"dma" => {} //"bdma" => {} //"dmamux" => {} // For other peripherals, one singleton per peri _ => singletons.push(p.name.clone()), } } // One singleton per EXTI line for pin_num in 0..16 { singletons.push(format!("EXTI{}", pin_num)); } // One singleton per DMA channel stm32_metapac::dma_channels! { ($channel_peri:ident, $dma_peri:ident, $version:ident, $channel_num:expr, $ignore:tt) => { singletons.push(stringify!($channel_peri).to_string()); }; } let mut generated = String::new(); write!( &mut generated, "embassy_hal_common::peripherals!({});\n", singletons.join(",") ) .unwrap(); // ======== // Generate DMA IRQs. // This can't be done with macrotables alone because in many chips, one irq is shared between many // channels, so we have to deduplicate them. #[allow(unused_mut)] let mut dma_irqs: Vec<String> = Vec::new(); #[allow(unused_mut)] let mut bdma_irqs: Vec<String> = Vec::new(); stm32_metapac::interrupts! { ($peri:ident, dma, $block:ident, $signal_name:ident, $irq:ident) => { dma_irqs.push(stringify!($irq).to_string()); }; ($peri:ident, bdma, $block:ident, $signal_name:ident, $irq:ident) => { bdma_irqs.push(stringify!($irq).to_string()); }; } dma_irqs.sort(); dma_irqs.dedup(); bdma_irqs.sort(); bdma_irqs.dedup(); for irq in dma_irqs { write!( &mut generated, "#[crate::interrupt] unsafe fn {} () {{ crate::dma::dma::on_irq(); }}\n", irq ) .unwrap(); } for irq in bdma_irqs { write!( &mut generated, "#[crate::interrupt] unsafe fn {} () {{ crate::dma::bdma::on_irq(); }}\n", irq ) .unwrap(); } // ======== // Write generated.rs let out_dir = &PathBuf::from(env::var_os("OUT_DIR").unwrap()); let out_file = out_dir.join("generated.rs").to_string_lossy().to_string(); fs::write(out_file, &generated).unwrap(); // ======== // Multicore let mut s = chip_name.split('_'); let mut chip_name: String = s.next().unwrap().to_string(); let core_name = if let Some(c) = s.next() { if !c.starts_with("CM") { chip_name.push('_'); chip_name.push_str(c); None } else { Some(c) } } else { None }; if let Some(core) = core_name { println!( "cargo:rustc-cfg={}_{}", &chip_name[..chip_name.len() - 2], core ); } else { println!("cargo:rustc-cfg={}", &chip_name[..chip_name.len() - 2]); } // ======== // stm32f3 wildcard features used in RCC if chip_name.starts_with("stm32f3") { println!("cargo:rustc-cfg={}x{}", &chip_name[..9], &chip_name[10..11]); } // ======== // Handle time-driver-XXXX features. let time_driver = match env::vars() .map(|(a, _)| a) .filter(|x| x.starts_with("CARGO_FEATURE_TIME_DRIVER_")) .get_one() { Ok(x) => Some( x.strip_prefix("CARGO_FEATURE_TIME_DRIVER_") .unwrap() .to_ascii_lowercase(), ), Err(GetOneError::None) => None, Err(GetOneError::Multiple) => panic!("Multiple stm32xx Cargo features enabled"), }; match time_driver.as_ref().map(|x| x.as_ref()) { None => {} Some("tim2") => println!("cargo:rustc-cfg=time_driver_tim2"), Some("tim3") => println!("cargo:rustc-cfg=time_driver_tim3"), Some("tim4") => println!("cargo:rustc-cfg=time_driver_tim4"), Some("tim5") => println!("cargo:rustc-cfg=time_driver_tim5"), Some("any") => { if singletons.contains(&"TIM2".to_string()) { println!("cargo:rustc-cfg=time_driver_tim2"); } else if singletons.contains(&"TIM3".to_string()) { println!("cargo:rustc-cfg=time_driver_tim3"); } else if singletons.contains(&"TIM4".to_string()) { println!("cargo:rustc-cfg=time_driver_tim4"); } else if singletons.contains(&"TIM5".to_string()) { println!("cargo:rustc-cfg=time_driver_tim5"); } else { panic!("time-driver-any requested, but the chip doesn't have TIM2, TIM3, TIM4 or TIM5.") } } _ => panic!("unknown time_driver {:?}", time_driver), } // Handle time-driver-XXXX features. if env::var("CARGO_FEATURE_TIME_DRIVER_ANY").is_ok() {} println!("cargo:rustc-cfg={}", &chip_name[..chip_name.len() - 2]); println!("cargo:rerun-if-changed=build.rs"); } enum GetOneError { None, Multiple, } trait IteratorExt: Iterator { fn get_one(self) -> Result<Self::Item, GetOneError>; } impl<T: Iterator> IteratorExt for T { fn get_one(mut self) -> Result<Self::Item, GetOneError> { match self.next() { None => Err(GetOneError::None), Some(res) => match self.next() { Some(_) => Err(GetOneError::Multiple), None => Ok(res), }, } } }
31.07874
111
0.529389
67fc758a97327bf8c860fe6a8d8028ce9e793d06
373
use naia_derive::Replicate; use naia_shared::Property; #[derive(Replicate)] #[protocol_path = "crate::protocol::Protocol"] pub struct Auth { pub username: Property<String>, pub password: Property<String>, } impl Auth { pub fn new(username: &str, password: &str) -> Self { return Auth::new_complete(username.to_string(), password.to_string()); } }
23.3125
78
0.683646
3345f3452e836164074c900cb1c68e1f4c409c72
1,316
use std::io; use std::io::prelude::*; extern crate regex; use regex::Regex; struct CodeGenerator { code: u64, } impl Iterator for CodeGenerator { type Item = u64; fn next(&mut self) -> Option<Self::Item> { self.code *= 252533; self.code %= 33554393; Some(self.code) } } fn parse(input: &String) -> (u32, u32) { let format = Regex::new(r".*row (\d+), column (\d+).*").unwrap(); let caps = match format.captures(input) { Some(c) => c, None => panic!("could not parse input"), }; let row = u32::from_str_radix(caps.at(1).unwrap(), 10).unwrap(); let col = u32::from_str_radix(caps.at(2).unwrap(), 10).unwrap(); (row, col) } fn main() { let stdin = io::stdin(); let input = stdin.lock().lines().next().unwrap(); let (target_row, target_col) = parse(&input.unwrap()); let mut code = 20151125; let mut generator = CodeGenerator { code: code, }; let mut row = 1; let mut col = 1; loop { println!("({}, {}); {}", row, col, code); if row == target_row && col == target_col { break; } code = generator.next().unwrap(); if row == 1 { row = col + 1; col = 1; } else { row -= 1; col += 1; } } }
25.803922
69
0.512918
db68f84ce21e09aaeff094f163e21243348a6c6b
23,455
//! Contains the `Error` and `Result` types that `mongodb` uses. use std::{ collections::{HashMap, HashSet}, fmt::{self, Debug}, sync::Arc, }; use bson::Bson; use serde::Deserialize; use thiserror::Error; use crate::{bson::Document, options::ServerAddress}; const RECOVERING_CODES: [i32; 5] = [11600, 11602, 13436, 189, 91]; const NOTMASTER_CODES: [i32; 3] = [10107, 13435, 10058]; const SHUTTING_DOWN_CODES: [i32; 2] = [11600, 91]; const RETRYABLE_READ_CODES: [i32; 11] = [11600, 11602, 10107, 13435, 13436, 189, 91, 7, 6, 89, 9001]; const RETRYABLE_WRITE_CODES: [i32; 12] = [ 11600, 11602, 10107, 13435, 13436, 189, 91, 7, 6, 89, 9001, 262, ]; const UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL_CODES: [i32; 3] = [50, 64, 91]; /// Retryable write error label. This label will be added to an error when the error is /// write-retryable. pub const RETRYABLE_WRITE_ERROR: &str = "RetryableWriteError"; /// Transient transaction error label. This label will be added to a network error or server /// selection error that occurs during a transaction. pub const TRANSIENT_TRANSACTION_ERROR: &str = "TransientTransactionError"; /// Unknown transaction commit result error label. This label will be added to a server selection /// error, network error, write-retryable error, MaxTimeMSExpired error, or write concern /// failed/timeout during a commitTransaction. pub const UNKNOWN_TRANSACTION_COMMIT_RESULT: &str = "UnknownTransactionCommitResult"; /// The result type for all methods that can return an error in the `mongodb` crate. pub type Result<T> = std::result::Result<T, Error>; /// An error that can occur in the `mongodb` crate. The inner /// [`ErrorKind`](enum.ErrorKind.html) is wrapped in an `Arc` to allow the errors to be /// cloned. #[derive(Clone, Debug, Error)] #[error("{kind}")] #[non_exhaustive] pub struct Error { /// The type of error that occurred. pub kind: Box<ErrorKind>, labels: HashSet<String>, pub(crate) wire_version: Option<i32>, } impl Error { pub(crate) fn new(kind: ErrorKind, labels: Option<impl IntoIterator<Item = String>>) -> Self { let mut labels: HashSet<String> = labels .map(|labels| labels.into_iter().collect()) .unwrap_or_default(); if let Some(wc) = kind.get_write_concern_error() { labels.extend(wc.labels.clone()); } Self { kind: Box::new(kind), labels, wire_version: None, } } pub(crate) fn pool_cleared_error(address: &ServerAddress, cause: &Error) -> Self { ErrorKind::ConnectionPoolCleared { message: format!( "Connection pool for {} cleared because another operation failed with: {}", address, cause ), } .into() } /// Creates an `AuthenticationError` for the given mechanism with the provided reason. pub(crate) fn authentication_error(mechanism_name: &str, reason: &str) -> Self { ErrorKind::Authentication { message: format!("{} failure: {}", mechanism_name, reason), } .into() } /// Creates an `AuthenticationError` for the given mechanism with a generic "unknown" message. pub(crate) fn unknown_authentication_error(mechanism_name: &str) -> Error { Error::authentication_error(mechanism_name, "internal error") } /// Creates an `AuthenticationError` for the given mechanism when the server response is /// invalid. pub(crate) fn invalid_authentication_response(mechanism_name: &str) -> Error { Error::authentication_error(mechanism_name, "invalid server response") } pub(crate) fn internal(message: impl Into<String>) -> Error { ErrorKind::Internal { message: message.into(), } .into() } pub(crate) fn invalid_argument(message: impl Into<String>) -> Error { ErrorKind::InvalidArgument { message: message.into(), } .into() } pub(crate) fn is_state_change_error(&self) -> bool { self.is_recovering() || self.is_not_master() } pub(crate) fn is_auth_error(&self) -> bool { matches!(self.kind.as_ref(), ErrorKind::Authentication { .. }) } pub(crate) fn is_command_error(&self) -> bool { matches!(self.kind.as_ref(), ErrorKind::Command(_)) } pub(crate) fn is_network_timeout(&self) -> bool { matches!(self.kind.as_ref(), ErrorKind::Io(ref io_err) if io_err.kind() == std::io::ErrorKind::TimedOut) } /// Whether this error is an "ns not found" error or not. pub(crate) fn is_ns_not_found(&self) -> bool { matches!(self.kind.as_ref(), ErrorKind::Command(ref err) if err.code == 26) } pub(crate) fn is_server_selection_error(&self) -> bool { matches!(self.kind.as_ref(), ErrorKind::ServerSelection { .. }) } /// Whether a read operation should be retried if this error occurs. pub(crate) fn is_read_retryable(&self) -> bool { if self.is_network_error() { return true; } match self.code() { Some(code) => RETRYABLE_READ_CODES.contains(&code), None => false, } } pub(crate) fn is_write_retryable(&self) -> bool { self.contains_label(RETRYABLE_WRITE_ERROR) } /// Whether a "RetryableWriteError" label should be added to this error. If max_wire_version /// indicates a 4.4+ server, a label should only be added if the error is a network error. /// Otherwise, a label should be added if the error is a network error or the error code /// matches one of the retryable write codes. pub(crate) fn should_add_retryable_write_label(&self, max_wire_version: i32) -> bool { if max_wire_version > 8 { return self.is_network_error(); } if self.is_network_error() { return true; } match &self.code() { Some(code) => RETRYABLE_WRITE_CODES.contains(code), None => false, } } pub(crate) fn should_add_unknown_transaction_commit_result_label(&self) -> bool { if self.contains_label(TRANSIENT_TRANSACTION_ERROR) { return false; } if self.is_network_error() || self.is_server_selection_error() || self.is_write_retryable() { return true; } match self.code() { Some(code) => UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL_CODES.contains(&code), None => false, } } /// Whether an error originated from the server. pub(crate) fn is_server_error(&self) -> bool { matches!( self.kind.as_ref(), ErrorKind::Authentication { .. } | ErrorKind::BulkWrite(_) | ErrorKind::Command(_) | ErrorKind::Write(_) ) } /// Returns the labels for this error. pub fn labels(&self) -> &HashSet<String> { &self.labels } /// Whether this error contains the specified label. pub fn contains_label<T: AsRef<str>>(&self, label: T) -> bool { self.labels().contains(label.as_ref()) } /// Adds the given label to this error. pub(crate) fn add_label<T: AsRef<str>>(&mut self, label: T) { let label = label.as_ref().to_string(); self.labels.insert(label); } pub(crate) fn from_resolve_error(error: trust_dns_resolver::error::ResolveError) -> Self { ErrorKind::DnsResolve { message: error.to_string(), } .into() } pub(crate) fn is_non_timeout_network_error(&self) -> bool { matches!(self.kind.as_ref(), ErrorKind::Io(ref io_err) if io_err.kind() != std::io::ErrorKind::TimedOut) } pub(crate) fn is_network_error(&self) -> bool { matches!( self.kind.as_ref(), ErrorKind::Io(..) | ErrorKind::ConnectionPoolCleared { .. } ) } /// Gets the code from this error for performing SDAM updates, if applicable. /// Any codes contained in WriteErrors are ignored. pub(crate) fn code(&self) -> Option<i32> { match self.kind.as_ref() { ErrorKind::Command(command_error) => Some(command_error.code), // According to SDAM spec, write concern error codes MUST also be checked, and // writeError codes MUST NOT be checked. ErrorKind::BulkWrite(BulkWriteFailure { write_concern_error: Some(wc_error), .. }) => Some(wc_error.code), ErrorKind::Write(WriteFailure::WriteConcernError(wc_error)) => Some(wc_error.code), _ => None, } } /// Gets the message for this error, if applicable, for use in testing. /// If this error is a BulkWriteError, the messages are concatenated. #[cfg(test)] pub(crate) fn message(&self) -> Option<String> { match self.kind.as_ref() { ErrorKind::Command(command_error) => Some(command_error.message.clone()), // since this is used primarily for errorMessageContains assertions in the unified // runner, we just concatenate all the relevant server messages into one for // bulk errors. ErrorKind::BulkWrite(BulkWriteFailure { write_concern_error, write_errors, inserted_ids: _, }) => { let mut msg = "".to_string(); if let Some(wc_error) = write_concern_error { msg.push_str(wc_error.message.as_str()); } if let Some(write_errors) = write_errors { for we in write_errors { msg.push_str(we.message.as_str()); } } Some(msg) } ErrorKind::Write(WriteFailure::WriteConcernError(wc_error)) => { Some(wc_error.message.clone()) } ErrorKind::Write(WriteFailure::WriteError(write_error)) => { Some(write_error.message.clone()) } ErrorKind::Transaction { message } => Some(message.clone()), ErrorKind::IncompatibleServer { message } => Some(message.clone()), _ => None, } } /// Gets the code name from this error, if applicable. #[cfg(test)] pub(crate) fn code_name(&self) -> Option<&str> { match self.kind.as_ref() { ErrorKind::Command(ref cmd_err) => Some(cmd_err.code_name.as_str()), ErrorKind::Write(ref failure) => match failure { WriteFailure::WriteConcernError(ref wce) => Some(wce.code_name.as_str()), WriteFailure::WriteError(ref we) => we.code_name.as_deref(), }, ErrorKind::BulkWrite(ref bwe) => bwe .write_concern_error .as_ref() .map(|wce| wce.code_name.as_str()), _ => None, } } /// If this error corresponds to a "not master" error as per the SDAM spec. pub(crate) fn is_not_master(&self) -> bool { self.code() .map(|code| NOTMASTER_CODES.contains(&code)) .unwrap_or(false) } /// If this error corresponds to a "node is recovering" error as per the SDAM spec. pub(crate) fn is_recovering(&self) -> bool { self.code() .map(|code| RECOVERING_CODES.contains(&code)) .unwrap_or(false) } /// If this error corresponds to a "node is shutting down" error as per the SDAM spec. pub(crate) fn is_shutting_down(&self) -> bool { self.code() .map(|code| SHUTTING_DOWN_CODES.contains(&code)) .unwrap_or(false) } pub(crate) fn is_pool_cleared(&self) -> bool { matches!(self.kind.as_ref(), ErrorKind::ConnectionPoolCleared { .. }) } /// If this error is resumable as per the change streams spec. pub(crate) fn is_resumable(&self) -> bool { if !self.is_server_error() { return true; } let code = self.code(); if code == Some(43) { return true; } if matches!(self.wire_version, Some(v) if v >= 9) && self.contains_label("ResumableChangeStreamError") { return true; } if let (Some(code), true) = (code, matches!(self.wire_version, Some(v) if v < 9)) { if [ 6, 7, 89, 91, 189, 262, 9001, 10107, 11600, 11602, 13435, 13436, 63, 150, 13388, 234, 133, ] .iter() .any(|c| *c == code) { return true; } } false } } impl<E> From<E> for Error where ErrorKind: From<E>, { fn from(err: E) -> Self { Error::new(err.into(), None::<Option<String>>) } } impl From<bson::de::Error> for ErrorKind { fn from(err: bson::de::Error) -> Self { Self::BsonDeserialization(err) } } impl From<bson::ser::Error> for ErrorKind { fn from(err: bson::ser::Error) -> Self { Self::BsonSerialization(err) } } impl From<bson::raw::Error> for ErrorKind { fn from(err: bson::raw::Error) -> Self { Self::InvalidResponse { message: err.to_string(), } } } impl From<std::io::Error> for ErrorKind { fn from(err: std::io::Error) -> Self { Self::Io(Arc::new(err)) } } impl From<std::io::ErrorKind> for ErrorKind { fn from(err: std::io::ErrorKind) -> Self { Self::Io(Arc::new(err.into())) } } /// The types of errors that can occur. #[allow(missing_docs)] #[derive(Clone, Debug, Error)] #[non_exhaustive] pub enum ErrorKind { /// An invalid argument was provided. #[error("An invalid argument was provided: {message}")] #[non_exhaustive] InvalidArgument { message: String }, /// An error occurred while the [`Client`](../struct.Client.html) attempted to authenticate a /// connection. #[error("{message}")] #[non_exhaustive] Authentication { message: String }, /// Wrapper around `bson::de::Error`. #[error("{0}")] BsonDeserialization(crate::bson::de::Error), /// Wrapper around `bson::ser::Error`. #[error("{0}")] BsonSerialization(crate::bson::ser::Error), /// An error occurred when trying to execute a write operation consisting of multiple writes. #[error("An error occurred when trying to execute a write operation: {0:?}")] BulkWrite(BulkWriteFailure), /// The server returned an error to an attempted operation. #[error("Command failed {0}")] Command(CommandError), /// An error occurred during DNS resolution. #[error("An error occurred during DNS resolution: {message}")] #[non_exhaustive] DnsResolve { message: String }, #[error("Internal error: {message}")] #[non_exhaustive] Internal { message: String }, /// Wrapper around [`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html). #[error("{0}")] Io(Arc<std::io::Error>), /// The connection pool for a server was cleared during operation execution due to /// a concurrent error, causing the operation to fail. #[error("{message}")] #[non_exhaustive] ConnectionPoolCleared { message: String }, /// The server returned an invalid reply to a database operation. #[error("The server returned an invalid reply to a database operation: {message}")] #[non_exhaustive] InvalidResponse { message: String }, /// The Client was not able to select a server for the operation. #[error("{message}")] #[non_exhaustive] ServerSelection { message: String }, /// The Client does not support sessions. #[error("Attempted to start a session on a deployment that does not support sessions")] SessionsNotSupported, #[error("{message}")] #[non_exhaustive] InvalidTlsConfig { message: String }, /// An error occurred when trying to execute a write operation. #[error("An error occurred when trying to execute a write operation: {0:?}")] Write(WriteFailure), /// An error occurred during a transaction. #[error("{message}")] #[non_exhaustive] Transaction { message: String }, /// The server does not support the operation. #[error("The server does not support a database operation: {message}")] #[non_exhaustive] IncompatibleServer { message: String }, /// No resume token was present in a change stream document. #[error("Cannot provide resume functionality when the resume token is missing")] MissingResumeToken, } impl ErrorKind { // This is only used as part of a workaround to Atlas Proxy not returning // toplevel error labels. // TODO CLOUDP-105256 Remove this when Atlas Proxy error label behavior is fixed. fn get_write_concern_error(&self) -> Option<&WriteConcernError> { match self { ErrorKind::BulkWrite(BulkWriteFailure { write_concern_error, .. }) => write_concern_error.as_ref(), ErrorKind::Write(WriteFailure::WriteConcernError(err)) => Some(err), _ => None, } } } /// An error that occurred due to a database command failing. #[derive(Clone, Debug, Deserialize)] #[non_exhaustive] pub struct CommandError { /// Identifies the type of error. pub code: i32, /// The name associated with the error code. #[serde(rename = "codeName", default)] pub code_name: String, /// A description of the error that occurred. #[serde(rename = "errmsg")] pub message: String, } impl fmt::Display for CommandError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "({}): {})", self.code_name, self.message) } } /// An error that occurred due to not being able to satisfy a write concern. #[derive(Clone, Debug, Deserialize, PartialEq)] #[non_exhaustive] pub struct WriteConcernError { /// Identifies the type of write concern error. pub code: i32, /// The name associated with the error code. #[serde(rename = "codeName", default)] pub code_name: String, /// A description of the error that occurred. #[serde(rename = "errmsg")] pub message: String, /// A document identifying the write concern setting related to the error. #[serde(rename = "errInfo")] pub details: Option<Document>, /// Labels categorizing the error. // TODO CLOUDP-105256 Remove this when the Atlas Proxy properly returns // error labels at the top level. #[serde(rename = "errorLabels", default)] pub(crate) labels: Vec<String>, } /// An error that occurred during a write operation that wasn't due to being unable to satisfy a /// write concern. #[derive(Clone, Debug, PartialEq, Deserialize)] #[non_exhaustive] pub struct WriteError { /// Identifies the type of write error. pub code: i32, /// The name associated with the error code. /// /// Note that the server will not return this in some cases, hence `code_name` being an /// `Option`. #[serde(rename = "codeName", default)] pub code_name: Option<String>, /// A description of the error that occurred. #[serde(rename = "errmsg")] pub message: String, /// A document providing more information about the write error (e.g. details /// pertaining to document validation). #[serde(rename = "errInfo")] pub details: Option<Document>, } /// An error that occurred during a write operation consisting of multiple writes that wasn't due to /// being unable to satisfy a write concern. #[derive(Debug, PartialEq, Clone, Deserialize)] #[non_exhaustive] pub struct BulkWriteError { /// Index into the list of operations that this error corresponds to. #[serde(default)] pub index: usize, /// Identifies the type of write concern error. pub code: i32, /// The name associated with the error code. /// /// Note that the server will not return this in some cases, hence `code_name` being an /// `Option`. #[serde(rename = "codeName", default)] pub code_name: Option<String>, /// A description of the error that occurred. #[serde(rename = "errmsg")] pub message: String, /// A document providing more information about the write error (e.g. details /// pertaining to document validation). #[serde(rename = "errInfo")] pub details: Option<Document>, } /// The set of errors that occurred during a write operation. #[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct BulkWriteFailure { /// The error(s) that occurred on account of a non write concern failure. pub write_errors: Option<Vec<BulkWriteError>>, /// The error that occurred on account of write concern failure. pub write_concern_error: Option<WriteConcernError>, #[serde(skip)] pub(crate) inserted_ids: HashMap<usize, Bson>, } impl BulkWriteFailure { pub(crate) fn new() -> Self { BulkWriteFailure { write_errors: None, write_concern_error: None, inserted_ids: Default::default(), } } } /// An error that occurred when trying to execute a write operation. #[derive(Clone, Debug)] #[non_exhaustive] pub enum WriteFailure { /// An error that occurred due to not being able to satisfy a write concern. WriteConcernError(WriteConcernError), /// An error that occurred during a write operation that wasn't due to being unable to satisfy /// a write concern. WriteError(WriteError), } impl WriteFailure { fn from_bulk_failure(bulk: BulkWriteFailure) -> Result<Self> { if let Some(bulk_write_error) = bulk.write_errors.and_then(|es| es.into_iter().next()) { let write_error = WriteError { code: bulk_write_error.code, code_name: bulk_write_error.code_name, message: bulk_write_error.message, details: bulk_write_error.details, }; Ok(WriteFailure::WriteError(write_error)) } else if let Some(wc_error) = bulk.write_concern_error { Ok(WriteFailure::WriteConcernError(wc_error)) } else { Err(ErrorKind::InvalidResponse { message: "error missing write errors and write concern errors".to_string(), } .into()) } } } /// Translates ErrorKind::BulkWriteError cases to ErrorKind::WriteErrors, leaving all other errors /// untouched. pub(crate) fn convert_bulk_errors(error: Error) -> Error { match *error.kind { ErrorKind::BulkWrite(bulk_failure) => match WriteFailure::from_bulk_failure(bulk_failure) { Ok(failure) => Error::new(ErrorKind::Write(failure), Some(error.labels)), Err(e) => e, }, _ => error, } } /// Flag a load-balanced mode mismatch. With debug assertions enabled, it will panic; otherwise, /// it will return the argument, or `()` if none is given. // TODO RUST-230 Log an error in the non-panic branch for mode mismatch. macro_rules! load_balanced_mode_mismatch { ($e:expr) => {{ if cfg!(debug_assertions) { panic!("load-balanced mode mismatch") } return $e; }}; () => { load_balanced_mode_mismatch!(()) }; } pub(crate) use load_balanced_mode_mismatch;
34.341142
112
0.618333
1ecd693219b891e364335a251953b76d6aa8187e
1,617
use mysql; use crate::material::MySQLConnection; pub trait Select { fn select<T>(&self, query_str: &str, process_row: &dyn Fn(mysql::Row) -> T) -> Vec<T>; fn select_wparams<T>(&self, query_str: &str, process_row: &dyn Fn(mysql::Row) -> T, params: std::vec::Vec<(std::string::String, mysql::Value)>) -> Vec<T>; fn select_value<T>(&self, query_str: &str, process_row: &dyn Fn(mysql::Row) -> T) -> Option<T>; fn select_wparams_value<T>(&self, query_str: &str, process_row: &dyn Fn(mysql::Row) -> T, params: std::vec::Vec<(std::string::String, mysql::Value)>) -> Option<T>; } impl Select for MySQLConnection { fn select<T>(&self, query_str: &str, process_row: &dyn Fn(mysql::Row) -> T) -> Vec<T> { self.con.prep_exec(query_str, ()) .map(|result| { result.map(|x| x.unwrap()) .map(|row| process_row(row)) .collect() }).unwrap() } fn select_wparams<T>(&self, query_str: &str, process_row: &dyn Fn(mysql::Row) -> T, params: std::vec::Vec<(std::string::String, mysql::Value)>) -> Vec<T> { self.con.prep_exec(query_str, params) .map(|result| { result.map(|x| x.unwrap()) .map(|row| process_row(row)) .collect() }).unwrap() } fn select_value<T>(&self, query_str: &str, process_row: &dyn Fn(mysql::Row) -> T) -> Option<T> { self.select(query_str, process_row).pop() } fn select_wparams_value<T>(&self, query_str: &str, process_row: &dyn Fn(mysql::Row) -> T, params: std::vec::Vec<(std::string::String, mysql::Value)>) -> Option<T> { self.select_wparams(query_str, process_row, params).pop() } }
38.5
165
0.615337
904624f9ab0161d1c67a9614a826bf5832fdb3ec
11,451
//! Renderer for function calls. use hir::{AsAssocItem, HasSource, HirDisplay}; use ide_db::SymbolKind; use itertools::Itertools; use syntax::ast; use crate::{ item::{CompletionItem, CompletionItemKind, CompletionKind, CompletionRelevance, ImportEdit}, render::{ builder_ext::Params, compute_exact_name_match, compute_ref_match, compute_type_match, RenderContext, }, }; pub(crate) fn render_fn( ctx: RenderContext<'_>, import_to_add: Option<ImportEdit>, local_name: Option<hir::Name>, fn_: hir::Function, ) -> Option<CompletionItem> { let _p = profile::span("render_fn"); Some(FunctionRender::new(ctx, None, local_name, fn_, false)?.render(import_to_add)) } pub(crate) fn render_method( ctx: RenderContext<'_>, import_to_add: Option<ImportEdit>, receiver: Option<hir::Name>, local_name: Option<hir::Name>, fn_: hir::Function, ) -> Option<CompletionItem> { let _p = profile::span("render_method"); Some(FunctionRender::new(ctx, receiver, local_name, fn_, true)?.render(import_to_add)) } #[derive(Debug)] struct FunctionRender<'a> { ctx: RenderContext<'a>, name: String, receiver: Option<hir::Name>, func: hir::Function, /// NB: having `ast::Fn` here might or might not be a good idea. The problem /// with it is that, to get an `ast::`, you want to parse the corresponding /// source file. So, when flyimport completions suggest a bunch of /// functions, we spend quite some time parsing many files. /// /// We need ast because we want to access parameter names (patterns). We can /// add them to the hir of the function itself, but parameter names are not /// something hir cares otherwise. /// /// Alternatively we can reconstruct params from the function body, but that /// would require parsing anyway. /// /// It seems that just using `ast` is the best choice -- most of parses /// should be cached anyway. ast_node: ast::Fn, is_method: bool, } impl<'a> FunctionRender<'a> { fn new( ctx: RenderContext<'a>, receiver: Option<hir::Name>, local_name: Option<hir::Name>, fn_: hir::Function, is_method: bool, ) -> Option<FunctionRender<'a>> { let name = local_name.unwrap_or_else(|| fn_.name(ctx.db())).to_string(); let ast_node = fn_.source(ctx.db())?.value; Some(FunctionRender { ctx, name, receiver, func: fn_, ast_node, is_method }) } fn render(self, import_to_add: Option<ImportEdit>) -> CompletionItem { let params = self.params(); let call = match &self.receiver { Some(receiver) => format!("{}.{}", receiver, &self.name), None => self.name.clone(), }; let mut item = CompletionItem::new(CompletionKind::Reference, self.ctx.source_range(), call.clone()); item.kind(self.kind()) .set_documentation(self.ctx.docs(self.func)) .set_deprecated( self.ctx.is_deprecated(self.func) || self.ctx.is_deprecated_assoc_item(self.func), ) .detail(self.detail()) .add_call_parens(self.ctx.completion, call.clone(), params); if import_to_add.is_none() { let db = self.ctx.db(); if let Some(actm) = self.func.as_assoc_item(db) { if let Some(trt) = actm.containing_trait_or_trait_impl(db) { item.trait_name(trt.name(db).to_string()); } } } item.add_import(import_to_add).lookup_by(self.name); let ret_type = self.func.ret_type(self.ctx.db()); item.set_relevance(CompletionRelevance { type_match: compute_type_match(self.ctx.completion, &ret_type), exact_name_match: compute_exact_name_match(self.ctx.completion, &call), ..CompletionRelevance::default() }); if let Some(ref_match) = compute_ref_match(self.ctx.completion, &ret_type) { // FIXME // For now we don't properly calculate the edits for ref match // completions on methods, so we've disabled them. See #8058. if !self.is_method { item.ref_match(ref_match); } } item.build() } fn detail(&self) -> String { let ret_ty = self.func.ret_type(self.ctx.db()); let ret = if ret_ty.is_unit() { // Omit the return type if it is the unit type String::new() } else { format!(" {}", self.ty_display()) }; format!("fn({}){}", self.params_display(), ret) } fn params_display(&self) -> String { if let Some(self_param) = self.func.self_param(self.ctx.db()) { let params = self .func .assoc_fn_params(self.ctx.db()) .into_iter() .skip(1) // skip the self param because we are manually handling that .map(|p| p.ty().display(self.ctx.db()).to_string()); std::iter::once(self_param.display(self.ctx.db()).to_owned()).chain(params).join(", ") } else { let params = self .func .assoc_fn_params(self.ctx.db()) .into_iter() .map(|p| p.ty().display(self.ctx.db()).to_string()) .join(", "); params } } fn ty_display(&self) -> String { let ret_ty = self.func.ret_type(self.ctx.db()); format!("-> {}", ret_ty.display(self.ctx.db())) } fn add_arg(&self, arg: &str, ty: &hir::Type) -> String { if let Some(derefed_ty) = ty.remove_ref() { for (name, local) in self.ctx.completion.locals.iter() { if name == arg && local.ty(self.ctx.db()) == derefed_ty { let mutability = if ty.is_mutable_reference() { "&mut " } else { "&" }; return format!("{}{}", mutability, arg); } } } arg.to_string() } fn params(&self) -> Params { let ast_params = match self.ast_node.param_list() { Some(it) => it, None => return Params::Named(Vec::new()), }; let mut params_pats = Vec::new(); let params_ty = if self.ctx.completion.has_dot_receiver() || self.receiver.is_some() { self.func.method_params(self.ctx.db()).unwrap_or_default() } else { if let Some(s) = ast_params.self_param() { cov_mark::hit!(parens_for_method_call_as_assoc_fn); params_pats.push(Some(s.to_string())); } self.func.assoc_fn_params(self.ctx.db()) }; params_pats .extend(ast_params.params().into_iter().map(|it| it.pat().map(|it| it.to_string()))); let params = params_pats .into_iter() .zip(params_ty) .flat_map(|(pat, param_ty)| { let pat = pat?; let name = pat; let arg = name.trim_start_matches("mut ").trim_start_matches('_'); Some(self.add_arg(arg, param_ty.ty())) }) .collect(); Params::Named(params) } fn kind(&self) -> CompletionItemKind { if self.func.self_param(self.ctx.db()).is_some() { CompletionItemKind::Method } else { SymbolKind::Function.into() } } } #[cfg(test)] mod tests { use crate::{ tests::{check_edit, check_edit_with_config, TEST_CONFIG}, CompletionConfig, }; #[test] fn inserts_parens_for_function_calls() { cov_mark::check!(inserts_parens_for_function_calls); check_edit( "no_args", r#" fn no_args() {} fn main() { no_$0 } "#, r#" fn no_args() {} fn main() { no_args()$0 } "#, ); check_edit( "with_args", r#" fn with_args(x: i32, y: String) {} fn main() { with_$0 } "#, r#" fn with_args(x: i32, y: String) {} fn main() { with_args(${1:x}, ${2:y})$0 } "#, ); check_edit( "foo", r#" struct S; impl S { fn foo(&self) {} } fn bar(s: &S) { s.f$0 } "#, r#" struct S; impl S { fn foo(&self) {} } fn bar(s: &S) { s.foo()$0 } "#, ); check_edit( "foo", r#" struct S {} impl S { fn foo(&self, x: i32) {} } fn bar(s: &S) { s.f$0 } "#, r#" struct S {} impl S { fn foo(&self, x: i32) {} } fn bar(s: &S) { s.foo(${1:x})$0 } "#, ); check_edit( "foo", r#" struct S {} impl S { fn foo(&self, x: i32) { $0 } } "#, r#" struct S {} impl S { fn foo(&self, x: i32) { self.foo(${1:x})$0 } } "#, ); } #[test] fn parens_for_method_call_as_assoc_fn() { cov_mark::check!(parens_for_method_call_as_assoc_fn); check_edit( "foo", r#" struct S; impl S { fn foo(&self) {} } fn main() { S::f$0 } "#, r#" struct S; impl S { fn foo(&self) {} } fn main() { S::foo(${1:&self})$0 } "#, ); } #[test] fn suppress_arg_snippets() { cov_mark::check!(suppress_arg_snippets); check_edit_with_config( CompletionConfig { add_call_argument_snippets: false, ..TEST_CONFIG }, "with_args", r#" fn with_args(x: i32, y: String) {} fn main() { with_$0 } "#, r#" fn with_args(x: i32, y: String) {} fn main() { with_args($0) } "#, ); } #[test] fn strips_underscores_from_args() { check_edit( "foo", r#" fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {} fn main() { f$0 } "#, r#" fn foo(_foo: i32, ___bar: bool, ho_ge_: String) {} fn main() { foo(${1:foo}, ${2:bar}, ${3:ho_ge_})$0 } "#, ); } #[test] fn insert_ref_when_matching_local_in_scope() { check_edit( "ref_arg", r#" struct Foo {} fn ref_arg(x: &Foo) {} fn main() { let x = Foo {}; ref_ar$0 } "#, r#" struct Foo {} fn ref_arg(x: &Foo) {} fn main() { let x = Foo {}; ref_arg(${1:&x})$0 } "#, ); } #[test] fn insert_mut_ref_when_matching_local_in_scope() { check_edit( "ref_arg", r#" struct Foo {} fn ref_arg(x: &mut Foo) {} fn main() { let x = Foo {}; ref_ar$0 } "#, r#" struct Foo {} fn ref_arg(x: &mut Foo) {} fn main() { let x = Foo {}; ref_arg(${1:&mut x})$0 } "#, ); } #[test] fn insert_ref_when_matching_local_in_scope_for_method() { check_edit( "apply_foo", r#" struct Foo {} struct Bar {} impl Bar { fn apply_foo(&self, x: &Foo) {} } fn main() { let x = Foo {}; let y = Bar {}; y.$0 } "#, r#" struct Foo {} struct Bar {} impl Bar { fn apply_foo(&self, x: &Foo) {} } fn main() { let x = Foo {}; let y = Bar {}; y.apply_foo(${1:&x})$0 } "#, ); } #[test] fn trim_mut_keyword_in_func_completion() { check_edit( "take_mutably", r#" fn take_mutably(mut x: &i32) {} fn main() { take_m$0 } "#, r#" fn take_mutably(mut x: &i32) {} fn main() { take_mutably(${1:x})$0 } "#, ); } }
24.785714
98
0.527378
699479104eead928393994804e03d222e9f9345d
346
// Copyright (c) The Dijets Core Contributors // SPDX-License-Identifier: Apache-2.0 pub fn read_env_var(v: &str) -> String { std::env::var(v).unwrap_or_else(|_| String::new()) } pub fn read_bool_env_var(v: &str) -> bool { let val = read_env_var(v).to_lowercase(); val.parse::<bool>() == Ok(true) || val.parse::<usize>() == Ok(1) }
28.833333
68
0.635838
ef3a7c9821b972aea7b0c07669556fc3b13b1bf8
7,195
use std::fs; use std::path::Path; use std::sync::Arc; use fuzzy_matcher::skim::SkimMatcherV2; use fuzzy_matcher::FuzzyMatcher; use ini::Ini; use serde::{Deserialize, Serialize}; use walkdir::WalkDir; use druid::{ AppDelegate, Command, DelegateCtx, Env, Event, HotKey, KeyCode, SysMods, Target, WindowId, }; use crate::{AppState, SearchResult}; #[derive(Serialize, Deserialize)] pub struct Delegate { #[serde(skip)] matcher: SkimMatcherV2, cache: Vec<SearchResult>, } impl Delegate { pub fn new() -> Self { Self { matcher: SkimMatcherV2::default(), cache: match fs::File::open("/tmp/fuzzle_cache.bincode") { Ok(file) => match bincode::deserialize_from::<fs::File, Delegate>(file) { Ok(delegate) => delegate.cache, Err(_) => vec![], }, Err(_) => vec![], }, } } fn populate_entry(&mut self, path: &Path) -> Option<SearchResult> { let info = Ini::load_from_file(path).unwrap(); let section = match info.section(Some("Desktop Entry")) { Some(sec) => sec, None => return None, }; let name = match section.get("Name") { Some(name) => name.to_string(), None => return None, }; let description = match section.get("Comment") { Some(description) => description.to_string(), None => return None, }; let icon = match section.get("Icon") { Some(icon) => icon, None => return None, }; let command = match section.get("Exec") { Some(command) => command.to_string(), None => return None, }; // TODO: Ideally the user should be able to configure // a default theme a some fallback themes // // First search a default theme let icon_entry = WalkDir::new("/usr/share/icons/hicolor/48x48") .into_iter() .filter_map(|e| e.ok()) .find(|e| e.path().file_stem().unwrap() == icon); // If we can't find the icon, search any theme. // Even though WalkDir is quite fast, this can become slow if there are // a lot of themes let icon_entry = match icon_entry { Some(icon_entry) => Some(icon_entry), None => { let mut res = None; for icon_theme in std::fs::read_dir("/usr/share/icons/").unwrap() { let mut icon_theme_path = icon_theme.unwrap().path(); icon_theme_path.push("48x48"); res = WalkDir::new(icon_theme_path) .into_iter() .filter_map(|e| e.ok()) .find(|e| e.path().file_stem().unwrap() == icon); if res.is_some() { break; } } res } }; let icon_path = match icon_entry { Some(entry) => Some(String::from(entry.path().to_str().unwrap())), None => None, }; Some(SearchResult { icon_path, path: String::from(path.to_str().unwrap()), name, description, command, score: 0, selected: false, indices: vec![], }) } fn populate_cache(&mut self) { self.cache = fs::read_dir("/usr/share/applications/") .expect("Can't find /usr/share/applications/, I'll just die") .filter_map(|path| self.populate_entry(&path.unwrap().path())) .collect(); // Reset search results if let Ok(file) = fs::File::create("/tmp/fuzzle_cache.bincode") { bincode::serialize_into(file, self).unwrap(); } } fn search(&mut self, data: &AppState) -> (usize, Vec<SearchResult>) { // Search in all the cache so we have score for each entry let mut res: Vec<SearchResult> = self .cache .iter() .filter_map(|sr| { let result = self.matcher.fuzzy_indices(&sr.name, &data.input_text); if let Some((score, indices)) = result { Some(SearchResult { score, indices, selected: false, ..sr.clone() }) } else { None } }) .collect(); // Now order by score, descending res.sort_unstable_by_key(|a| -a.score); // Select the line let len = res.len(); if len > data.selected_line { res[data.selected_line].selected = true; } ( len, res[data.selected_line.max(1) - 1..(data.selected_line + 3).min(len)].to_vec(), ) } } impl AppDelegate<AppState> for Delegate { fn event( &mut self, _ctx: &mut DelegateCtx, _window_id: WindowId, event: Event, data: &mut AppState, _env: &Env, ) -> Option<Event> { let (num_results, results) = self.search(&data); if let Event::KeyDown(key_event) = event { match key_event { ke if ke.key_code == KeyCode::Escape => std::process::exit(0), ke if ke.key_code == KeyCode::Return => { let command = data.search_results[data.selected_line].command.clone(); let command = command.split_whitespace().next().unwrap(); if std::process::Command::new(command).spawn().is_ok() { std::process::exit(0) } } ke if (HotKey::new(SysMods::Cmd, "j")).matches(ke) || ke.key_code == KeyCode::ArrowDown => { data.selected_line = data.selected_line.min(num_results - 2) + 1; } ke if (HotKey::new(SysMods::Cmd, "k")).matches(ke) || ke.key_code == KeyCode::ArrowUp => { data.selected_line = data.selected_line.max(1) - 1; } k_e if k_e.key_code.is_printable() || (HotKey::new(None, KeyCode::Backspace)).matches(k_e) => { // Reset selected line if new text comes data.selected_line = 0; } _ => (), } }; data.search_results = Arc::new(results); Some(event) } fn command( &mut self, _d: &mut DelegateCtx, _t: &Target, _c: &Command, _a: &mut AppState, _e: &Env, ) -> bool { false } fn window_added(&mut self, _i: WindowId, _d: &mut AppState, _e: &Env, _c: &mut DelegateCtx) { if self.cache.is_empty() { self.populate_cache(); } } fn window_removed(&mut self, _i: WindowId, _d: &mut AppState, _e: &Env, _c: &mut DelegateCtx) {} }
32.853881
100
0.484781
112f97cb0138360a7d6a7bc555a170f9b144c3e8
1,596
/* * Copyright 2020 Fluence Labs Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use crate::{make_swarms, ConnectedClient, KAD_TIMEOUT}; use libp2p::core::Multiaddr; use std::str::FromStr; use std::thread::sleep; pub fn connect_swarms(node_count: usize) -> impl Fn(usize) -> ConnectedClient { let swarms = make_swarms(node_count); sleep(KAD_TIMEOUT); move |i| ConnectedClient::connect_to(swarms[i].1.clone()).expect("connect client") } pub fn connect_real(node_count: usize) -> impl Fn(usize) -> ConnectedClient { let nodes = vec![ "/ip4/134.209.186.43/tcp/7001", "/ip4/134.209.186.43/tcp/7002", "/ip4/134.209.186.43/tcp/7003", "/ip4/134.209.186.43/tcp/7004", "/ip4/134.209.186.43/tcp/7005", "/ip4/134.209.186.43/tcp/7770", "/ip4/134.209.186.43/tcp/7100", ] .into_iter() .map(|addr| Multiaddr::from_str(addr).expect("valid multiaddr")) .cycle() .take(node_count) .collect::<Vec<_>>(); move |i| ConnectedClient::connect_to(nodes[i].clone()).expect("connect client") }
33.25
86
0.675439
39f8cf10eba97e247e646e8fa27d5744a890f038
29,843
// Copyright 2020. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use std::sync::Arc; use chrono::Utc; use futures::{channel::mpsc::Receiver, FutureExt, StreamExt}; use log::*; use crate::transaction_service::{ error::{TransactionServiceError, TransactionServiceProtocolError}, handle::TransactionEvent, service::TransactionServiceResources, storage::database::{CompletedTransaction, OutboundTransaction, TransactionBackend, TransactionStatus}, }; use futures::channel::oneshot; use tari_comms::{peer_manager::NodeId, types::CommsPublicKey}; use tari_comms_dht::{ domain_message::OutboundDomainMessage, envelope::NodeDestination, outbound::{MessageSendStates, OutboundEncryption, SendMessageResponse}, }; use tari_core::transactions::{ tari_amount::MicroTari, transaction::{KernelFeatures, TransactionError}, transaction_protocol::{proto, recipient::RecipientSignedMessage, sender::SingleRoundSenderData}, SenderTransactionProtocol, }; use tari_p2p::{services::liveness::LivenessEvent, tari_message::TariMessageType}; const LOG_TARGET: &str = "wallet::transaction_service::protocols::send_protocol"; #[derive(Debug, PartialEq)] pub enum TransactionProtocolStage { Initial, WaitForReply, } pub struct TransactionSendProtocol<TBackend> where TBackend: TransactionBackend + Clone + 'static { id: u64, dest_pubkey: CommsPublicKey, amount: MicroTari, message: String, sender_protocol: SenderTransactionProtocol, stage: TransactionProtocolStage, resources: TransactionServiceResources<TBackend>, transaction_reply_receiver: Option<Receiver<(CommsPublicKey, RecipientSignedMessage)>>, cancellation_receiver: Option<oneshot::Receiver<()>>, } #[allow(clippy::too_many_arguments)] impl<TBackend> TransactionSendProtocol<TBackend> where TBackend: TransactionBackend + Clone + 'static { pub fn new( id: u64, resources: TransactionServiceResources<TBackend>, transaction_reply_receiver: Receiver<(CommsPublicKey, RecipientSignedMessage)>, cancellation_receiver: oneshot::Receiver<()>, dest_pubkey: CommsPublicKey, amount: MicroTari, message: String, sender_protocol: SenderTransactionProtocol, stage: TransactionProtocolStage, ) -> Self { Self { id, resources, transaction_reply_receiver: Some(transaction_reply_receiver), cancellation_receiver: Some(cancellation_receiver), dest_pubkey, amount, message, sender_protocol, stage, } } /// Execute the Transaction Send Protocol as an async task. pub async fn execute(mut self) -> Result<u64, TransactionServiceProtocolError> { info!( "Starting Transaction Send protocol for TxId: {} at Stage {:?}", self.id, self.stage ); // Only Send the transaction if the protocol stage is Initial. If the protocol is started in a later stage // ignore this if self.stage == TransactionProtocolStage::Initial { if !self.sender_protocol.is_single_round_message_ready() { error!(target: LOG_TARGET, "Sender Transaction Protocol is in an invalid state"); return Err(TransactionServiceProtocolError::new( self.id, TransactionServiceError::InvalidStateError, )); } let msg = self .sender_protocol .build_single_round_message() .map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?; let tx_id = msg.tx_id; if tx_id != self.id { return Err(TransactionServiceProtocolError::new( self.id, TransactionServiceError::InvalidStateError, )); } let SendResult { direct_send_result, store_and_forward_send_result, } = self.send_transaction(msg).await?; if !direct_send_result && !store_and_forward_send_result { return Err(TransactionServiceProtocolError::new( self.id, TransactionServiceError::OutboundSendFailure, )); } self.resources .output_manager_service .confirm_pending_transaction(self.id) .await .map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?; let fee = self .sender_protocol .get_fee_amount() .map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?; let outbound_tx = OutboundTransaction::new( tx_id, self.dest_pubkey.clone(), self.amount, fee, self.sender_protocol.clone(), TransactionStatus::Pending, self.message.clone(), Utc::now().naive_utc(), direct_send_result, ); self.resources .db .add_pending_outbound_transaction(outbound_tx.tx_id, outbound_tx) .await .map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?; info!( target: LOG_TARGET, "Pending Outbound Transaction TxId: {:?} added. Waiting for Reply or Cancellation", self.id, ); } // Waiting for Transaction Reply let tx_id = self.id; let mut receiver = self .transaction_reply_receiver .take() .ok_or_else(|| TransactionServiceProtocolError::new(self.id, TransactionServiceError::InvalidStateError))?; let mut cancellation_receiver = self .cancellation_receiver .take() .ok_or_else(|| TransactionServiceProtocolError::new(self.id, TransactionServiceError::InvalidStateError))? .fuse(); let mut outbound_tx = self .resources .db .get_pending_outbound_transaction(tx_id) .await .map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?; let mut direct_send_result = outbound_tx.direct_send_success; if !outbound_tx.sender_protocol.is_collecting_single_signature() { error!(target: LOG_TARGET, "Pending Transaction not in correct state"); return Err(TransactionServiceProtocolError::new( self.id, TransactionServiceError::InvalidStateError, )); } // Add receiver to Liveness Service to monitor for liveness let mut liveness_event_stream = self.resources.liveness_service.get_event_stream_fused(); let destination_node_id = NodeId::from_key(&self.dest_pubkey) .map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?; if !direct_send_result { self.resources .liveness_service .add_node_id(destination_node_id.clone()) .await .map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?; } #[allow(unused_assignments)] let mut reply = None; loop { futures::select! { (spk, rr) = receiver.select_next_some() => { let rr_tx_id = rr.tx_id; reply = Some(rr); if outbound_tx.destination_public_key != spk { error!( target: LOG_TARGET, "Transaction Reply did not come from the expected Public Key" ); } else if !outbound_tx.sender_protocol.check_tx_id(rr_tx_id) { error!(target: LOG_TARGET, "Transaction Reply does not have the correct TxId"); } else { break; } }, liveness_event = liveness_event_stream.select_next_some() => { if let Ok(event) = liveness_event { if let LivenessEvent::ReceivedPong(pong_event) = (*event).clone() { if !direct_send_result && pong_event.node_id == destination_node_id { debug!(target: LOG_TARGET, "Pong message received from counter-party before Transaction Reply is received, resending transaction TxId: {}", self.id); let msg = self.sender_protocol.get_single_round_message().map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?; // If a direct send attempt is successful then stop resending on Pong and remove an instance of this node_id to be monitored in liveness if self.send_transaction_direct_only(msg).await? { direct_send_result = true; self.resources .liveness_service .remove_node_id(destination_node_id.clone()) .await .map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?; } } } } }, _ = cancellation_receiver => { info!(target: LOG_TARGET, "Cancelling Transaction Send Protocol for TxId: {}", self.id); return Err(TransactionServiceProtocolError::new( self.id, TransactionServiceError::TransactionCancelled, )); } } } let recipient_reply = reply.ok_or_else(|| { TransactionServiceProtocolError::new(self.id, TransactionServiceError::TransactionCancelled) })?; outbound_tx .sender_protocol .add_single_recipient_info(recipient_reply, &self.resources.factories.range_proof) .map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?; let finalize_result = outbound_tx .sender_protocol .finalize(KernelFeatures::empty(), &self.resources.factories) .map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?; if !finalize_result { return Err(TransactionServiceProtocolError::new( self.id, TransactionServiceError::TransactionError(TransactionError::ValidationError( "Transaction could not be finalized".to_string(), )), )); } let tx = outbound_tx .sender_protocol .get_transaction() .map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?; let completed_transaction = CompletedTransaction::new( tx_id, self.resources.node_identity.public_key().clone(), outbound_tx.destination_public_key.clone(), outbound_tx.amount, outbound_tx.fee, tx.clone(), TransactionStatus::Completed, outbound_tx.message.clone(), Utc::now().naive_utc(), ); self.resources .db .complete_outbound_transaction(tx_id, completed_transaction.clone()) .await .map_err(|e| TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)))?; info!( target: LOG_TARGET, "Transaction Recipient Reply for TX_ID = {} received", tx_id, ); let finalized_transaction_message = proto::TransactionFinalizedMessage { tx_id, transaction: Some(tx.clone().into()), }; let _ = self .resources .event_publisher .send(Arc::new(TransactionEvent::ReceivedTransactionReply(tx_id))) .map_err(|e| { trace!( target: LOG_TARGET, "Error sending event, usually because there are no subscribers: {:?}", e ); e }); match self .resources .outbound_message_service .send_direct( outbound_tx.destination_public_key.clone(), OutboundEncryption::None, OutboundDomainMessage::new( TariMessageType::TransactionFinalized, finalized_transaction_message.clone(), ), ) .await { Ok(result) => match result.resolve_ok().await { None => { self.send_transaction_finalized_message_store_and_forward(finalized_transaction_message.clone()) .await? }, Some(send_states) => { if send_states.len() == 1 { debug!( target: LOG_TARGET, "Transaction Finalized (TxId: {}) Direct Send to {} queued with Message Tag: {:?}", self.id, self.dest_pubkey, send_states[0].tag, ); match send_states.wait_single().await { true => { info!( target: LOG_TARGET, "Direct Send of Transaction Finalized message for TX_ID: {} was successful", self.id ); }, false => { error!( target: LOG_TARGET, "Direct Send of Transaction Finalized message for TX_ID: {} was unsuccessful and \ no message was sent", self.id ); self.send_transaction_finalized_message_store_and_forward( finalized_transaction_message.clone(), ) .await? }, } } else { error!( target: LOG_TARGET, "Transaction Finalized message Send Direct for TxID: {} failed", self.id ); self.send_transaction_finalized_message_store_and_forward(finalized_transaction_message.clone()) .await? } }, }, Err(e) => { return Err(TransactionServiceProtocolError::new( self.id, TransactionServiceError::from(e), )) }, } Ok(self.id) } /// Attempt to send the transaction to the recipient both directly and via Store-and-forward. If both fail to send /// the transaction will be cancelled. /// # Arguments /// `msg`: The transaction data message to be sent async fn send_transaction( &mut self, msg: SingleRoundSenderData, ) -> Result<SendResult, TransactionServiceProtocolError> { let proto_message = proto::TransactionSenderMessage::single(msg.clone().into()); let mut store_and_forward_send_result = false; let mut direct_send_result = false; info!( target: LOG_TARGET, "Attempting to Send Transaction (TxId: {}) to recipient with Node Id: {}", self.id, self.dest_pubkey, ); match self .resources .outbound_message_service .send_direct( self.dest_pubkey.clone(), OutboundEncryption::None, OutboundDomainMessage::new(TariMessageType::SenderPartialTransaction, proto_message.clone()), ) .await { Ok(result) => match result { SendMessageResponse::Queued(send_states) => { if self.wait_on_dail(send_states).await { direct_send_result = true; } else { store_and_forward_send_result = self.send_transaction_store_and_forward(msg.clone()).await?; } }, SendMessageResponse::Failed => { store_and_forward_send_result = self.send_transaction_store_and_forward(msg.clone()).await?; }, SendMessageResponse::PendingDiscovery(rx) => { store_and_forward_send_result = self.send_transaction_store_and_forward(msg.clone()).await?; // now wait for discovery to complete match rx.await { Ok(send_msg_response) => match send_msg_response { SendMessageResponse::Queued(send_states) => { debug!("Discovery of {} completed for TxID: {}", self.dest_pubkey, self.id); direct_send_result = self.wait_on_dail(send_states).await; }, _ => (), }, Err(e) => { error!( target: LOG_TARGET, "Error waiting for Discovery while sending message to TxId: {} {:?}", self.id, e ); }, } }, }, Err(e) => { error!(target: LOG_TARGET, "Direct Transaction Send failed: {:?}", e); }, } let _ = self .resources .event_publisher .send(Arc::new(TransactionEvent::TransactionDirectSendResult( self.id, direct_send_result, ))); let _ = self .resources .event_publisher .send(Arc::new(TransactionEvent::TransactionStoreForwardSendResult( self.id, store_and_forward_send_result, ))); if !direct_send_result && !store_and_forward_send_result { error!( target: LOG_TARGET, "Failed to Send Transaction (TxId: {}) both Directly or via Store and Forward. Pending Transaction \ will be cancelled", self.id ); if let Err(e) = self.resources.output_manager_service.cancel_transaction(self.id).await { error!( target: LOG_TARGET, "Failed to Cancel TX_ID: {} after failed sending attempt with error {:?}", self.id, e ); }; } Ok(SendResult { direct_send_result, store_and_forward_send_result, }) } /// This function contains the logic to wait on a dial and send of a queued message async fn wait_on_dail(&self, send_states: MessageSendStates) -> bool { if send_states.len() == 1 { debug!( target: LOG_TARGET, "Transaction (TxId: {}) Direct Send to {} queued with Message Tag: {:?}", self.id, self.dest_pubkey, send_states[0].tag, ); match send_states.wait_single().await { true => { info!( target: LOG_TARGET, "Direct Send process for TX_ID: {} was successful", self.id ); true }, false => { error!( target: LOG_TARGET, "Direct Send process for TX_ID: {} was unsuccessful and no message was sent", self.id ); false }, } } else { error!( target: LOG_TARGET, "Transaction Send Direct for TxID: {} failed", self.id ); false } } /// Contains all the logic to send the transaction to the recipient via store and forward /// # Arguments /// `msg`: The transaction data message to be sent /// 'send_events': A bool indicating whether we should send events during the operation or not. async fn send_transaction_store_and_forward( &mut self, msg: SingleRoundSenderData, ) -> Result<bool, TransactionServiceProtocolError> { let proto_message = proto::TransactionSenderMessage::single(msg.into()); match self .resources .outbound_message_service .broadcast( NodeDestination::NodeId(Box::new(NodeId::from_key(&self.dest_pubkey).map_err(|e| { TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)) })?)), OutboundEncryption::EncryptFor(Box::new(self.dest_pubkey.clone())), vec![], OutboundDomainMessage::new(TariMessageType::SenderPartialTransaction, proto_message), ) .await { Ok(result) => match result.resolve_ok().await { None => { error!( target: LOG_TARGET, "Transaction Send (TxId: {}) to neighbours for Store and Forward failed", self.id ); Ok(false) }, Some(send_states) if !send_states.is_empty() => { let (successful_sends, _) = send_states.wait_all().await; if !successful_sends.is_empty() { info!( target: LOG_TARGET, "Transaction (TxId: {}) Send to Neighbours for Store and Forward successful with Message \ Tags: {:?}", self.id, successful_sends, ); Ok(true) } else { error!( target: LOG_TARGET, "Transaction Send to Neighbours for Store and Forward for TX_ID: {} was unsuccessful and \ no messages were sent", self.id ); Ok(false) } }, Some(_) => { error!( target: LOG_TARGET, "Transaction Send to Neighbours for Store and Forward for TX_ID: {} was unsuccessful and no \ messages were sent", self.id ); Ok(false) }, }, Err(e) => { error!( target: LOG_TARGET, "Transaction Send (TxId: {}) to neighbours for Store and Forward failed: {:?}", self.id, e ); Ok(false) }, } } /// Contains all the logic to send a transaction to the recipient only directly /// # Arguments /// `msg`: The transaction data message to be sent async fn send_transaction_direct_only( &mut self, msg: SingleRoundSenderData, ) -> Result<bool, TransactionServiceProtocolError> { let proto_message = proto::TransactionSenderMessage::single(msg.clone().into()); info!( target: LOG_TARGET, "Attempting to resend Transaction (TxId: {}) to recipient with Node Id: {} directly only.", self.id, self.dest_pubkey, ); match self .resources .outbound_message_service .send_direct( self.dest_pubkey.clone(), OutboundEncryption::None, OutboundDomainMessage::new(TariMessageType::SenderPartialTransaction, proto_message.clone()), ) .await { Ok(result) => match result.resolve_ok().await { Some(send_states) if send_states.len() == 1 => { if self.wait_on_dail(send_states).await { if let Err(e) = self.resources.db.mark_direct_send_success(self.id).await { error!(target: LOG_TARGET, "Error updating database: {:?}", e); } } }, _ => { error!( target: LOG_TARGET, "Transaction Send Direct for TxID: {} failed", self.id ); return Ok(false); }, }, Err(e) => { error!( target: LOG_TARGET, "Transaction Direct Send for TxID: {} failed: {:?}", self.id, e ); return Ok(false); }, } Ok(true) } async fn send_transaction_finalized_message_store_and_forward( &mut self, msg: proto::TransactionFinalizedMessage, ) -> Result<(), TransactionServiceProtocolError> { match self .resources .outbound_message_service .broadcast( NodeDestination::NodeId(Box::new(NodeId::from_key(&self.dest_pubkey).map_err(|e| { TransactionServiceProtocolError::new(self.id, TransactionServiceError::from(e)) })?)), OutboundEncryption::EncryptFor(Box::new(self.dest_pubkey.clone())), vec![], OutboundDomainMessage::new(TariMessageType::TransactionFinalized, msg.clone()), ) .await { Ok(result) => match result.resolve_ok().await { None => { error!( target: LOG_TARGET, "Sending Finalized Transaction (TxId: {}) to neighbours for Store and Forward failed", self.id ); }, Some(tags) if !tags.is_empty() => { info!( target: LOG_TARGET, "Sending Finalized Transaction (TxId: {}) to Neighbours for Store and Forward successful with \ Message Tags: {:?}", self.id, tags, ); }, Some(_) => { error!( target: LOG_TARGET, "Sending Finalized Transaction to Neighbours for Store and Forward for TX_ID: {} was \ unsuccessful and no messages were sent", self.id ); }, }, Err(e) => { error!( target: LOG_TARGET, "Sending Finalized Transaction (TxId: {}) to neighbours for Store and Forward failed: {:?}", self.id, e ); }, }; Ok(()) } } struct SendResult { direct_send_result: bool, store_and_forward_send_result: bool, }
41.049519
184
0.523004
386635af4ee591f229ba21fccd6d3f4fc2484bd3
2,303
#[cfg(test)] #[cfg(feature = "mosquitto-available")] mod tests { use std::process::{Command, Stdio}; use std::{thread, time}; use assert_cmd::prelude::*; use predicates::prelude::*; #[test] /// Tests that only one instance of `tedge_agent` is running. /// This is done by spawning/running two instances of `tedge_agent` /// expecting the first one to work and the second to fail. fn tedge_agent_check_no_multiple_instances_running() -> Result<(), Box<dyn std::error::Error>> { let _ignore_errors = std::fs::remove_file("/run/lock/tedge_agent.lock"); // running first `tedge_agent` binary let mut agent = Command::cargo_bin(env!("CARGO_PKG_NAME"))? .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()?; // running second `tedge_agent` binary let mut agent_2 = Command::cargo_bin(env!("CARGO_PKG_NAME"))? .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn()?; // trying up to 10 times before breaking out. for _ in 0..10 { if let Ok(Some(code)) = agent.try_wait() { agent.wait_with_output().unwrap().assert().failure().stdout( predicate::str::contains("Another instance of tedge_agent is running."), ); agent_2.kill(); let _ignore_error = std::fs::remove_file("/run/lock/tedge_agent.lock"); return Ok(()); } else if let Ok(Some(code)) = agent_2.try_wait() { agent_2 .wait_with_output() .unwrap() .assert() .failure() .stdout(predicate::str::contains( "Another instance of tedge_agent is running.", )); agent.kill(); let _ignore_error = std::fs::remove_file("/run/lock/tedge_agent.lock"); return Ok(()); } thread::sleep(time::Duration::from_millis(200)); } // cleanup before panic agent.kill(); agent_2.kill(); let _ignore_error = std::fs::remove_file("/run/lock/tedge_agent.lock"); panic!("Agent failed to stop.") } }
37.754098
100
0.534086
91de9f87dfbb3949a7d6195ab6e43d0aeca7fde9
899
extern crate timely; use timely::dataflow::operators::*; fn main() { let iterations = std::env::args().nth(1).unwrap().parse::<u64>().unwrap(); let elements = std::env::args().nth(2).unwrap().parse::<u64>().unwrap(); // initializes and runs a timely dataflow timely::execute_from_args(std::env::args().skip(3), move |worker| { let index = worker.index(); let peers = worker.peers(); worker.dataflow::<u64,_,_>(move |scope| { let (helper, cycle) = scope.feedback(1); (0 .. elements) .filter(move |&x| (x as usize) % peers == index) .to_stream(scope) .concat(&cycle) .exchange(|&x| x) .map_in_place(|x| *x += 1) .branch_when(move |t| t < &iterations).1 .connect_loop(helper); }); }).unwrap(); }
33.296296
78
0.50723
1c197abbf7d8fc50238bb12d4fa57182d812988a
24,564
//! Types and functions related to graphical outputs //! //! This modules provides two main elements. The first is the //! [`OutputHandler`](struct.OutputHandler.html) type, which is a //! [`MultiGlobalHandler`](../environment/trait.MultiGlobalHandler.html) for //! use with the [`init_environment!`](../macro.init_environment.html) macro. It is automatically //! included if you use the [`new_default_environment!`](../macro.new_default_environment.html). //! //! The second is the [`with_output_info`](fn.with_output_info.html) with allows you to //! access the information associated to this output, as an [`OutputInfo`](struct.OutputInfo.html). use std::{ cell::RefCell, rc::{self, Rc}, sync::{self, Arc, Mutex}, }; use wayland_client::{ protocol::{ wl_output::{self, Event, WlOutput}, wl_registry, }, Attached, DispatchData, Main, }; use wayland_protocols::unstable::xdg_output::v1::client::{ zxdg_output_manager_v1::ZxdgOutputManagerV1, zxdg_output_v1::{self, ZxdgOutputV1}, }; pub use wayland_client::protocol::wl_output::{Subpixel, Transform}; /// A possible mode for an output #[derive(Copy, Clone, Debug)] pub struct Mode { /// Number of pixels of this mode in format `(width, height)` /// /// for example `(1920, 1080)` pub dimensions: (i32, i32), /// Refresh rate for this mode, in mHz pub refresh_rate: i32, /// Whether this is the current mode for this output pub is_current: bool, /// Whether this is the preferred mode for this output pub is_preferred: bool, } #[derive(Clone, Debug)] #[non_exhaustive] /// Compiled information about an output pub struct OutputInfo { /// The ID of this output as a global pub id: u32, /// The model name of this output as advertised by the server pub model: String, /// The make name of this output as advertised by the server pub make: String, /// The name of this output as advertised by the server /// /// Each name is unique among all wl_output globals, but if a wl_output /// global is destroyed the same name may be reused later. The names will /// also remain consistent across sessions with the same hardware and /// software configuration. /// /// Examples of names include 'HDMI-A-1', 'WL-1', 'X11-1', etc. However, do /// not assume that the name is a reflection of an underlying DRM connector, /// X11 connection, etc. /// /// Note that this is not filled in by version 3 of the wl_output protocol, /// but it has been proposed for inclusion in version 4. Until then, it is /// only filled in if your environment has an [XdgOutputHandler] global /// handler for [ZxdgOutputManagerV1]. pub name: String, /// The description of this output as advertised by the server /// /// The description is a UTF-8 string with no convention defined for its /// contents. The description is not guaranteed to be unique among all /// wl_output globals. Examples might include 'Foocorp 11" Display' or /// 'Virtual X11 output via :1'. /// /// Note that this is not filled in by version 3 of the wl_output protocol, /// but it has been proposed for inclusion in version 4. Until then, it is /// only filled in if your environment has an [XdgOutputHandler] global /// handler for [ZxdgOutputManagerV1]. pub description: String, /// Location of the top-left corner of this output in compositor /// space /// /// Note that the compositor may decide to always report (0,0) if /// it decides clients are not allowed to know this information. pub location: (i32, i32), /// Physical dimensions of this output, in unspecified units pub physical_size: (i32, i32), /// The subpixel layout for this output pub subpixel: Subpixel, /// The current transformation applied to this output /// /// You can pre-render your buffers taking this information /// into account and advertising it via `wl_buffer.set_tranform` /// for better performances. pub transform: Transform, /// The scaling factor of this output /// /// Any buffer whose scaling factor does not match the one /// of the output it is displayed on will be rescaled accordingly. /// /// For example, a buffer of scaling factor 1 will be doubled in /// size if the output scaling factor is 2. pub scale_factor: i32, /// Possible modes for an output pub modes: Vec<Mode>, /// Has this output been unadvertized by the registry /// /// If this is the case, it has become inert, you might want to /// call its `release()` method if you don't plan to use it any /// longer. pub obsolete: bool, } impl OutputInfo { fn new(id: u32) -> OutputInfo { OutputInfo { id, model: String::new(), make: String::new(), name: String::new(), description: String::new(), location: (0, 0), physical_size: (0, 0), subpixel: Subpixel::Unknown, transform: Transform::Normal, scale_factor: 1, modes: Vec::new(), obsolete: false, } } } type OutputCallback = dyn Fn(WlOutput, &OutputInfo, DispatchData) + Send + Sync; enum OutputData { Ready { info: OutputInfo, callbacks: Vec<sync::Weak<OutputCallback>>, }, Pending { id: u32, has_xdg: bool, events: Vec<Event>, callbacks: Vec<sync::Weak<OutputCallback>>, }, PendingXDG { info: OutputInfo, callbacks: Vec<sync::Weak<OutputCallback>>, }, } type OutputStatusCallback = dyn FnMut(WlOutput, &OutputInfo, DispatchData) + 'static; /// A handler for `wl_output` /// /// This handler can be used for managing `wl_output` in the /// [`init_environment!`](../macro.init_environment.html) macro, and is automatically /// included in [`new_default_environment!`](../macro.new_default_environment.html). /// /// It aggregates the output information and makes it available via the /// [`with_output_info`](fn.with_output_info.html) function. pub struct OutputHandler { outputs: Vec<(u32, Attached<WlOutput>)>, status_listeners: Rc<RefCell<Vec<rc::Weak<RefCell<OutputStatusCallback>>>>>, xdg_listener: Option<rc::Weak<RefCell<XdgOutputHandlerInner>>>, } impl OutputHandler { /// Create a new instance of this handler pub fn new() -> OutputHandler { OutputHandler { outputs: Vec::new(), status_listeners: Rc::new(RefCell::new(Vec::new())), xdg_listener: None, } } } impl crate::environment::MultiGlobalHandler<WlOutput> for OutputHandler { fn created( &mut self, registry: Attached<wl_registry::WlRegistry>, id: u32, version: u32, _: DispatchData, ) { // We currently support wl_output up to version 3 let version = std::cmp::min(version, 3); let output = registry.bind::<WlOutput>(version, id); let has_xdg; if let Some(xdg) = self.xdg_listener.as_ref().and_then(rc::Weak::upgrade) { has_xdg = xdg.borrow_mut().new_xdg_output(&output, &self.status_listeners); } else { has_xdg = false; } if version > 1 { // wl_output.done event was only added at version 2 // In case of an old version 1, we just behave as if it was send at the start output.as_ref().user_data().set_threadsafe(|| { Mutex::new(OutputData::Pending { id, has_xdg, events: vec![], callbacks: vec![] }) }); } else { output.as_ref().user_data().set_threadsafe(|| { Mutex::new(OutputData::Ready { info: OutputInfo::new(id), callbacks: vec![] }) }); } let status_listeners_handle = self.status_listeners.clone(); let xdg_listener_handle = self.xdg_listener.clone(); output.quick_assign(move |output, event, ddata| { process_output_event( output, event, ddata, &status_listeners_handle, &xdg_listener_handle, ) }); self.outputs.push((id, (*output).clone())); } fn removed(&mut self, id: u32, mut ddata: DispatchData) { let status_listeners_handle = &self.status_listeners; let xdg_listener_handle = &self.xdg_listener; self.outputs.retain(|(i, o)| { if *i != id { true } else { make_obsolete(o, ddata.reborrow(), status_listeners_handle, xdg_listener_handle); false } }); } fn get_all(&self) -> Vec<Attached<WlOutput>> { self.outputs.iter().map(|(_, o)| o.clone()).collect() } } fn process_output_event( output: Main<WlOutput>, event: Event, mut ddata: DispatchData, listeners: &Rc<RefCell<Vec<rc::Weak<RefCell<OutputStatusCallback>>>>>, xdg_listener: &Option<rc::Weak<RefCell<XdgOutputHandlerInner>>>, ) { let udata_mutex = output .as_ref() .user_data() .get::<Mutex<OutputData>>() .expect("SCTK: wl_output has invalid UserData"); let mut udata = udata_mutex.lock().unwrap(); if let Event::Done = event { let (id, has_xdg, pending_events, mut callbacks) = match *udata { OutputData::Pending { id, has_xdg, events: ref mut v, callbacks: ref mut cb } => { (id, has_xdg, std::mem::take(v), std::mem::take(cb)) } OutputData::PendingXDG { ref mut info, ref mut callbacks } => { notify(&output, info, ddata.reborrow(), callbacks); notify_status_listeners(&output, info, ddata, listeners); let info = info.clone(); let callbacks = std::mem::take(callbacks); *udata = OutputData::Ready { info, callbacks }; return; } OutputData::Ready { ref mut info, ref mut callbacks } => { // a Done event on an output that is already ready was due to a // status change (which was already merged) notify(&output, info, ddata, callbacks); return; } }; let mut info = OutputInfo::new(id); for evt in pending_events { merge_event(&mut info, evt); } notify(&output, &info, ddata.reborrow(), &mut callbacks); if let Some(xdg) = xdg_listener.as_ref().and_then(rc::Weak::upgrade) { if has_xdg || xdg.borrow_mut().new_xdg_output(&output, listeners) { *udata = OutputData::PendingXDG { info, callbacks }; return; } } notify_status_listeners(&output, &info, ddata, listeners); *udata = OutputData::Ready { info, callbacks }; } else { match *udata { OutputData::Pending { events: ref mut v, .. } => v.push(event), OutputData::PendingXDG { ref mut info, .. } | OutputData::Ready { ref mut info, .. } => { merge_event(info, event); } } } } fn make_obsolete( output: &Attached<WlOutput>, mut ddata: DispatchData, listeners: &RefCell<Vec<rc::Weak<RefCell<OutputStatusCallback>>>>, xdg_listener: &Option<rc::Weak<RefCell<XdgOutputHandlerInner>>>, ) { let udata_mutex = output .as_ref() .user_data() .get::<Mutex<OutputData>>() .expect("SCTK: wl_output has invalid UserData"); let mut udata = udata_mutex.lock().unwrap(); if let Some(xdg) = xdg_listener.as_ref().and_then(rc::Weak::upgrade) { xdg.borrow_mut().destroy_xdg_output(output); } let (id, mut callbacks) = match *udata { OutputData::PendingXDG { ref mut info, ref mut callbacks } | OutputData::Ready { ref mut info, ref mut callbacks } => { info.obsolete = true; notify(output, info, ddata.reborrow(), callbacks); notify_status_listeners(output, info, ddata, listeners); return; } OutputData::Pending { id, callbacks: ref mut cb, .. } => (id, std::mem::take(cb)), }; let mut info = OutputInfo::new(id); info.obsolete = true; notify(output, &info, ddata.reborrow(), &mut callbacks); notify_status_listeners(output, &info, ddata, listeners); *udata = OutputData::Ready { info, callbacks }; } fn merge_event(info: &mut OutputInfo, event: Event) { match event { Event::Geometry { x, y, physical_width, physical_height, subpixel, model, make, transform, } => { info.location = (x, y); info.physical_size = (physical_width, physical_height); info.subpixel = subpixel; info.transform = transform; info.model = model; info.make = make; } Event::Scale { factor } => { info.scale_factor = factor; } Event::Mode { width, height, refresh, flags } => { let mut found = false; if let Some(mode) = info .modes .iter_mut() .find(|m| m.dimensions == (width, height) && m.refresh_rate == refresh) { // this mode already exists, update it mode.is_preferred = flags.contains(wl_output::Mode::Preferred); mode.is_current = flags.contains(wl_output::Mode::Current); found = true; } if !found { // otherwise, add it info.modes.push(Mode { dimensions: (width, height), refresh_rate: refresh, is_preferred: flags.contains(wl_output::Mode::Preferred), is_current: flags.contains(wl_output::Mode::Current), }) } } // ignore all other events _ => (), } } fn notify( output: &WlOutput, info: &OutputInfo, mut ddata: DispatchData, callbacks: &mut Vec<sync::Weak<OutputCallback>>, ) { callbacks.retain(|weak| { if let Some(arc) = sync::Weak::upgrade(weak) { (*arc)(output.clone(), info, ddata.reborrow()); true } else { false } }); } fn notify_status_listeners( output: &WlOutput, info: &OutputInfo, mut ddata: DispatchData, listeners: &RefCell<Vec<rc::Weak<RefCell<OutputStatusCallback>>>>, ) { // Notify the callbacks listening for new outputs listeners.borrow_mut().retain(|lst| { if let Some(cb) = rc::Weak::upgrade(lst) { (&mut *cb.borrow_mut())(output.clone(), info, ddata.reborrow()); true } else { false } }) } /// Access the info associated with this output /// /// The provided closure is given the [`OutputInfo`](struct.OutputInfo.html) as argument, /// and its return value is returned from this function. /// /// If the provided `WlOutput` has not yet been initialized or is not managed by SCTK, `None` is returned. /// /// If the output has been removed by the compositor, the `obsolete` field of the `OutputInfo` /// will be set to `true`. This handler will not automatically detroy the output by calling its /// `release` method, to avoid interfering with your logic. pub fn with_output_info<T, F: FnOnce(&OutputInfo) -> T>(output: &WlOutput, f: F) -> Option<T> { if let Some(udata_mutex) = output.as_ref().user_data().get::<Mutex<OutputData>>() { let udata = udata_mutex.lock().unwrap(); match *udata { OutputData::PendingXDG { ref info, .. } | OutputData::Ready { ref info, .. } => { Some(f(info)) } OutputData::Pending { .. } => None, } } else { None } } /// Add a listener to this output /// /// The provided closure will be called whenever a property of the output changes, /// including when it is removed by the compositor (in this case it'll be marked as /// obsolete). /// /// The returned [`OutputListener`](struct.OutputListener) keeps your callback alive, /// dropping it will disable the callback and free the closure. pub fn add_output_listener<F: Fn(WlOutput, &OutputInfo, DispatchData) + Send + Sync + 'static>( output: &WlOutput, f: F, ) -> OutputListener { let arc = Arc::new(f) as Arc<_>; if let Some(udata_mutex) = output.as_ref().user_data().get::<Mutex<OutputData>>() { let mut udata = udata_mutex.lock().unwrap(); match *udata { OutputData::Pending { ref mut callbacks, .. } | OutputData::PendingXDG { ref mut callbacks, .. } | OutputData::Ready { ref mut callbacks, .. } => { callbacks.push(Arc::downgrade(&arc)); } } } OutputListener { _cb: arc } } /// A handle to an output listener callback /// /// Dropping it disables the associated callback and frees the closure. pub struct OutputListener { _cb: Arc<dyn Fn(WlOutput, &OutputInfo, DispatchData) + Send + Sync + 'static>, } /// A handle to an output status callback /// /// Dropping it disables the associated callback and frees the closure. pub struct OutputStatusListener { _cb: Rc<RefCell<OutputStatusCallback>>, } /// Trait representing the OutputHandler functions /// /// Implementing this trait on your inner environment struct used with the /// [`environment!`](../macro.environment.html) by delegating it to its /// [`OutputHandler`](struct.OutputHandler.html) field will make available the output-associated /// method on your [`Environment`](../environment/struct.Environment.html). pub trait OutputHandling { /// Insert a listener for output creation and removal events fn listen<F: FnMut(WlOutput, &OutputInfo, DispatchData) + 'static>( &mut self, f: F, ) -> OutputStatusListener; } impl OutputHandling for OutputHandler { fn listen<F: FnMut(WlOutput, &OutputInfo, DispatchData) + 'static>( &mut self, f: F, ) -> OutputStatusListener { let rc = Rc::new(RefCell::new(f)) as Rc<_>; self.status_listeners.borrow_mut().push(Rc::downgrade(&rc)); OutputStatusListener { _cb: rc } } } impl<E: OutputHandling> crate::environment::Environment<E> { /// Insert a new listener for outputs /// /// The provided closure will be invoked whenever a `wl_output` is created or removed. /// /// Note that if outputs already exist when this callback is setup, it'll not be invoked on them. /// For you to be notified of them as well, you need to first process them manually by calling /// `.get_all_outputs()`. /// /// The returned [`OutputStatusListener`](../output/struct.OutputStatusListener.hmtl) keeps your /// callback alive, dropping it will disable it. #[must_use = "the returned OutputStatusListener keeps your callback alive, dropping it will disable it"] pub fn listen_for_outputs<F: FnMut(WlOutput, &OutputInfo, DispatchData) + 'static>( &self, f: F, ) -> OutputStatusListener { self.with_inner(move |inner| OutputHandling::listen(inner, f)) } } impl<E: crate::environment::MultiGlobalHandler<WlOutput>> crate::environment::Environment<E> { /// Shorthand method to retrieve the list of outputs pub fn get_all_outputs(&self) -> Vec<WlOutput> { self.get_all_globals::<WlOutput>().into_iter().map(|o| o.detach()).collect() } } /// A handler for `zxdg_output_manager_v1` /// /// This handler adds additional information to the OutputInfo struct that is /// available through the xdg_output interface. Because this requires binding /// the two handlers together when they are being created, it does not work with /// [`new_default_environment!`](../macro.new_default_environment.html); you /// must use [`default_environment!`](../macro.default_environment.html) and /// create the [OutputHandler] outside the constructor. /// /// ```no_compile /// let (sctk_outputs, sctk_xdg_out) = smithay_client_toolkit::output::XdgOutputHandler::new_output_handlers(); /// /// let env = smithay_client_toolkit::environment::Environment::new(&wl_display, &mut wl_queue, Globals { /// sctk_compositor: SimpleGlobal::new(), /// sctk_shm: smithay_client_toolkit::shm::ShmHandler::new(), /// sctk_seats : smithay_client_toolkit::seat::SeatHandler::new(), /// sctk_shell : smithay_client_toolkit::shell::ShellHandler::new(), /// sctk_outputs, /// sctk_xdg_out, /// // ... /// })?; /// /// ``` pub struct XdgOutputHandler { inner: Rc<RefCell<XdgOutputHandlerInner>>, } struct XdgOutputHandlerInner { xdg_manager: Option<Attached<ZxdgOutputManagerV1>>, outputs: Vec<(WlOutput, Attached<ZxdgOutputV1>)>, } impl XdgOutputHandler { /// Create a new instance of this handler bound to the given OutputHandler. pub fn new(output_handler: &mut OutputHandler) -> Self { let inner = Rc::new(RefCell::new(XdgOutputHandlerInner { xdg_manager: None, outputs: Vec::new() })); output_handler.xdg_listener = Some(Rc::downgrade(&inner)); XdgOutputHandler { inner } } /// Helper function to create a bound pair of OutputHandler and XdgOutputHandler. pub fn new_output_handlers() -> (OutputHandler, Self) { let mut oh = OutputHandler::new(); let xh = XdgOutputHandler::new(&mut oh); (oh, xh) } } impl XdgOutputHandlerInner { fn new_xdg_output( &mut self, output: &WlOutput, listeners: &Rc<RefCell<Vec<rc::Weak<RefCell<OutputStatusCallback>>>>>, ) -> bool { if let Some(xdg_manager) = &self.xdg_manager { let xdg_main = xdg_manager.get_xdg_output(output); let wl_out = output.clone(); let listeners = listeners.clone(); xdg_main.quick_assign(move |_xdg_out, event, ddata| { process_xdg_event(&wl_out, event, ddata, &listeners) }); self.outputs.push((output.clone(), xdg_main.into())); true } else { false } } fn destroy_xdg_output(&mut self, output: &WlOutput) { self.outputs.retain(|(out, xdg_out)| { if out.as_ref().is_alive() && out != output { true } else { xdg_out.destroy(); false } }); } } fn process_xdg_event( wl_out: &WlOutput, event: zxdg_output_v1::Event, mut ddata: DispatchData, listeners: &RefCell<Vec<rc::Weak<RefCell<OutputStatusCallback>>>>, ) { use zxdg_output_v1::Event; let udata_mutex = wl_out .as_ref() .user_data() .get::<Mutex<OutputData>>() .expect("SCTK: wl_output has invalid UserData"); let mut udata = udata_mutex.lock().unwrap(); let (info, callbacks, pending) = match &mut *udata { OutputData::Ready { info, callbacks } => (info, callbacks, false), OutputData::PendingXDG { info, callbacks } => (info, callbacks, true), OutputData::Pending { .. } => unreachable!(), }; match event { Event::Name { name } => { info.name = name; } Event::Description { description } => { info.description = description; } Event::Done => { notify(wl_out, info, ddata.reborrow(), callbacks); if pending { notify_status_listeners(wl_out, info, ddata, listeners); let info = info.clone(); let callbacks = std::mem::take(callbacks); *udata = OutputData::Ready { info, callbacks }; } } _ => (), } } impl crate::environment::GlobalHandler<ZxdgOutputManagerV1> for XdgOutputHandler { fn created( &mut self, registry: Attached<wl_registry::WlRegistry>, id: u32, version: u32, _: DispatchData, ) { let version = std::cmp::min(version, 3); let mut inner = self.inner.borrow_mut(); let xdg_manager: Main<ZxdgOutputManagerV1> = registry.bind(version, id); inner.xdg_manager = Some(xdg_manager.into()); } fn get(&self) -> Option<Attached<ZxdgOutputManagerV1>> { let inner = self.inner.borrow(); inner.xdg_manager.clone() } }
36.717489
112
0.607596
26b1f9f5b40d46dea7d6fc02b9f80f61d934c2d9
2,294
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::DEV_ADDR { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = "Possible values of the field `dev_addr`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DEV_ADDRR { #[doc = r" Reserved"] _Reserved(u8), } impl DEV_ADDRR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { DEV_ADDRR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> DEV_ADDRR { match value { i => DEV_ADDRR::_Reserved(i), } } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:6 - USB Device Address"] #[inline] pub fn dev_addr(&self) -> DEV_ADDRR { DEV_ADDRR::_from({ const MASK: u8 = 127; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } }
23.649485
59
0.501744
ed890ff30806d9f3cc5cc28df1304d48d6017a25
5,248
//! This code is needed in order to support a channel that can receive with a //! timeout. use Builder; use mpmc::Queue; use wheel::{Token, Wheel}; use futures::task::Task; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; use std::thread::{self, Thread}; #[derive(Clone)] pub struct Worker { tx: Arc<Tx>, } /// Communicate with the timer thread struct Tx { chan: Arc<Chan>, worker: Thread, tolerance: Duration, max_timeout: Duration, } struct Chan { run: AtomicBool, set_timeouts: SetQueue, mod_timeouts: ModQueue, } /// Messages sent on the `set_timeouts` exchange struct SetTimeout(Instant, Task); /// Messages sent on the `mod_timeouts` queue enum ModTimeout { Move(Token, Instant, Task), Cancel(Token, Instant), } type SetQueue = Queue<SetTimeout, Token>; type ModQueue = Queue<ModTimeout, ()>; impl Worker { /// Spawn a worker, returning a handle to allow communication pub fn spawn(mut wheel: Wheel, builder: Builder) -> Worker { let tolerance = builder.get_tick_duration(); let max_timeout = builder.get_max_timeout(); let capacity = builder.get_channel_capacity(); // Assert that the wheel has at least capacity available timeouts assert!(wheel.available() >= capacity); let chan = Arc::new(Chan { run: AtomicBool::new(true), set_timeouts: Queue::with_capacity(capacity, || wheel.reserve().unwrap()), mod_timeouts: Queue::with_capacity(capacity, || ()), }); let chan2 = chan.clone(); // Spawn the worker thread let t = thread::Builder::new() .name(builder.thread_name.unwrap_or_else(|| "tokio-timer".to_owned())) .spawn(move || run(chan2, wheel)) .expect("thread::spawn"); Worker { tx: Arc::new(Tx { chan: chan, worker: t.thread().clone(), tolerance: tolerance, max_timeout: max_timeout, }), } } /// The earliest a timeout can fire before the requested `Instance` pub fn tolerance(&self) -> &Duration { &self.tx.tolerance } pub fn max_timeout(&self) -> &Duration { &self.tx.max_timeout } /// Set a timeout pub fn set_timeout(&self, when: Instant, task: Task) -> Result<Token, Task> { self.tx.chan.set_timeouts.push(SetTimeout(when, task)) .and_then(|ret| { // Unpark the timer thread self.tx.worker.unpark(); Ok(ret) }) .map_err(|SetTimeout(_, task)| task) } /// Move a timeout pub fn move_timeout(&self, token: Token, when: Instant, task: Task) -> Result<(), Task> { self.tx.chan.mod_timeouts.push(ModTimeout::Move(token, when, task)) .and_then(|ret| { self.tx.worker.unpark(); Ok(ret) }) .map_err(|v| { match v { ModTimeout::Move(_, _, task) => task, _ => unreachable!(), } }) } /// Cancel a timeout pub fn cancel_timeout(&self, token: Token, instant: Instant) { // The result here is ignored because: // // 1) this fn is only called when the timeout is dropping, so nothing // can be done with the result // 2) Not being able to cancel a timeout is not a huge deal and only // results in a spurious wakeup. // let _ = self.tx.chan.mod_timeouts.push(ModTimeout::Cancel(token, instant)); } } fn run(chan: Arc<Chan>, mut wheel: Wheel) { while chan.run.load(Ordering::Relaxed) { let now = Instant::now(); // Fire off all expired timeouts while let Some(task) = wheel.poll(now) { task.notify(); } // As long as the wheel has capacity to manage new timeouts, read off // of the queue. while let Some(token) = wheel.reserve() { match chan.set_timeouts.pop(token) { Ok((SetTimeout(when, task), token)) => { wheel.set_timeout(token, when, task); } Err(token) => { wheel.release(token); break; } } } loop { match chan.mod_timeouts.pop(()) { Ok((ModTimeout::Move(token, when, task), _)) => { wheel.move_timeout(token, when, task); } Ok((ModTimeout::Cancel(token, when), _)) => { wheel.cancel(token, when); } Err(_) => break, } } // Update `now` in case the tick was extra long for some reason let now = Instant::now(); if let Some(next) = wheel.next_timeout() { if next > now { thread::park_timeout(next - now); } } else { thread::park(); } } } impl Drop for Tx { fn drop(&mut self) { self.chan.run.store(false, Ordering::Relaxed); self.worker.unpark(); } }
28.994475
93
0.536204
7114aa3e434d3e760ea914e72f704cd7b7993ac0
1,679
use rustc_serialize::json; use client::Client; use std::io::Read; pub struct UserService { pub client: Client, } #[derive(RustcDecodable, RustcEncodable, Debug)] pub struct User { pub login: String, pub id: i32, pub avatar_url: String, pub gravatar_id: String, pub url: String, pub html_url: String, pub followers_url: String, pub following_url: String, pub gists_url: String, pub starred_url: String, pub subscriptions_url: String, pub organizations_url: String, pub repos_url: String, pub events_url: String, pub received_events_url: String, pub site_admin: bool, pub name: String, pub company: String, pub blog: String, pub location: String, pub email: String, pub hireable: bool, pub bio: Option<String>, pub public_repos: i32, pub public_gists: i32, pub followers: i32, pub following: i32, pub created_at: String, pub updated_at: String, } impl UserService { pub fn new(client: Client) -> UserService { UserService { client: client, } } pub fn get_user(&mut self, user_name: String) -> User { let res = self.client.request(format!("{}{}", "/users/", user_name)); let mut resp = res.unwrap(); let mut content = String::new(); resp.read_to_string(&mut content); let u: User = json::decode(&content).unwrap(); return u; } } #[test] fn get_user() { let mut username = String::new(); username.push_str("ttacon"); let mut us = UserService::new(Client::new(String::new())); let user = us.get_user(username); println!("user: {:?}", user); }
23.985714
77
0.624777
142eba1b72332f83486f9b638c0b368b95b6d8e5
92,818
//! The Rust abstract syntax tree module. //! //! This module contains common structures forming the language AST. //! Two main entities in the module are [`Item`] (which represents an AST element with //! additional metadata), and [`ItemKind`] (which represents a concrete type and contains //! information specific to the type of the item). //! //! Other module items worth mentioning: //! - [`Ty`] and [`TyKind`]: A parsed Rust type. //! - [`Expr`] and [`ExprKind`]: A parsed Rust expression. //! - [`Pat`] and [`PatKind`]: A parsed Rust pattern. Patterns are often dual to expressions. //! - [`Stmt`] and [`StmtKind`]: An executable action that does not return a value. //! - [`FnDecl`], [`FnHeader`] and [`Param`]: Metadata associated with a function declaration. //! - [`Generics`], [`GenericParam`], [`WhereClause`]: Metadata associated with generic parameters. //! - [`EnumDef`] and [`Variant`]: Enum declaration. //! - [`Lit`] and [`LitKind`]: Literal expressions. //! - [`MacroDef`], [`MacStmtStyle`], [`MacCall`], [`MacDelimiter`]: Macro definition and invocation. //! - [`Attribute`]: Metadata associated with item. //! - [`UnOp`], [`BinOp`], and [`BinOpKind`]: Unary and binary operators. pub use crate::util::parser::ExprPrecedence; pub use GenericArgs::*; pub use UnsafeSource::*; use crate::ptr::P; use crate::token::{self, CommentKind, Delimiter}; use crate::tokenstream::{DelimSpan, LazyTokenStream, TokenStream}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::sync::Lrc; use rustc_data_structures::thin_vec::ThinVec; use rustc_macros::HashStable_Generic; use rustc_serialize::{self, Decoder, Encoder}; use rustc_span::source_map::{respan, Spanned}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; use std::cmp::Ordering; use std::convert::TryFrom; use std::fmt; use std::mem; #[cfg(test)] mod tests; /// A "Label" is an identifier of some point in sources, /// e.g. in the following code: /// /// ```rust /// 'outer: loop { /// break 'outer; /// } /// ``` /// /// `'outer` is a label. #[derive(Clone, Encodable, Decodable, Copy, HashStable_Generic, Eq, PartialEq)] pub struct Label { pub ident: Ident, } impl fmt::Debug for Label { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "label({:?})", self.ident) } } /// A "Lifetime" is an annotation of the scope in which variable /// can be used, e.g. `'a` in `&'a i32`. #[derive(Clone, Encodable, Decodable, Copy)] pub struct Lifetime { pub id: NodeId, pub ident: Ident, } impl fmt::Debug for Lifetime { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "lifetime({}: {})", self.id, self) } } impl fmt::Display for Lifetime { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.ident.name) } } /// A "Path" is essentially Rust's notion of a name. /// /// It's represented as a sequence of identifiers, /// along with a bunch of supporting information. /// /// E.g., `std::cmp::PartialEq`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct Path { pub span: Span, /// The segments in the path: the things separated by `::`. /// Global paths begin with `kw::PathRoot`. pub segments: Vec<PathSegment>, pub tokens: Option<LazyTokenStream>, } impl PartialEq<Symbol> for Path { #[inline] fn eq(&self, symbol: &Symbol) -> bool { self.segments.len() == 1 && { self.segments[0].ident.name == *symbol } } } impl<CTX: rustc_span::HashStableContext> HashStable<CTX> for Path { fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { self.segments.len().hash_stable(hcx, hasher); for segment in &self.segments { segment.ident.hash_stable(hcx, hasher); } } } impl Path { // Convert a span and an identifier to the corresponding // one-segment path. pub fn from_ident(ident: Ident) -> Path { Path { segments: vec![PathSegment::from_ident(ident)], span: ident.span, tokens: None } } pub fn is_global(&self) -> bool { !self.segments.is_empty() && self.segments[0].ident.name == kw::PathRoot } } /// A segment of a path: an identifier, an optional lifetime, and a set of types. /// /// E.g., `std`, `String` or `Box<T>`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct PathSegment { /// The identifier portion of this path segment. pub ident: Ident, pub id: NodeId, /// Type/lifetime parameters attached to this path. They come in /// two flavors: `Path<A,B,C>` and `Path(A,B) -> C`. /// `None` means that no parameter list is supplied (`Path`), /// `Some` means that parameter list is supplied (`Path<X, Y>`) /// but it can be empty (`Path<>`). /// `P` is used as a size optimization for the common case with no parameters. pub args: Option<P<GenericArgs>>, } impl PathSegment { pub fn from_ident(ident: Ident) -> Self { PathSegment { ident, id: DUMMY_NODE_ID, args: None } } pub fn path_root(span: Span) -> Self { PathSegment::from_ident(Ident::new(kw::PathRoot, span)) } pub fn span(&self) -> Span { match &self.args { Some(args) => self.ident.span.to(args.span()), None => self.ident.span, } } } /// The arguments of a path segment. /// /// E.g., `<A, B>` as in `Foo<A, B>` or `(A, B)` as in `Foo(A, B)`. #[derive(Clone, Encodable, Decodable, Debug)] pub enum GenericArgs { /// The `<'a, A, B, C>` in `foo::bar::baz::<'a, A, B, C>`. AngleBracketed(AngleBracketedArgs), /// The `(A, B)` and `C` in `Foo(A, B) -> C`. Parenthesized(ParenthesizedArgs), } impl GenericArgs { pub fn is_angle_bracketed(&self) -> bool { matches!(self, AngleBracketed(..)) } pub fn span(&self) -> Span { match *self { AngleBracketed(ref data) => data.span, Parenthesized(ref data) => data.span, } } } /// Concrete argument in the sequence of generic args. #[derive(Clone, Encodable, Decodable, Debug)] pub enum GenericArg { /// `'a` in `Foo<'a>` Lifetime(Lifetime), /// `Bar` in `Foo<Bar>` Type(P<Ty>), /// `1` in `Foo<1>` Const(AnonConst), } impl GenericArg { pub fn span(&self) -> Span { match self { GenericArg::Lifetime(lt) => lt.ident.span, GenericArg::Type(ty) => ty.span, GenericArg::Const(ct) => ct.value.span, } } } /// A path like `Foo<'a, T>`. #[derive(Clone, Encodable, Decodable, Debug, Default)] pub struct AngleBracketedArgs { /// The overall span. pub span: Span, /// The comma separated parts in the `<...>`. pub args: Vec<AngleBracketedArg>, } /// Either an argument for a parameter e.g., `'a`, `Vec<u8>`, `0`, /// or a constraint on an associated item, e.g., `Item = String` or `Item: Bound`. #[derive(Clone, Encodable, Decodable, Debug)] pub enum AngleBracketedArg { /// Argument for a generic parameter. Arg(GenericArg), /// Constraint for an associated item. Constraint(AssocConstraint), } impl AngleBracketedArg { pub fn span(&self) -> Span { match self { AngleBracketedArg::Arg(arg) => arg.span(), AngleBracketedArg::Constraint(constraint) => constraint.span, } } } impl Into<Option<P<GenericArgs>>> for AngleBracketedArgs { fn into(self) -> Option<P<GenericArgs>> { Some(P(GenericArgs::AngleBracketed(self))) } } impl Into<Option<P<GenericArgs>>> for ParenthesizedArgs { fn into(self) -> Option<P<GenericArgs>> { Some(P(GenericArgs::Parenthesized(self))) } } /// A path like `Foo(A, B) -> C`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct ParenthesizedArgs { /// ```text /// Foo(A, B) -> C /// ^^^^^^^^^^^^^^ /// ``` pub span: Span, /// `(A, B)` pub inputs: Vec<P<Ty>>, /// ```text /// Foo(A, B) -> C /// ^^^^^^ /// ``` pub inputs_span: Span, /// `C` pub output: FnRetTy, } impl ParenthesizedArgs { pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs { let args = self .inputs .iter() .cloned() .map(|input| AngleBracketedArg::Arg(GenericArg::Type(input))) .collect(); AngleBracketedArgs { span: self.inputs_span, args } } } pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID}; /// A modifier on a bound, e.g., `?Trait` or `~const Trait`. /// /// Negative bounds should also be handled here. #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)] pub enum TraitBoundModifier { /// No modifiers None, /// `?Trait` Maybe, /// `~const Trait` MaybeConst, /// `~const ?Trait` // // This parses but will be rejected during AST validation. MaybeConstMaybe, } /// The AST represents all type param bounds as types. /// `typeck::collect::compute_bounds` matches these against /// the "special" built-in traits (see `middle::lang_items`) and /// detects `Copy`, `Send` and `Sync`. #[derive(Clone, Encodable, Decodable, Debug)] pub enum GenericBound { Trait(PolyTraitRef, TraitBoundModifier), Outlives(Lifetime), } impl GenericBound { pub fn span(&self) -> Span { match self { GenericBound::Trait(ref t, ..) => t.span, GenericBound::Outlives(ref l) => l.ident.span, } } } pub type GenericBounds = Vec<GenericBound>; /// Specifies the enforced ordering for generic parameters. In the future, /// if we wanted to relax this order, we could override `PartialEq` and /// `PartialOrd`, to allow the kinds to be unordered. #[derive(Hash, Clone, Copy)] pub enum ParamKindOrd { Lifetime, Type, Const, // `Infer` is not actually constructed directly from the AST, but is implicitly constructed // during HIR lowering, and `ParamKindOrd` will implicitly order inferred variables last. Infer, } impl Ord for ParamKindOrd { fn cmp(&self, other: &Self) -> Ordering { use ParamKindOrd::*; let to_int = |v| match v { Lifetime => 0, Infer | Type | Const => 1, }; to_int(*self).cmp(&to_int(*other)) } } impl PartialOrd for ParamKindOrd { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl PartialEq for ParamKindOrd { fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal } } impl Eq for ParamKindOrd {} impl fmt::Display for ParamKindOrd { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ParamKindOrd::Lifetime => "lifetime".fmt(f), ParamKindOrd::Type => "type".fmt(f), ParamKindOrd::Const { .. } => "const".fmt(f), ParamKindOrd::Infer => "infer".fmt(f), } } } #[derive(Clone, Encodable, Decodable, Debug)] pub enum GenericParamKind { /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`). Lifetime, Type { default: Option<P<Ty>>, }, Const { ty: P<Ty>, /// Span of the `const` keyword. kw_span: Span, /// Optional default value for the const generic param default: Option<AnonConst>, }, } #[derive(Clone, Encodable, Decodable, Debug)] pub struct GenericParam { pub id: NodeId, pub ident: Ident, pub attrs: AttrVec, pub bounds: GenericBounds, pub is_placeholder: bool, pub kind: GenericParamKind, pub colon_span: Option<Span>, } impl GenericParam { pub fn span(&self) -> Span { match &self.kind { GenericParamKind::Lifetime | GenericParamKind::Type { default: None } => { self.ident.span } GenericParamKind::Type { default: Some(ty) } => self.ident.span.to(ty.span), GenericParamKind::Const { kw_span, default: Some(default), .. } => { kw_span.to(default.value.span) } GenericParamKind::Const { kw_span, default: None, ty } => kw_span.to(ty.span), } } } /// Represents lifetime, type and const parameters attached to a declaration of /// a function, enum, trait, etc. #[derive(Clone, Encodable, Decodable, Debug)] pub struct Generics { pub params: Vec<GenericParam>, pub where_clause: WhereClause, pub span: Span, } impl Default for Generics { /// Creates an instance of `Generics`. fn default() -> Generics { Generics { params: Vec::new(), where_clause: WhereClause { has_where_token: false, predicates: Vec::new(), span: DUMMY_SP, }, span: DUMMY_SP, } } } /// A where-clause in a definition. #[derive(Clone, Encodable, Decodable, Debug)] pub struct WhereClause { /// `true` if we ate a `where` token: this can happen /// if we parsed no predicates (e.g. `struct Foo where {}`). /// This allows us to pretty-print accurately. pub has_where_token: bool, pub predicates: Vec<WherePredicate>, pub span: Span, } /// A single predicate in a where-clause. #[derive(Clone, Encodable, Decodable, Debug)] pub enum WherePredicate { /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`). BoundPredicate(WhereBoundPredicate), /// A lifetime predicate (e.g., `'a: 'b + 'c`). RegionPredicate(WhereRegionPredicate), /// An equality predicate (unsupported). EqPredicate(WhereEqPredicate), } impl WherePredicate { pub fn span(&self) -> Span { match self { WherePredicate::BoundPredicate(p) => p.span, WherePredicate::RegionPredicate(p) => p.span, WherePredicate::EqPredicate(p) => p.span, } } } /// A type bound. /// /// E.g., `for<'c> Foo: Send + Clone + 'c`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct WhereBoundPredicate { pub span: Span, /// Any generics from a `for` binding. pub bound_generic_params: Vec<GenericParam>, /// The type being bounded. pub bounded_ty: P<Ty>, /// Trait and lifetime bounds (`Clone + Send + 'static`). pub bounds: GenericBounds, } /// A lifetime predicate. /// /// E.g., `'a: 'b + 'c`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct WhereRegionPredicate { pub span: Span, pub lifetime: Lifetime, pub bounds: GenericBounds, } /// An equality predicate (unsupported). /// /// E.g., `T = int`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct WhereEqPredicate { pub id: NodeId, pub span: Span, pub lhs_ty: P<Ty>, pub rhs_ty: P<Ty>, } #[derive(Clone, Encodable, Decodable, Debug)] pub struct Crate { pub attrs: Vec<Attribute>, pub items: Vec<P<Item>>, pub spans: ModSpans, /// Must be equal to `CRATE_NODE_ID` after the crate root is expanded, but may hold /// expansion placeholders or an unassigned value (`DUMMY_NODE_ID`) before that. pub id: NodeId, pub is_placeholder: bool, } /// Possible values inside of compile-time attribute lists. /// /// E.g., the '..' in `#[name(..)]`. #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)] pub enum NestedMetaItem { /// A full MetaItem, for recursive meta items. MetaItem(MetaItem), /// A literal. /// /// E.g., `"foo"`, `64`, `true`. Literal(Lit), } /// A spanned compile-time attribute item. /// /// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`. #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)] pub struct MetaItem { pub path: Path, pub kind: MetaItemKind, pub span: Span, } /// A compile-time attribute item. /// /// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`. #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)] pub enum MetaItemKind { /// Word meta item. /// /// E.g., `test` as in `#[test]`. Word, /// List meta item. /// /// E.g., `derive(..)` as in `#[derive(..)]`. List(Vec<NestedMetaItem>), /// Name value meta item. /// /// E.g., `feature = "foo"` as in `#[feature = "foo"]`. NameValue(Lit), } /// A block (`{ .. }`). /// /// E.g., `{ .. }` as in `fn foo() { .. }`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct Block { /// The statements in the block. pub stmts: Vec<Stmt>, pub id: NodeId, /// Distinguishes between `unsafe { ... }` and `{ ... }`. pub rules: BlockCheckMode, pub span: Span, pub tokens: Option<LazyTokenStream>, /// The following *isn't* a parse error, but will cause multiple errors in following stages. /// ```compile_fail /// let x = { /// foo: var /// }; /// ``` /// #34255 pub could_be_bare_literal: bool, } /// A match pattern. /// /// Patterns appear in match statements and some other contexts, such as `let` and `if let`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct Pat { pub id: NodeId, pub kind: PatKind, pub span: Span, pub tokens: Option<LazyTokenStream>, } impl Pat { /// Attempt reparsing the pattern as a type. /// This is intended for use by diagnostics. pub fn to_ty(&self) -> Option<P<Ty>> { let kind = match &self.kind { // In a type expression `_` is an inference variable. PatKind::Wild => TyKind::Infer, // An IDENT pattern with no binding mode would be valid as path to a type. E.g. `u32`. PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None) => { TyKind::Path(None, Path::from_ident(*ident)) } PatKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()), PatKind::MacCall(mac) => TyKind::MacCall(mac.clone()), // `&mut? P` can be reinterpreted as `&mut? T` where `T` is `P` reparsed as a type. PatKind::Ref(pat, mutbl) => { pat.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))? } // A slice/array pattern `[P]` can be reparsed as `[T]`, an unsized array, // when `P` can be reparsed as a type `T`. PatKind::Slice(pats) if pats.len() == 1 => pats[0].to_ty().map(TyKind::Slice)?, // A tuple pattern `(P0, .., Pn)` can be reparsed as `(T0, .., Tn)` // assuming `T0` to `Tn` are all syntactically valid as types. PatKind::Tuple(pats) => { let mut tys = Vec::with_capacity(pats.len()); // FIXME(#48994) - could just be collected into an Option<Vec> for pat in pats { tys.push(pat.to_ty()?); } TyKind::Tup(tys) } _ => return None, }; Some(P(Ty { kind, id: self.id, span: self.span, tokens: None })) } /// Walk top-down and call `it` in each place where a pattern occurs /// starting with the root pattern `walk` is called on. If `it` returns /// false then we will descend no further but siblings will be processed. pub fn walk(&self, it: &mut impl FnMut(&Pat) -> bool) { if !it(self) { return; } match &self.kind { // Walk into the pattern associated with `Ident` (if any). PatKind::Ident(_, _, Some(p)) => p.walk(it), // Walk into each field of struct. PatKind::Struct(_, _, fields, _) => fields.iter().for_each(|field| field.pat.walk(it)), // Sequence of patterns. PatKind::TupleStruct(_, _, s) | PatKind::Tuple(s) | PatKind::Slice(s) | PatKind::Or(s) => s.iter().for_each(|p| p.walk(it)), // Trivial wrappers over inner patterns. PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it), // These patterns do not contain subpatterns, skip. PatKind::Wild | PatKind::Rest | PatKind::Lit(_) | PatKind::Range(..) | PatKind::Ident(..) | PatKind::Path(..) | PatKind::MacCall(_) => {} } } /// Is this a `..` pattern? pub fn is_rest(&self) -> bool { matches!(self.kind, PatKind::Rest) } } /// A single field in a struct pattern. /// /// Patterns like the fields of `Foo { x, ref y, ref mut z }` /// are treated the same as `x: x, y: ref y, z: ref mut z`, /// except when `is_shorthand` is true. #[derive(Clone, Encodable, Decodable, Debug)] pub struct PatField { /// The identifier for the field. pub ident: Ident, /// The pattern the field is destructured to. pub pat: P<Pat>, pub is_shorthand: bool, pub attrs: AttrVec, pub id: NodeId, pub span: Span, pub is_placeholder: bool, } #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)] pub enum BindingMode { ByRef(Mutability), ByValue(Mutability), } #[derive(Clone, Encodable, Decodable, Debug)] pub enum RangeEnd { /// `..=` or `...` Included(RangeSyntax), /// `..` Excluded, } #[derive(Clone, Encodable, Decodable, Debug)] pub enum RangeSyntax { /// `...` DotDotDot, /// `..=` DotDotEq, } /// All the different flavors of pattern that Rust recognizes. #[derive(Clone, Encodable, Decodable, Debug)] pub enum PatKind { /// Represents a wildcard pattern (`_`). Wild, /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`), /// or a unit struct/variant pattern, or a const pattern (in the last two cases the third /// field must be `None`). Disambiguation cannot be done with parser alone, so it happens /// during name resolution. Ident(BindingMode, Ident, Option<P<Pat>>), /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`). /// The `bool` is `true` in the presence of a `..`. Struct(Option<QSelf>, Path, Vec<PatField>, /* recovered */ bool), /// A tuple struct/variant pattern (`Variant(x, y, .., z)`). TupleStruct(Option<QSelf>, Path, Vec<P<Pat>>), /// An or-pattern `A | B | C`. /// Invariant: `pats.len() >= 2`. Or(Vec<P<Pat>>), /// A possibly qualified path pattern. /// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants /// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can /// only legally refer to associated constants. Path(Option<QSelf>, Path), /// A tuple pattern (`(a, b)`). Tuple(Vec<P<Pat>>), /// A `box` pattern. Box(P<Pat>), /// A reference pattern (e.g., `&mut (a, b)`). Ref(P<Pat>, Mutability), /// A literal. Lit(P<Expr>), /// A range pattern (e.g., `1...2`, `1..2`, `1..`, `..2`, `1..=2`, `..=2`). Range(Option<P<Expr>>, Option<P<Expr>>, Spanned<RangeEnd>), /// A slice pattern `[a, b, c]`. Slice(Vec<P<Pat>>), /// A rest pattern `..`. /// /// Syntactically it is valid anywhere. /// /// Semantically however, it only has meaning immediately inside: /// - a slice pattern: `[a, .., b]`, /// - a binding pattern immediately inside a slice pattern: `[a, r @ ..]`, /// - a tuple pattern: `(a, .., b)`, /// - a tuple struct/variant pattern: `$path(a, .., b)`. /// /// In all of these cases, an additional restriction applies, /// only one rest pattern may occur in the pattern sequences. Rest, /// Parentheses in patterns used for grouping (i.e., `(PAT)`). Paren(P<Pat>), /// A macro pattern; pre-expansion. MacCall(MacCall), } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)] #[derive(HashStable_Generic, Encodable, Decodable)] pub enum Mutability { Mut, Not, } impl Mutability { pub fn invert(self) -> Self { match self { Mutability::Mut => Mutability::Not, Mutability::Not => Mutability::Mut, } } pub fn prefix_str(&self) -> &'static str { match self { Mutability::Mut => "mut ", Mutability::Not => "", } } } /// The kind of borrow in an `AddrOf` expression, /// e.g., `&place` or `&raw const place`. #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[derive(Encodable, Decodable, HashStable_Generic)] pub enum BorrowKind { /// A normal borrow, `&$expr` or `&mut $expr`. /// The resulting type is either `&'a T` or `&'a mut T` /// where `T = typeof($expr)` and `'a` is some lifetime. Ref, /// A raw borrow, `&raw const $expr` or `&raw mut $expr`. /// The resulting type is either `*const T` or `*mut T` /// where `T = typeof($expr)`. Raw, } #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)] pub enum BinOpKind { /// The `+` operator (addition) Add, /// The `-` operator (subtraction) Sub, /// The `*` operator (multiplication) Mul, /// The `/` operator (division) Div, /// The `%` operator (modulus) Rem, /// The `&&` operator (logical and) And, /// The `||` operator (logical or) Or, /// The `^` operator (bitwise xor) BitXor, /// The `&` operator (bitwise and) BitAnd, /// The `|` operator (bitwise or) BitOr, /// The `<<` operator (shift left) Shl, /// The `>>` operator (shift right) Shr, /// The `==` operator (equality) Eq, /// The `<` operator (less than) Lt, /// The `<=` operator (less than or equal to) Le, /// The `!=` operator (not equal to) Ne, /// The `>=` operator (greater than or equal to) Ge, /// The `>` operator (greater than) Gt, } impl BinOpKind { pub fn to_string(&self) -> &'static str { use BinOpKind::*; match *self { Add => "+", Sub => "-", Mul => "*", Div => "/", Rem => "%", And => "&&", Or => "||", BitXor => "^", BitAnd => "&", BitOr => "|", Shl => "<<", Shr => ">>", Eq => "==", Lt => "<", Le => "<=", Ne => "!=", Ge => ">=", Gt => ">", } } pub fn lazy(&self) -> bool { matches!(self, BinOpKind::And | BinOpKind::Or) } pub fn is_comparison(&self) -> bool { use BinOpKind::*; // Note for developers: please keep this as is; // we want compilation to fail if another variant is added. match *self { Eq | Lt | Le | Ne | Gt | Ge => true, And | Or | Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr => false, } } } pub type BinOp = Spanned<BinOpKind>; /// Unary operator. /// /// Note that `&data` is not an operator, it's an `AddrOf` expression. #[derive(Clone, Encodable, Decodable, Debug, Copy)] pub enum UnOp { /// The `*` operator for dereferencing Deref, /// The `!` operator for logical inversion Not, /// The `-` operator for negation Neg, } impl UnOp { pub fn to_string(op: UnOp) -> &'static str { match op { UnOp::Deref => "*", UnOp::Not => "!", UnOp::Neg => "-", } } } /// A statement #[derive(Clone, Encodable, Decodable, Debug)] pub struct Stmt { pub id: NodeId, pub kind: StmtKind, pub span: Span, } impl Stmt { pub fn has_trailing_semicolon(&self) -> bool { match &self.kind { StmtKind::Semi(_) => true, StmtKind::MacCall(mac) => matches!(mac.style, MacStmtStyle::Semicolon), _ => false, } } /// Converts a parsed `Stmt` to a `Stmt` with /// a trailing semicolon. /// /// This only modifies the parsed AST struct, not the attached /// `LazyTokenStream`. The parser is responsible for calling /// `CreateTokenStream::add_trailing_semi` when there is actually /// a semicolon in the tokenstream. pub fn add_trailing_semicolon(mut self) -> Self { self.kind = match self.kind { StmtKind::Expr(expr) => StmtKind::Semi(expr), StmtKind::MacCall(mac) => { StmtKind::MacCall(mac.map(|MacCallStmt { mac, style: _, attrs, tokens }| { MacCallStmt { mac, style: MacStmtStyle::Semicolon, attrs, tokens } })) } kind => kind, }; self } pub fn is_item(&self) -> bool { matches!(self.kind, StmtKind::Item(_)) } pub fn is_expr(&self) -> bool { matches!(self.kind, StmtKind::Expr(_)) } } #[derive(Clone, Encodable, Decodable, Debug)] pub enum StmtKind { /// A local (let) binding. Local(P<Local>), /// An item definition. Item(P<Item>), /// Expr without trailing semi-colon. Expr(P<Expr>), /// Expr with a trailing semi-colon. Semi(P<Expr>), /// Just a trailing semi-colon. Empty, /// Macro. MacCall(P<MacCallStmt>), } #[derive(Clone, Encodable, Decodable, Debug)] pub struct MacCallStmt { pub mac: MacCall, pub style: MacStmtStyle, pub attrs: AttrVec, pub tokens: Option<LazyTokenStream>, } #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)] pub enum MacStmtStyle { /// The macro statement had a trailing semicolon (e.g., `foo! { ... };` /// `foo!(...);`, `foo![...];`). Semicolon, /// The macro statement had braces (e.g., `foo! { ... }`). Braces, /// The macro statement had parentheses or brackets and no semicolon (e.g., /// `foo!(...)`). All of these will end up being converted into macro /// expressions. NoBraces, } /// Local represents a `let` statement, e.g., `let <pat>:<ty> = <expr>;`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct Local { pub id: NodeId, pub pat: P<Pat>, pub ty: Option<P<Ty>>, pub kind: LocalKind, pub span: Span, pub attrs: AttrVec, pub tokens: Option<LazyTokenStream>, } #[derive(Clone, Encodable, Decodable, Debug)] pub enum LocalKind { /// Local declaration. /// Example: `let x;` Decl, /// Local declaration with an initializer. /// Example: `let x = y;` Init(P<Expr>), /// Local declaration with an initializer and an `else` clause. /// Example: `let Some(x) = y else { return };` InitElse(P<Expr>, P<Block>), } impl LocalKind { pub fn init(&self) -> Option<&Expr> { match self { Self::Decl => None, Self::Init(i) | Self::InitElse(i, _) => Some(i), } } pub fn init_else_opt(&self) -> Option<(&Expr, Option<&Block>)> { match self { Self::Decl => None, Self::Init(init) => Some((init, None)), Self::InitElse(init, els) => Some((init, Some(els))), } } } /// An arm of a 'match'. /// /// E.g., `0..=10 => { println!("match!") }` as in /// /// ``` /// match 123 { /// 0..=10 => { println!("match!") }, /// _ => { println!("no match!") }, /// } /// ``` #[derive(Clone, Encodable, Decodable, Debug)] pub struct Arm { pub attrs: AttrVec, /// Match arm pattern, e.g. `10` in `match foo { 10 => {}, _ => {} }` pub pat: P<Pat>, /// Match arm guard, e.g. `n > 10` in `match foo { n if n > 10 => {}, _ => {} }` pub guard: Option<P<Expr>>, /// Match arm body. pub body: P<Expr>, pub span: Span, pub id: NodeId, pub is_placeholder: bool, } /// A single field in a struct expression, e.g. `x: value` and `y` in `Foo { x: value, y }`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct ExprField { pub attrs: AttrVec, pub id: NodeId, pub span: Span, pub ident: Ident, pub expr: P<Expr>, pub is_shorthand: bool, pub is_placeholder: bool, } #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)] pub enum BlockCheckMode { Default, Unsafe(UnsafeSource), } #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)] pub enum UnsafeSource { CompilerGenerated, UserProvided, } /// A constant (expression) that's not an item or associated item, /// but needs its own `DefId` for type-checking, const-eval, etc. /// These are usually found nested inside types (e.g., array lengths) /// or expressions (e.g., repeat counts), and also used to define /// explicit discriminant values for enum variants. #[derive(Clone, Encodable, Decodable, Debug)] pub struct AnonConst { pub id: NodeId, pub value: P<Expr>, } /// An expression. #[derive(Clone, Encodable, Decodable, Debug)] pub struct Expr { pub id: NodeId, pub kind: ExprKind, pub span: Span, pub attrs: AttrVec, pub tokens: Option<LazyTokenStream>, } // `Expr` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] rustc_data_structures::static_assert_size!(Expr, 104); impl Expr { /// Returns `true` if this expression would be valid somewhere that expects a value; /// for example, an `if` condition. pub fn returns(&self) -> bool { if let ExprKind::Block(ref block, _) = self.kind { match block.stmts.last().map(|last_stmt| &last_stmt.kind) { // Implicit return Some(StmtKind::Expr(_)) => true, // Last statement is an explicit return? Some(StmtKind::Semi(expr)) => matches!(expr.kind, ExprKind::Ret(_)), // This is a block that doesn't end in either an implicit or explicit return. _ => false, } } else { // This is not a block, it is a value. true } } /// Is this expr either `N`, or `{ N }`. /// /// If this is not the case, name resolution does not resolve `N` when using /// `min_const_generics` as more complex expressions are not supported. pub fn is_potential_trivial_const_param(&self) -> bool { let this = if let ExprKind::Block(ref block, None) = self.kind { if block.stmts.len() == 1 { if let StmtKind::Expr(ref expr) = block.stmts[0].kind { expr } else { self } } else { self } } else { self }; if let ExprKind::Path(None, ref path) = this.kind { if path.segments.len() == 1 && path.segments[0].args.is_none() { return true; } } false } pub fn to_bound(&self) -> Option<GenericBound> { match &self.kind { ExprKind::Path(None, path) => Some(GenericBound::Trait( PolyTraitRef::new(Vec::new(), path.clone(), self.span), TraitBoundModifier::None, )), _ => None, } } pub fn peel_parens(&self) -> &Expr { let mut expr = self; while let ExprKind::Paren(inner) = &expr.kind { expr = &inner; } expr } /// Attempts to reparse as `Ty` (for diagnostic purposes). pub fn to_ty(&self) -> Option<P<Ty>> { let kind = match &self.kind { // Trivial conversions. ExprKind::Path(qself, path) => TyKind::Path(qself.clone(), path.clone()), ExprKind::MacCall(mac) => TyKind::MacCall(mac.clone()), ExprKind::Paren(expr) => expr.to_ty().map(TyKind::Paren)?, ExprKind::AddrOf(BorrowKind::Ref, mutbl, expr) => { expr.to_ty().map(|ty| TyKind::Rptr(None, MutTy { ty, mutbl: *mutbl }))? } ExprKind::Repeat(expr, expr_len) => { expr.to_ty().map(|ty| TyKind::Array(ty, expr_len.clone()))? } ExprKind::Array(exprs) if exprs.len() == 1 => exprs[0].to_ty().map(TyKind::Slice)?, ExprKind::Tup(exprs) => { let tys = exprs.iter().map(|expr| expr.to_ty()).collect::<Option<Vec<_>>>()?; TyKind::Tup(tys) } // If binary operator is `Add` and both `lhs` and `rhs` are trait bounds, // then type of result is trait object. // Otherwise we don't assume the result type. ExprKind::Binary(binop, lhs, rhs) if binop.node == BinOpKind::Add => { if let (Some(lhs), Some(rhs)) = (lhs.to_bound(), rhs.to_bound()) { TyKind::TraitObject(vec![lhs, rhs], TraitObjectSyntax::None) } else { return None; } } ExprKind::Underscore => TyKind::Infer, // This expression doesn't look like a type syntactically. _ => return None, }; Some(P(Ty { kind, id: self.id, span: self.span, tokens: None })) } pub fn precedence(&self) -> ExprPrecedence { match self.kind { ExprKind::Box(_) => ExprPrecedence::Box, ExprKind::Array(_) => ExprPrecedence::Array, ExprKind::ConstBlock(_) => ExprPrecedence::ConstBlock, ExprKind::Call(..) => ExprPrecedence::Call, ExprKind::MethodCall(..) => ExprPrecedence::MethodCall, ExprKind::Tup(_) => ExprPrecedence::Tup, ExprKind::Binary(op, ..) => ExprPrecedence::Binary(op.node), ExprKind::Unary(..) => ExprPrecedence::Unary, ExprKind::Lit(_) => ExprPrecedence::Lit, ExprKind::Type(..) | ExprKind::Cast(..) => ExprPrecedence::Cast, ExprKind::Let(..) => ExprPrecedence::Let, ExprKind::If(..) => ExprPrecedence::If, ExprKind::While(..) => ExprPrecedence::While, ExprKind::ForLoop(..) => ExprPrecedence::ForLoop, ExprKind::Loop(..) => ExprPrecedence::Loop, ExprKind::Match(..) => ExprPrecedence::Match, ExprKind::Closure(..) => ExprPrecedence::Closure, ExprKind::Block(..) => ExprPrecedence::Block, ExprKind::TryBlock(..) => ExprPrecedence::TryBlock, ExprKind::Async(..) => ExprPrecedence::Async, ExprKind::Await(..) => ExprPrecedence::Await, ExprKind::Assign(..) => ExprPrecedence::Assign, ExprKind::AssignOp(..) => ExprPrecedence::AssignOp, ExprKind::Field(..) => ExprPrecedence::Field, ExprKind::Index(..) => ExprPrecedence::Index, ExprKind::Range(..) => ExprPrecedence::Range, ExprKind::Underscore => ExprPrecedence::Path, ExprKind::Path(..) => ExprPrecedence::Path, ExprKind::AddrOf(..) => ExprPrecedence::AddrOf, ExprKind::Break(..) => ExprPrecedence::Break, ExprKind::Continue(..) => ExprPrecedence::Continue, ExprKind::Ret(..) => ExprPrecedence::Ret, ExprKind::InlineAsm(..) => ExprPrecedence::InlineAsm, ExprKind::MacCall(..) => ExprPrecedence::Mac, ExprKind::Struct(..) => ExprPrecedence::Struct, ExprKind::Repeat(..) => ExprPrecedence::Repeat, ExprKind::Paren(..) => ExprPrecedence::Paren, ExprKind::Try(..) => ExprPrecedence::Try, ExprKind::Yield(..) => ExprPrecedence::Yield, ExprKind::Yeet(..) => ExprPrecedence::Yeet, ExprKind::Err => ExprPrecedence::Err, } } pub fn take(&mut self) -> Self { mem::replace( self, Expr { id: DUMMY_NODE_ID, kind: ExprKind::Err, span: DUMMY_SP, attrs: ThinVec::new(), tokens: None, }, ) } } /// Limit types of a range (inclusive or exclusive) #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug)] pub enum RangeLimits { /// Inclusive at the beginning, exclusive at the end HalfOpen, /// Inclusive at the beginning and end Closed, } #[derive(Clone, Encodable, Decodable, Debug)] pub enum StructRest { /// `..x`. Base(P<Expr>), /// `..`. Rest(Span), /// No trailing `..` or expression. None, } #[derive(Clone, Encodable, Decodable, Debug)] pub struct StructExpr { pub qself: Option<QSelf>, pub path: Path, pub fields: Vec<ExprField>, pub rest: StructRest, } #[derive(Clone, Encodable, Decodable, Debug)] pub enum ExprKind { /// A `box x` expression. Box(P<Expr>), /// An array (`[a, b, c, d]`) Array(Vec<P<Expr>>), /// Allow anonymous constants from an inline `const` block ConstBlock(AnonConst), /// A function call /// /// The first field resolves to the function itself, /// and the second field is the list of arguments. /// This also represents calling the constructor of /// tuple-like ADTs such as tuple structs and enum variants. Call(P<Expr>, Vec<P<Expr>>), /// A method call (`x.foo::<'static, Bar, Baz>(a, b, c, d)`) /// /// The `PathSegment` represents the method name and its generic arguments /// (within the angle brackets). /// The first element of the vector of an `Expr` is the expression that evaluates /// to the object on which the method is being called on (the receiver), /// and the remaining elements are the rest of the arguments. /// Thus, `x.foo::<Bar, Baz>(a, b, c, d)` is represented as /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`. /// This `Span` is the span of the function, without the dot and receiver /// (e.g. `foo(a, b)` in `x.foo(a, b)` MethodCall(PathSegment, Vec<P<Expr>>, Span), /// A tuple (e.g., `(a, b, c, d)`). Tup(Vec<P<Expr>>), /// A binary operation (e.g., `a + b`, `a * b`). Binary(BinOp, P<Expr>, P<Expr>), /// A unary operation (e.g., `!x`, `*x`). Unary(UnOp, P<Expr>), /// A literal (e.g., `1`, `"foo"`). Lit(Lit), /// A cast (e.g., `foo as f64`). Cast(P<Expr>, P<Ty>), /// A type ascription (e.g., `42: usize`). Type(P<Expr>, P<Ty>), /// A `let pat = expr` expression that is only semantically allowed in the condition /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`). /// /// `Span` represents the whole `let pat = expr` statement. Let(P<Pat>, P<Expr>, Span), /// An `if` block, with an optional `else` block. /// /// `if expr { block } else { expr }` If(P<Expr>, P<Block>, Option<P<Expr>>), /// A while loop, with an optional label. /// /// `'label: while expr { block }` While(P<Expr>, P<Block>, Option<Label>), /// A `for` loop, with an optional label. /// /// `'label: for pat in expr { block }` /// /// This is desugared to a combination of `loop` and `match` expressions. ForLoop(P<Pat>, P<Expr>, P<Block>, Option<Label>), /// Conditionless loop (can be exited with `break`, `continue`, or `return`). /// /// `'label: loop { block }` Loop(P<Block>, Option<Label>), /// A `match` block. Match(P<Expr>, Vec<Arm>), /// A closure (e.g., `move |a, b, c| a + b + c`). /// /// The final span is the span of the argument block `|...|`. Closure(CaptureBy, Async, Movability, P<FnDecl>, P<Expr>, Span), /// A block (`'label: { ... }`). Block(P<Block>, Option<Label>), /// An async block (`async move { ... }`). /// /// The `NodeId` is the `NodeId` for the closure that results from /// desugaring an async block, just like the NodeId field in the /// `Async::Yes` variant. This is necessary in order to create a def for the /// closure which can be used as a parent of any child defs. Defs /// created during lowering cannot be made the parent of any other /// preexisting defs. Async(CaptureBy, NodeId, P<Block>), /// An await expression (`my_future.await`). Await(P<Expr>), /// A try block (`try { ... }`). TryBlock(P<Block>), /// An assignment (`a = foo()`). /// The `Span` argument is the span of the `=` token. Assign(P<Expr>, P<Expr>, Span), /// An assignment with an operator. /// /// E.g., `a += 1`. AssignOp(BinOp, P<Expr>, P<Expr>), /// Access of a named (e.g., `obj.foo`) or unnamed (e.g., `obj.0`) struct field. Field(P<Expr>, Ident), /// An indexing operation (e.g., `foo[2]`). Index(P<Expr>, P<Expr>), /// A range (e.g., `1..2`, `1..`, `..2`, `1..=2`, `..=2`; and `..` in destructuring assignment). Range(Option<P<Expr>>, Option<P<Expr>>, RangeLimits), /// An underscore, used in destructuring assignment to ignore a value. Underscore, /// Variable reference, possibly containing `::` and/or type /// parameters (e.g., `foo::bar::<baz>`). /// /// Optionally "qualified" (e.g., `<Vec<T> as SomeTrait>::SomeType`). Path(Option<QSelf>, Path), /// A referencing operation (`&a`, `&mut a`, `&raw const a` or `&raw mut a`). AddrOf(BorrowKind, Mutability, P<Expr>), /// A `break`, with an optional label to break, and an optional expression. Break(Option<Label>, Option<P<Expr>>), /// A `continue`, with an optional label. Continue(Option<Label>), /// A `return`, with an optional value to be returned. Ret(Option<P<Expr>>), /// Output of the `asm!()` macro. InlineAsm(P<InlineAsm>), /// A macro invocation; pre-expansion. MacCall(MacCall), /// A struct literal expression. /// /// E.g., `Foo {x: 1, y: 2}`, or `Foo {x: 1, .. rest}`. Struct(P<StructExpr>), /// An array literal constructed from one repeated element. /// /// E.g., `[1; 5]`. The expression is the element to be /// repeated; the constant is the number of times to repeat it. Repeat(P<Expr>, AnonConst), /// No-op: used solely so we can pretty-print faithfully. Paren(P<Expr>), /// A try expression (`expr?`). Try(P<Expr>), /// A `yield`, with an optional value to be yielded. Yield(Option<P<Expr>>), /// A `do yeet` (aka `throw`/`fail`/`bail`/`raise`/whatever), /// with an optional value to be returned. Yeet(Option<P<Expr>>), /// Placeholder for an expression that wasn't syntactically well formed in some way. Err, } /// The explicit `Self` type in a "qualified path". The actual /// path, including the trait and the associated item, is stored /// separately. `position` represents the index of the associated /// item qualified with this `Self` type. /// /// ```ignore (only-for-syntax-highlight) /// <Vec<T> as a::b::Trait>::AssociatedItem /// ^~~~~ ~~~~~~~~~~~~~~^ /// ty position = 3 /// /// <Vec<T>>::AssociatedItem /// ^~~~~ ^ /// ty position = 0 /// ``` #[derive(Clone, Encodable, Decodable, Debug)] pub struct QSelf { pub ty: P<Ty>, /// The span of `a::b::Trait` in a path like `<Vec<T> as /// a::b::Trait>::AssociatedItem`; in the case where `position == /// 0`, this is an empty span. pub path_span: Span, pub position: usize, } /// A capture clause used in closures and `async` blocks. #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] pub enum CaptureBy { /// `move |x| y + x`. Value, /// `move` keyword was not specified. Ref, } /// The movability of a generator / closure literal: /// whether a generator contains self-references, causing it to be `!Unpin`. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable, Debug, Copy)] #[derive(HashStable_Generic)] pub enum Movability { /// May contain self-references, `!Unpin`. Static, /// Must not contain self-references, `Unpin`. Movable, } /// Represents a macro invocation. The `path` indicates which macro /// is being invoked, and the `args` are arguments passed to it. #[derive(Clone, Encodable, Decodable, Debug)] pub struct MacCall { pub path: Path, pub args: P<MacArgs>, pub prior_type_ascription: Option<(Span, bool)>, } impl MacCall { pub fn span(&self) -> Span { self.path.span.to(self.args.span().unwrap_or(self.path.span)) } } /// Arguments passed to an attribute or a function-like macro. #[derive(Clone, Encodable, Decodable, Debug)] pub enum MacArgs { /// No arguments - `#[attr]`. Empty, /// Delimited arguments - `#[attr()/[]/{}]` or `mac!()/[]/{}`. Delimited(DelimSpan, MacDelimiter, TokenStream), /// Arguments of a key-value attribute - `#[attr = "value"]`. Eq( /// Span of the `=` token. Span, /// The "value". MacArgsEq, ), } // The RHS of a `MacArgs::Eq` starts out as an expression. Once macro expansion // is completed, all cases end up either as a literal, which is the form used // after lowering to HIR, or as an error. #[derive(Clone, Encodable, Decodable, Debug)] pub enum MacArgsEq { Ast(P<Expr>), Hir(Lit), } impl MacArgs { pub fn delim(&self) -> Option<Delimiter> { match self { MacArgs::Delimited(_, delim, _) => Some(delim.to_token()), MacArgs::Empty | MacArgs::Eq(..) => None, } } pub fn span(&self) -> Option<Span> { match self { MacArgs::Empty => None, MacArgs::Delimited(dspan, ..) => Some(dspan.entire()), MacArgs::Eq(eq_span, MacArgsEq::Ast(expr)) => Some(eq_span.to(expr.span)), MacArgs::Eq(_, MacArgsEq::Hir(lit)) => { unreachable!("in literal form when getting span: {:?}", lit); } } } /// Tokens inside the delimiters or after `=`. /// Proc macros see these tokens, for example. pub fn inner_tokens(&self) -> TokenStream { match self { MacArgs::Empty => TokenStream::default(), MacArgs::Delimited(.., tokens) => tokens.clone(), MacArgs::Eq(_, MacArgsEq::Ast(expr)) => TokenStream::from_ast(expr), MacArgs::Eq(_, MacArgsEq::Hir(lit)) => { unreachable!("in literal form when getting inner tokens: {:?}", lit) } } } /// Whether a macro with these arguments needs a semicolon /// when used as a standalone item or statement. pub fn need_semicolon(&self) -> bool { !matches!(self, MacArgs::Delimited(_, MacDelimiter::Brace, _)) } } impl<CTX> HashStable<CTX> for MacArgs where CTX: crate::HashStableContext, { fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { mem::discriminant(self).hash_stable(ctx, hasher); match self { MacArgs::Empty => {} MacArgs::Delimited(dspan, delim, tokens) => { dspan.hash_stable(ctx, hasher); delim.hash_stable(ctx, hasher); tokens.hash_stable(ctx, hasher); } MacArgs::Eq(_eq_span, MacArgsEq::Ast(expr)) => { unreachable!("hash_stable {:?}", expr); } MacArgs::Eq(eq_span, MacArgsEq::Hir(lit)) => { eq_span.hash_stable(ctx, hasher); lit.hash_stable(ctx, hasher); } } } } #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug, HashStable_Generic)] pub enum MacDelimiter { Parenthesis, Bracket, Brace, } impl MacDelimiter { pub fn to_token(self) -> Delimiter { match self { MacDelimiter::Parenthesis => Delimiter::Parenthesis, MacDelimiter::Bracket => Delimiter::Bracket, MacDelimiter::Brace => Delimiter::Brace, } } pub fn from_token(delim: Delimiter) -> Option<MacDelimiter> { match delim { Delimiter::Parenthesis => Some(MacDelimiter::Parenthesis), Delimiter::Bracket => Some(MacDelimiter::Bracket), Delimiter::Brace => Some(MacDelimiter::Brace), Delimiter::Invisible => None, } } } /// Represents a macro definition. #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)] pub struct MacroDef { pub body: P<MacArgs>, /// `true` if macro was defined with `macro_rules`. pub macro_rules: bool, } #[derive(Clone, Encodable, Decodable, Debug, Copy, Hash, Eq, PartialEq)] #[derive(HashStable_Generic)] pub enum StrStyle { /// A regular string, like `"foo"`. Cooked, /// A raw string, like `r##"foo"##`. /// /// The value is the number of `#` symbols used. Raw(u8), } /// An AST literal. #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)] pub struct Lit { /// The original literal token as written in source code. pub token: token::Lit, /// The "semantic" representation of the literal lowered from the original tokens. /// Strings are unescaped, hexadecimal forms are eliminated, etc. /// FIXME: Remove this and only create the semantic representation during lowering to HIR. pub kind: LitKind, pub span: Span, } /// Same as `Lit`, but restricted to string literals. #[derive(Clone, Copy, Encodable, Decodable, Debug)] pub struct StrLit { /// The original literal token as written in source code. pub style: StrStyle, pub symbol: Symbol, pub suffix: Option<Symbol>, pub span: Span, /// The unescaped "semantic" representation of the literal lowered from the original token. /// FIXME: Remove this and only create the semantic representation during lowering to HIR. pub symbol_unescaped: Symbol, } impl StrLit { pub fn as_lit(&self) -> Lit { let token_kind = match self.style { StrStyle::Cooked => token::Str, StrStyle::Raw(n) => token::StrRaw(n), }; Lit { token: token::Lit::new(token_kind, self.symbol, self.suffix), span: self.span, kind: LitKind::Str(self.symbol_unescaped, self.style), } } } /// Type of the integer literal based on provided suffix. #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)] #[derive(HashStable_Generic)] pub enum LitIntType { /// e.g. `42_i32`. Signed(IntTy), /// e.g. `42_u32`. Unsigned(UintTy), /// e.g. `42`. Unsuffixed, } /// Type of the float literal based on provided suffix. #[derive(Clone, Copy, Encodable, Decodable, Debug, Hash, Eq, PartialEq)] #[derive(HashStable_Generic)] pub enum LitFloatType { /// A float literal with a suffix (`1f32` or `1E10f32`). Suffixed(FloatTy), /// A float literal without a suffix (`1.0 or 1.0E10`). Unsuffixed, } /// Literal kind. /// /// E.g., `"foo"`, `42`, `12.34`, or `bool`. #[derive(Clone, Encodable, Decodable, Debug, Hash, Eq, PartialEq, HashStable_Generic)] pub enum LitKind { /// A string literal (`"foo"`). Str(Symbol, StrStyle), /// A byte string (`b"foo"`). ByteStr(Lrc<[u8]>), /// A byte char (`b'f'`). Byte(u8), /// A character literal (`'a'`). Char(char), /// An integer literal (`1`). Int(u128, LitIntType), /// A float literal (`1f64` or `1E10f64`). Float(Symbol, LitFloatType), /// A boolean literal. Bool(bool), /// Placeholder for a literal that wasn't well-formed in some way. Err(Symbol), } impl LitKind { /// Returns `true` if this literal is a string. pub fn is_str(&self) -> bool { matches!(self, LitKind::Str(..)) } /// Returns `true` if this literal is byte literal string. pub fn is_bytestr(&self) -> bool { matches!(self, LitKind::ByteStr(_)) } /// Returns `true` if this is a numeric literal. pub fn is_numeric(&self) -> bool { matches!(self, LitKind::Int(..) | LitKind::Float(..)) } /// Returns `true` if this literal has no suffix. /// Note: this will return true for literals with prefixes such as raw strings and byte strings. pub fn is_unsuffixed(&self) -> bool { !self.is_suffixed() } /// Returns `true` if this literal has a suffix. pub fn is_suffixed(&self) -> bool { match *self { // suffixed variants LitKind::Int(_, LitIntType::Signed(..) | LitIntType::Unsigned(..)) | LitKind::Float(_, LitFloatType::Suffixed(..)) => true, // unsuffixed variants LitKind::Str(..) | LitKind::ByteStr(..) | LitKind::Byte(..) | LitKind::Char(..) | LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) | LitKind::Bool(..) | LitKind::Err(..) => false, } } } // N.B., If you change this, you'll probably want to change the corresponding // type structure in `middle/ty.rs` as well. #[derive(Clone, Encodable, Decodable, Debug)] pub struct MutTy { pub ty: P<Ty>, pub mutbl: Mutability, } /// Represents a function's signature in a trait declaration, /// trait implementation, or free function. #[derive(Clone, Encodable, Decodable, Debug)] pub struct FnSig { pub header: FnHeader, pub decl: P<FnDecl>, pub span: Span, } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] #[derive(Encodable, Decodable, HashStable_Generic)] pub enum FloatTy { F32, F64, } impl FloatTy { pub fn name_str(self) -> &'static str { match self { FloatTy::F32 => "f32", FloatTy::F64 => "f64", } } pub fn name(self) -> Symbol { match self { FloatTy::F32 => sym::f32, FloatTy::F64 => sym::f64, } } } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] #[derive(Encodable, Decodable, HashStable_Generic)] pub enum IntTy { Isize, I8, I16, I32, I64, I128, } impl IntTy { pub fn name_str(&self) -> &'static str { match *self { IntTy::Isize => "isize", IntTy::I8 => "i8", IntTy::I16 => "i16", IntTy::I32 => "i32", IntTy::I64 => "i64", IntTy::I128 => "i128", } } pub fn name(&self) -> Symbol { match *self { IntTy::Isize => sym::isize, IntTy::I8 => sym::i8, IntTy::I16 => sym::i16, IntTy::I32 => sym::i32, IntTy::I64 => sym::i64, IntTy::I128 => sym::i128, } } } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Debug)] #[derive(Encodable, Decodable, HashStable_Generic)] pub enum UintTy { Usize, U8, U16, U32, U64, U128, } impl UintTy { pub fn name_str(&self) -> &'static str { match *self { UintTy::Usize => "usize", UintTy::U8 => "u8", UintTy::U16 => "u16", UintTy::U32 => "u32", UintTy::U64 => "u64", UintTy::U128 => "u128", } } pub fn name(&self) -> Symbol { match *self { UintTy::Usize => sym::usize, UintTy::U8 => sym::u8, UintTy::U16 => sym::u16, UintTy::U32 => sym::u32, UintTy::U64 => sym::u64, UintTy::U128 => sym::u128, } } } /// A constraint on an associated type (e.g., `A = Bar` in `Foo<A = Bar>` or /// `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`). #[derive(Clone, Encodable, Decodable, Debug)] pub struct AssocConstraint { pub id: NodeId, pub ident: Ident, pub gen_args: Option<GenericArgs>, pub kind: AssocConstraintKind, pub span: Span, } /// The kinds of an `AssocConstraint`. #[derive(Clone, Encodable, Decodable, Debug)] pub enum Term { Ty(P<Ty>), Const(AnonConst), } impl From<P<Ty>> for Term { fn from(v: P<Ty>) -> Self { Term::Ty(v) } } impl From<AnonConst> for Term { fn from(v: AnonConst) -> Self { Term::Const(v) } } /// The kinds of an `AssocConstraint`. #[derive(Clone, Encodable, Decodable, Debug)] pub enum AssocConstraintKind { /// E.g., `A = Bar`, `A = 3` in `Foo<A = Bar>` where A is an associated type. Equality { term: Term }, /// E.g. `A: TraitA + TraitB` in `Foo<A: TraitA + TraitB>`. Bound { bounds: GenericBounds }, } #[derive(Encodable, Decodable, Debug)] pub struct Ty { pub id: NodeId, pub kind: TyKind, pub span: Span, pub tokens: Option<LazyTokenStream>, } impl Clone for Ty { fn clone(&self) -> Self { ensure_sufficient_stack(|| Self { id: self.id, kind: self.kind.clone(), span: self.span, tokens: self.tokens.clone(), }) } } impl Ty { pub fn peel_refs(&self) -> &Self { let mut final_ty = self; while let TyKind::Rptr(_, MutTy { ty, .. }) = &final_ty.kind { final_ty = &ty; } final_ty } } #[derive(Clone, Encodable, Decodable, Debug)] pub struct BareFnTy { pub unsafety: Unsafe, pub ext: Extern, pub generic_params: Vec<GenericParam>, pub decl: P<FnDecl>, /// Span of the `fn(...) -> ...` part. pub decl_span: Span, } /// The various kinds of type recognized by the compiler. #[derive(Clone, Encodable, Decodable, Debug)] pub enum TyKind { /// A variable-length slice (`[T]`). Slice(P<Ty>), /// A fixed length array (`[T; n]`). Array(P<Ty>, AnonConst), /// A raw pointer (`*const T` or `*mut T`). Ptr(MutTy), /// A reference (`&'a T` or `&'a mut T`). Rptr(Option<Lifetime>, MutTy), /// A bare function (e.g., `fn(usize) -> bool`). BareFn(P<BareFnTy>), /// The never type (`!`). Never, /// A tuple (`(A, B, C, D,...)`). Tup(Vec<P<Ty>>), /// A path (`module::module::...::Type`), optionally /// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`. /// /// Type parameters are stored in the `Path` itself. Path(Option<QSelf>, Path), /// A trait object type `Bound1 + Bound2 + Bound3` /// where `Bound` is a trait or a lifetime. TraitObject(GenericBounds, TraitObjectSyntax), /// An `impl Bound1 + Bound2 + Bound3` type /// where `Bound` is a trait or a lifetime. /// /// The `NodeId` exists to prevent lowering from having to /// generate `NodeId`s on the fly, which would complicate /// the generation of opaque `type Foo = impl Trait` items significantly. ImplTrait(NodeId, GenericBounds), /// No-op; kept solely so that we can pretty-print faithfully. Paren(P<Ty>), /// Unused for now. Typeof(AnonConst), /// This means the type should be inferred instead of it having been /// specified. This can appear anywhere in a type. Infer, /// Inferred type of a `self` or `&self` argument in a method. ImplicitSelf, /// A macro in the type position. MacCall(MacCall), /// Placeholder for a kind that has failed to be defined. Err, /// Placeholder for a `va_list`. CVarArgs, } impl TyKind { pub fn is_implicit_self(&self) -> bool { matches!(self, TyKind::ImplicitSelf) } pub fn is_unit(&self) -> bool { matches!(self, TyKind::Tup(tys) if tys.is_empty()) } } /// Syntax used to declare a trait object. #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] pub enum TraitObjectSyntax { Dyn, None, } /// Inline assembly operand explicit register or register class. /// /// E.g., `"eax"` as in `asm!("mov eax, 2", out("eax") result)`. #[derive(Clone, Copy, Encodable, Decodable, Debug)] pub enum InlineAsmRegOrRegClass { Reg(Symbol), RegClass(Symbol), } bitflags::bitflags! { #[derive(Encodable, Decodable, HashStable_Generic)] pub struct InlineAsmOptions: u16 { const PURE = 1 << 0; const NOMEM = 1 << 1; const READONLY = 1 << 2; const PRESERVES_FLAGS = 1 << 3; const NORETURN = 1 << 4; const NOSTACK = 1 << 5; const ATT_SYNTAX = 1 << 6; const RAW = 1 << 7; const MAY_UNWIND = 1 << 8; } } #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Hash, HashStable_Generic)] pub enum InlineAsmTemplatePiece { String(String), Placeholder { operand_idx: usize, modifier: Option<char>, span: Span }, } impl fmt::Display for InlineAsmTemplatePiece { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::String(s) => { for c in s.chars() { match c { '{' => f.write_str("{{")?, '}' => f.write_str("}}")?, _ => c.fmt(f)?, } } Ok(()) } Self::Placeholder { operand_idx, modifier: Some(modifier), .. } => { write!(f, "{{{}:{}}}", operand_idx, modifier) } Self::Placeholder { operand_idx, modifier: None, .. } => { write!(f, "{{{}}}", operand_idx) } } } } impl InlineAsmTemplatePiece { /// Rebuilds the asm template string from its pieces. pub fn to_string(s: &[Self]) -> String { use fmt::Write; let mut out = String::new(); for p in s.iter() { let _ = write!(out, "{}", p); } out } } /// Inline assembly symbol operands get their own AST node that is somewhat /// similar to `AnonConst`. /// /// The main difference is that we specifically don't assign it `DefId` in /// `DefCollector`. Instead this is deferred until AST lowering where we /// lower it to an `AnonConst` (for functions) or a `Path` (for statics) /// depending on what the path resolves to. #[derive(Clone, Encodable, Decodable, Debug)] pub struct InlineAsmSym { pub id: NodeId, pub qself: Option<QSelf>, pub path: Path, } /// Inline assembly operand. /// /// E.g., `out("eax") result` as in `asm!("mov eax, 2", out("eax") result)`. #[derive(Clone, Encodable, Decodable, Debug)] pub enum InlineAsmOperand { In { reg: InlineAsmRegOrRegClass, expr: P<Expr>, }, Out { reg: InlineAsmRegOrRegClass, late: bool, expr: Option<P<Expr>>, }, InOut { reg: InlineAsmRegOrRegClass, late: bool, expr: P<Expr>, }, SplitInOut { reg: InlineAsmRegOrRegClass, late: bool, in_expr: P<Expr>, out_expr: Option<P<Expr>>, }, Const { anon_const: AnonConst, }, Sym { sym: InlineAsmSym, }, } /// Inline assembly. /// /// E.g., `asm!("NOP");`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct InlineAsm { pub template: Vec<InlineAsmTemplatePiece>, pub template_strs: Box<[(Symbol, Option<Symbol>, Span)]>, pub operands: Vec<(InlineAsmOperand, Span)>, pub clobber_abis: Vec<(Symbol, Span)>, pub options: InlineAsmOptions, pub line_spans: Vec<Span>, } /// A parameter in a function header. /// /// E.g., `bar: usize` as in `fn foo(bar: usize)`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct Param { pub attrs: AttrVec, pub ty: P<Ty>, pub pat: P<Pat>, pub id: NodeId, pub span: Span, pub is_placeholder: bool, } /// Alternative representation for `Arg`s describing `self` parameter of methods. /// /// E.g., `&mut self` as in `fn foo(&mut self)`. #[derive(Clone, Encodable, Decodable, Debug)] pub enum SelfKind { /// `self`, `mut self` Value(Mutability), /// `&'lt self`, `&'lt mut self` Region(Option<Lifetime>, Mutability), /// `self: TYPE`, `mut self: TYPE` Explicit(P<Ty>, Mutability), } pub type ExplicitSelf = Spanned<SelfKind>; impl Param { /// Attempts to cast parameter to `ExplicitSelf`. pub fn to_self(&self) -> Option<ExplicitSelf> { if let PatKind::Ident(BindingMode::ByValue(mutbl), ident, _) = self.pat.kind { if ident.name == kw::SelfLower { return match self.ty.kind { TyKind::ImplicitSelf => Some(respan(self.pat.span, SelfKind::Value(mutbl))), TyKind::Rptr(lt, MutTy { ref ty, mutbl }) if ty.kind.is_implicit_self() => { Some(respan(self.pat.span, SelfKind::Region(lt, mutbl))) } _ => Some(respan( self.pat.span.to(self.ty.span), SelfKind::Explicit(self.ty.clone(), mutbl), )), }; } } None } /// Returns `true` if parameter is `self`. pub fn is_self(&self) -> bool { if let PatKind::Ident(_, ident, _) = self.pat.kind { ident.name == kw::SelfLower } else { false } } /// Builds a `Param` object from `ExplicitSelf`. pub fn from_self(attrs: AttrVec, eself: ExplicitSelf, eself_ident: Ident) -> Param { let span = eself.span.to(eself_ident.span); let infer_ty = P(Ty { id: DUMMY_NODE_ID, kind: TyKind::ImplicitSelf, span, tokens: None }); let param = |mutbl, ty| Param { attrs, pat: P(Pat { id: DUMMY_NODE_ID, kind: PatKind::Ident(BindingMode::ByValue(mutbl), eself_ident, None), span, tokens: None, }), span, ty, id: DUMMY_NODE_ID, is_placeholder: false, }; match eself.node { SelfKind::Explicit(ty, mutbl) => param(mutbl, ty), SelfKind::Value(mutbl) => param(mutbl, infer_ty), SelfKind::Region(lt, mutbl) => param( Mutability::Not, P(Ty { id: DUMMY_NODE_ID, kind: TyKind::Rptr(lt, MutTy { ty: infer_ty, mutbl }), span, tokens: None, }), ), } } } /// A signature (not the body) of a function declaration. /// /// E.g., `fn foo(bar: baz)`. /// /// Please note that it's different from `FnHeader` structure /// which contains metadata about function safety, asyncness, constness and ABI. #[derive(Clone, Encodable, Decodable, Debug)] pub struct FnDecl { pub inputs: Vec<Param>, pub output: FnRetTy, } impl FnDecl { pub fn has_self(&self) -> bool { self.inputs.get(0).map_or(false, Param::is_self) } pub fn c_variadic(&self) -> bool { self.inputs.last().map_or(false, |arg| matches!(arg.ty.kind, TyKind::CVarArgs)) } } /// Is the trait definition an auto trait? #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] pub enum IsAuto { Yes, No, } #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)] #[derive(HashStable_Generic)] pub enum Unsafe { Yes(Span), No, } #[derive(Copy, Clone, Encodable, Decodable, Debug)] pub enum Async { Yes { span: Span, closure_id: NodeId, return_impl_trait_id: NodeId }, No, } impl Async { pub fn is_async(self) -> bool { matches!(self, Async::Yes { .. }) } /// In this case this is an `async` return, the `NodeId` for the generated `impl Trait` item. pub fn opt_return_id(self) -> Option<NodeId> { match self { Async::Yes { return_impl_trait_id, .. } => Some(return_impl_trait_id), Async::No => None, } } } #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)] #[derive(HashStable_Generic)] pub enum Const { Yes(Span), No, } /// Item defaultness. /// For details see the [RFC #2532](https://github.com/rust-lang/rfcs/pull/2532). #[derive(Copy, Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] pub enum Defaultness { Default(Span), Final, } #[derive(Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] pub enum ImplPolarity { /// `impl Trait for Type` Positive, /// `impl !Trait for Type` Negative(Span), } impl fmt::Debug for ImplPolarity { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { ImplPolarity::Positive => "positive".fmt(f), ImplPolarity::Negative(_) => "negative".fmt(f), } } } #[derive(Clone, Encodable, Decodable, Debug)] pub enum FnRetTy { /// Returns type is not specified. /// /// Functions default to `()` and closures default to inference. /// Span points to where return type would be inserted. Default(Span), /// Everything else. Ty(P<Ty>), } impl FnRetTy { pub fn span(&self) -> Span { match *self { FnRetTy::Default(span) => span, FnRetTy::Ty(ref ty) => ty.span, } } } #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug)] pub enum Inline { Yes, No, } /// Module item kind. #[derive(Clone, Encodable, Decodable, Debug)] pub enum ModKind { /// Module with inlined definition `mod foo { ... }`, /// or with definition outlined to a separate file `mod foo;` and already loaded from it. /// The inner span is from the first token past `{` to the last token until `}`, /// or from the first to the last token in the loaded file. Loaded(Vec<P<Item>>, Inline, ModSpans), /// Module with definition outlined to a separate file `mod foo;` but not yet loaded from it. Unloaded, } #[derive(Copy, Clone, Encodable, Decodable, Debug)] pub struct ModSpans { /// `inner_span` covers the body of the module; for a file module, its the whole file. /// For an inline module, its the span inside the `{ ... }`, not including the curly braces. pub inner_span: Span, pub inject_use_span: Span, } impl Default for ModSpans { fn default() -> ModSpans { ModSpans { inner_span: Default::default(), inject_use_span: Default::default() } } } /// Foreign module declaration. /// /// E.g., `extern { .. }` or `extern "C" { .. }`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct ForeignMod { /// `unsafe` keyword accepted syntactically for macro DSLs, but not /// semantically by Rust. pub unsafety: Unsafe, pub abi: Option<StrLit>, pub items: Vec<P<ForeignItem>>, } #[derive(Clone, Encodable, Decodable, Debug)] pub struct EnumDef { pub variants: Vec<Variant>, } /// Enum variant. #[derive(Clone, Encodable, Decodable, Debug)] pub struct Variant { /// Attributes of the variant. pub attrs: AttrVec, /// Id of the variant (not the constructor, see `VariantData::ctor_id()`). pub id: NodeId, /// Span pub span: Span, /// The visibility of the variant. Syntactically accepted but not semantically. pub vis: Visibility, /// Name of the variant. pub ident: Ident, /// Fields and constructor id of the variant. pub data: VariantData, /// Explicit discriminant, e.g., `Foo = 1`. pub disr_expr: Option<AnonConst>, /// Is a macro placeholder pub is_placeholder: bool, } /// Part of `use` item to the right of its prefix. #[derive(Clone, Encodable, Decodable, Debug)] pub enum UseTreeKind { /// `use prefix` or `use prefix as rename` /// /// The extra `NodeId`s are for HIR lowering, when additional statements are created for each /// namespace. Simple(Option<Ident>, NodeId, NodeId), /// `use prefix::{...}` Nested(Vec<(UseTree, NodeId)>), /// `use prefix::*` Glob, } /// A tree of paths sharing common prefixes. /// Used in `use` items both at top-level and inside of braces in import groups. #[derive(Clone, Encodable, Decodable, Debug)] pub struct UseTree { pub prefix: Path, pub kind: UseTreeKind, pub span: Span, } impl UseTree { pub fn ident(&self) -> Ident { match self.kind { UseTreeKind::Simple(Some(rename), ..) => rename, UseTreeKind::Simple(None, ..) => { self.prefix.segments.last().expect("empty prefix in a simple import").ident } _ => panic!("`UseTree::ident` can only be used on a simple import"), } } } /// Distinguishes between `Attribute`s that decorate items and Attributes that /// are contained as statements within items. These two cases need to be /// distinguished for pretty-printing. #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy, HashStable_Generic)] pub enum AttrStyle { Outer, Inner, } rustc_index::newtype_index! { pub struct AttrId { ENCODABLE = custom DEBUG_FORMAT = "AttrId({})" } } impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_unit() } } impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId { fn decode(_: &mut D) -> AttrId { crate::attr::mk_attr_id() } } #[derive(Clone, Encodable, Decodable, Debug, HashStable_Generic)] pub struct AttrItem { pub path: Path, pub args: MacArgs, pub tokens: Option<LazyTokenStream>, } /// A list of attributes. pub type AttrVec = ThinVec<Attribute>; /// Metadata associated with an item. #[derive(Clone, Encodable, Decodable, Debug)] pub struct Attribute { pub kind: AttrKind, pub id: AttrId, /// Denotes if the attribute decorates the following construct (outer) /// or the construct this attribute is contained within (inner). pub style: AttrStyle, pub span: Span, } #[derive(Clone, Encodable, Decodable, Debug)] pub enum AttrKind { /// A normal attribute. Normal(AttrItem, Option<LazyTokenStream>), /// A doc comment (e.g. `/// ...`, `//! ...`, `/** ... */`, `/*! ... */`). /// Doc attributes (e.g. `#[doc="..."]`) are represented with the `Normal` /// variant (which is much less compact and thus more expensive). DocComment(CommentKind, Symbol), } /// `TraitRef`s appear in impls. /// /// Resolution maps each `TraitRef`'s `ref_id` to its defining trait; that's all /// that the `ref_id` is for. The `impl_id` maps to the "self type" of this impl. /// If this impl is an `ItemKind::Impl`, the `impl_id` is redundant (it could be the /// same as the impl's `NodeId`). #[derive(Clone, Encodable, Decodable, Debug)] pub struct TraitRef { pub path: Path, pub ref_id: NodeId, } #[derive(Clone, Encodable, Decodable, Debug)] pub struct PolyTraitRef { /// The `'a` in `for<'a> Foo<&'a T>`. pub bound_generic_params: Vec<GenericParam>, /// The `Foo<&'a T>` in `<'a> Foo<&'a T>`. pub trait_ref: TraitRef, pub span: Span, } impl PolyTraitRef { pub fn new(generic_params: Vec<GenericParam>, path: Path, span: Span) -> Self { PolyTraitRef { bound_generic_params: generic_params, trait_ref: TraitRef { path, ref_id: DUMMY_NODE_ID }, span, } } } #[derive(Clone, Encodable, Decodable, Debug)] pub struct Visibility { pub kind: VisibilityKind, pub span: Span, pub tokens: Option<LazyTokenStream>, } #[derive(Clone, Encodable, Decodable, Debug)] pub enum VisibilityKind { Public, Restricted { path: P<Path>, id: NodeId }, Inherited, } impl VisibilityKind { pub fn is_pub(&self) -> bool { matches!(self, VisibilityKind::Public) } } /// Field definition in a struct, variant or union. /// /// E.g., `bar: usize` as in `struct Foo { bar: usize }`. #[derive(Clone, Encodable, Decodable, Debug)] pub struct FieldDef { pub attrs: AttrVec, pub id: NodeId, pub span: Span, pub vis: Visibility, pub ident: Option<Ident>, pub ty: P<Ty>, pub is_placeholder: bool, } /// Fields and constructor ids of enum variants and structs. #[derive(Clone, Encodable, Decodable, Debug)] pub enum VariantData { /// Struct variant. /// /// E.g., `Bar { .. }` as in `enum Foo { Bar { .. } }`. Struct(Vec<FieldDef>, bool), /// Tuple variant. /// /// E.g., `Bar(..)` as in `enum Foo { Bar(..) }`. Tuple(Vec<FieldDef>, NodeId), /// Unit variant. /// /// E.g., `Bar = ..` as in `enum Foo { Bar = .. }`. Unit(NodeId), } impl VariantData { /// Return the fields of this variant. pub fn fields(&self) -> &[FieldDef] { match *self { VariantData::Struct(ref fields, ..) | VariantData::Tuple(ref fields, _) => fields, _ => &[], } } /// Return the `NodeId` of this variant's constructor, if it has one. pub fn ctor_id(&self) -> Option<NodeId> { match *self { VariantData::Struct(..) => None, VariantData::Tuple(_, id) | VariantData::Unit(id) => Some(id), } } } /// An item definition. #[derive(Clone, Encodable, Decodable, Debug)] pub struct Item<K = ItemKind> { pub attrs: Vec<Attribute>, pub id: NodeId, pub span: Span, pub vis: Visibility, /// The name of the item. /// It might be a dummy name in case of anonymous items. pub ident: Ident, pub kind: K, /// Original tokens this item was parsed from. This isn't necessarily /// available for all items, although over time more and more items should /// have this be `Some`. Right now this is primarily used for procedural /// macros, notably custom attributes. /// /// Note that the tokens here do not include the outer attributes, but will /// include inner attributes. pub tokens: Option<LazyTokenStream>, } impl Item { /// Return the span that encompasses the attributes. pub fn span_with_attributes(&self) -> Span { self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span)) } } /// `extern` qualifier on a function item or function type. #[derive(Clone, Copy, Encodable, Decodable, Debug)] pub enum Extern { None, Implicit, Explicit(StrLit), } impl Extern { pub fn from_abi(abi: Option<StrLit>) -> Extern { abi.map_or(Extern::Implicit, Extern::Explicit) } } /// A function header. /// /// All the information between the visibility and the name of the function is /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`). #[derive(Clone, Copy, Encodable, Decodable, Debug)] pub struct FnHeader { pub unsafety: Unsafe, pub asyncness: Async, pub constness: Const, pub ext: Extern, } impl FnHeader { /// Does this function header have any qualifiers or is it empty? pub fn has_qualifiers(&self) -> bool { let Self { unsafety, asyncness, constness, ext } = self; matches!(unsafety, Unsafe::Yes(_)) || asyncness.is_async() || matches!(constness, Const::Yes(_)) || !matches!(ext, Extern::None) } } impl Default for FnHeader { fn default() -> FnHeader { FnHeader { unsafety: Unsafe::No, asyncness: Async::No, constness: Const::No, ext: Extern::None, } } } #[derive(Clone, Encodable, Decodable, Debug)] pub struct Trait { pub unsafety: Unsafe, pub is_auto: IsAuto, pub generics: Generics, pub bounds: GenericBounds, pub items: Vec<P<AssocItem>>, } /// The location of a where clause on a `TyAlias` (`Span`) and whether there was /// a `where` keyword (`bool`). This is split out from `WhereClause`, since there /// are two locations for where clause on type aliases, but their predicates /// are concatenated together. /// /// Take this example: /// ```ignore (only-for-syntax-highlight) /// trait Foo { /// type Assoc<'a, 'b> where Self: 'a, Self: 'b; /// } /// impl Foo for () { /// type Assoc<'a, 'b> where Self: 'a = () where Self: 'b; /// // ^^^^^^^^^^^^^^ first where clause /// // ^^^^^^^^^^^^^^ second where clause /// } /// ``` /// /// If there is no where clause, then this is `false` with `DUMMY_SP`. #[derive(Copy, Clone, Encodable, Decodable, Debug, Default)] pub struct TyAliasWhereClause(pub bool, pub Span); #[derive(Clone, Encodable, Decodable, Debug)] pub struct TyAlias { pub defaultness: Defaultness, pub generics: Generics, /// The span information for the two where clauses (before equals, after equals) pub where_clauses: (TyAliasWhereClause, TyAliasWhereClause), /// The index in `generics.where_clause.predicates` that would split into /// predicates from the where clause before the equals and the predicates /// from the where clause after the equals pub where_predicates_split: usize, pub bounds: GenericBounds, pub ty: Option<P<Ty>>, } #[derive(Clone, Encodable, Decodable, Debug)] pub struct Impl { pub defaultness: Defaultness, pub unsafety: Unsafe, pub generics: Generics, pub constness: Const, pub polarity: ImplPolarity, /// The trait being implemented, if any. pub of_trait: Option<TraitRef>, pub self_ty: P<Ty>, pub items: Vec<P<AssocItem>>, } #[derive(Clone, Encodable, Decodable, Debug)] pub struct Fn { pub defaultness: Defaultness, pub generics: Generics, pub sig: FnSig, pub body: Option<P<Block>>, } #[derive(Clone, Encodable, Decodable, Debug)] pub enum ItemKind { /// An `extern crate` item, with the optional *original* crate name if the crate was renamed. /// /// E.g., `extern crate foo` or `extern crate foo_bar as foo`. ExternCrate(Option<Symbol>), /// A use declaration item (`use`). /// /// E.g., `use foo;`, `use foo::bar;` or `use foo::bar as FooBar;`. Use(UseTree), /// A static item (`static`). /// /// E.g., `static FOO: i32 = 42;` or `static FOO: &'static str = "bar";`. Static(P<Ty>, Mutability, Option<P<Expr>>), /// A constant item (`const`). /// /// E.g., `const FOO: i32 = 42;`. Const(Defaultness, P<Ty>, Option<P<Expr>>), /// A function declaration (`fn`). /// /// E.g., `fn foo(bar: usize) -> usize { .. }`. Fn(Box<Fn>), /// A module declaration (`mod`). /// /// E.g., `mod foo;` or `mod foo { .. }`. /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not /// semantically by Rust. Mod(Unsafe, ModKind), /// An external module (`extern`). /// /// E.g., `extern {}` or `extern "C" {}`. ForeignMod(ForeignMod), /// Module-level inline assembly (from `global_asm!()`). GlobalAsm(Box<InlineAsm>), /// A type alias (`type`). /// /// E.g., `type Foo = Bar<u8>;`. TyAlias(Box<TyAlias>), /// An enum definition (`enum`). /// /// E.g., `enum Foo<A, B> { C<A>, D<B> }`. Enum(EnumDef, Generics), /// A struct definition (`struct`). /// /// E.g., `struct Foo<A> { x: A }`. Struct(VariantData, Generics), /// A union definition (`union`). /// /// E.g., `union Foo<A, B> { x: A, y: B }`. Union(VariantData, Generics), /// A trait declaration (`trait`). /// /// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`. Trait(Box<Trait>), /// Trait alias /// /// E.g., `trait Foo = Bar + Quux;`. TraitAlias(Generics, GenericBounds), /// An implementation. /// /// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`. Impl(Box<Impl>), /// A macro invocation. /// /// E.g., `foo!(..)`. MacCall(MacCall), /// A macro definition. MacroDef(MacroDef), } #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] rustc_data_structures::static_assert_size!(ItemKind, 112); impl ItemKind { pub fn article(&self) -> &str { use ItemKind::*; match self { Use(..) | Static(..) | Const(..) | Fn(..) | Mod(..) | GlobalAsm(..) | TyAlias(..) | Struct(..) | Union(..) | Trait(..) | TraitAlias(..) | MacroDef(..) => "a", ExternCrate(..) | ForeignMod(..) | MacCall(..) | Enum(..) | Impl { .. } => "an", } } pub fn descr(&self) -> &str { match self { ItemKind::ExternCrate(..) => "extern crate", ItemKind::Use(..) => "`use` import", ItemKind::Static(..) => "static item", ItemKind::Const(..) => "constant item", ItemKind::Fn(..) => "function", ItemKind::Mod(..) => "module", ItemKind::ForeignMod(..) => "extern block", ItemKind::GlobalAsm(..) => "global asm item", ItemKind::TyAlias(..) => "type alias", ItemKind::Enum(..) => "enum", ItemKind::Struct(..) => "struct", ItemKind::Union(..) => "union", ItemKind::Trait(..) => "trait", ItemKind::TraitAlias(..) => "trait alias", ItemKind::MacCall(..) => "item macro invocation", ItemKind::MacroDef(..) => "macro definition", ItemKind::Impl { .. } => "implementation", } } pub fn generics(&self) -> Option<&Generics> { match self { Self::Fn(box Fn { generics, .. }) | Self::TyAlias(box TyAlias { generics, .. }) | Self::Enum(_, generics) | Self::Struct(_, generics) | Self::Union(_, generics) | Self::Trait(box Trait { generics, .. }) | Self::TraitAlias(generics, _) | Self::Impl(box Impl { generics, .. }) => Some(generics), _ => None, } } } /// Represents associated items. /// These include items in `impl` and `trait` definitions. pub type AssocItem = Item<AssocItemKind>; /// Represents associated item kinds. /// /// The term "provided" in the variants below refers to the item having a default /// definition / body. Meanwhile, a "required" item lacks a definition / body. /// In an implementation, all items must be provided. /// The `Option`s below denote the bodies, where `Some(_)` /// means "provided" and conversely `None` means "required". #[derive(Clone, Encodable, Decodable, Debug)] pub enum AssocItemKind { /// An associated constant, `const $ident: $ty $def?;` where `def ::= "=" $expr? ;`. /// If `def` is parsed, then the constant is provided, and otherwise required. Const(Defaultness, P<Ty>, Option<P<Expr>>), /// An associated function. Fn(Box<Fn>), /// An associated type. TyAlias(Box<TyAlias>), /// A macro expanding to associated items. MacCall(MacCall), } #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] rustc_data_structures::static_assert_size!(AssocItemKind, 72); impl AssocItemKind { pub fn defaultness(&self) -> Defaultness { match *self { Self::Const(defaultness, ..) | Self::Fn(box Fn { defaultness, .. }) | Self::TyAlias(box TyAlias { defaultness, .. }) => defaultness, Self::MacCall(..) => Defaultness::Final, } } } impl From<AssocItemKind> for ItemKind { fn from(assoc_item_kind: AssocItemKind) -> ItemKind { match assoc_item_kind { AssocItemKind::Const(a, b, c) => ItemKind::Const(a, b, c), AssocItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind), AssocItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind), AssocItemKind::MacCall(a) => ItemKind::MacCall(a), } } } impl TryFrom<ItemKind> for AssocItemKind { type Error = ItemKind; fn try_from(item_kind: ItemKind) -> Result<AssocItemKind, ItemKind> { Ok(match item_kind { ItemKind::Const(a, b, c) => AssocItemKind::Const(a, b, c), ItemKind::Fn(fn_kind) => AssocItemKind::Fn(fn_kind), ItemKind::TyAlias(ty_alias_kind) => AssocItemKind::TyAlias(ty_alias_kind), ItemKind::MacCall(a) => AssocItemKind::MacCall(a), _ => return Err(item_kind), }) } } /// An item in `extern` block. #[derive(Clone, Encodable, Decodable, Debug)] pub enum ForeignItemKind { /// A foreign static item (`static FOO: u8`). Static(P<Ty>, Mutability, Option<P<Expr>>), /// An foreign function. Fn(Box<Fn>), /// An foreign type. TyAlias(Box<TyAlias>), /// A macro expanding to foreign items. MacCall(MacCall), } #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] rustc_data_structures::static_assert_size!(ForeignItemKind, 72); impl From<ForeignItemKind> for ItemKind { fn from(foreign_item_kind: ForeignItemKind) -> ItemKind { match foreign_item_kind { ForeignItemKind::Static(a, b, c) => ItemKind::Static(a, b, c), ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind), ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind), ForeignItemKind::MacCall(a) => ItemKind::MacCall(a), } } } impl TryFrom<ItemKind> for ForeignItemKind { type Error = ItemKind; fn try_from(item_kind: ItemKind) -> Result<ForeignItemKind, ItemKind> { Ok(match item_kind { ItemKind::Static(a, b, c) => ForeignItemKind::Static(a, b, c), ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind), ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind), ItemKind::MacCall(a) => ForeignItemKind::MacCall(a), _ => return Err(item_kind), }) } } pub type ForeignItem = Item<ForeignItemKind>;
31.011694
101
0.579209
abecbf538b8047d2142b77f81691034269065a42
454
use core::ops::Range; use easy_ext::ext; use crate::inherent::Sealed; #[ext] pub impl<T> [T] where Self: Sealed<[T]> { fn as_ptr_range(&self) -> Range<*const T> { let start = self.as_ptr(); let end = unsafe { start.add(self.len()) }; start..end } fn as_mut_ptr_range(&mut self) -> Range<*mut T> { let start = self.as_mut_ptr(); let end = unsafe { start.add(self.len()) }; start..end } }
20.636364
53
0.555066
c1f1a3311b0d8b40dd6072cd80c3c179df6136e3
2,164
use core::ffi::c_void; use core::ptr::null_mut; use crate::basic_types::c_int; use crate::basic_types::c_char; use crate::basic_types::c_uchar; use crate::basic_types::size_t; #[no_mangle] pub extern "C" fn memchr(src: *const c_void, c: c_int, n: size_t) -> *mut c_void { let src1: *const c_char = src as *const c_char; let mut i = n; unsafe { while i > 0 { i -= 1; if *src1.add(i) == (c as c_char) { return src1.add(i) as *mut c_void; } } } return null_mut(); } #[no_mangle] pub extern "C" fn memcmp(cx: *const c_void, ct: *const c_void, n: size_t) -> c_int { let cx1: *const c_uchar = cx as *const c_uchar; let ct1: *const c_uchar = ct as *const c_uchar; let mut i = n; while i > 0 { i -= 1; unsafe { let cx2: c_uchar = *(cx1).add(i); let ct2: c_uchar = *(ct1).add(i); if cx2 != ct2 { return (cx2 - ct2).into(); } } } return 0; } // Adopted from Redox OS #[no_mangle] pub extern "C" fn memccpy(dest: *mut c_void, src: *const c_void, c: c_int, n: size_t) -> *mut c_void { let to = memchr(src, c, n); if to.is_null() { return to; } let dist = (to as usize) - (src as usize); if memcpy(dest, src, dist).is_null() { return null_mut(); } unsafe { return (dest as *mut u8).add(dist + 1) as *mut c_void; } } #[no_mangle] pub extern "C" fn memcpy(dest: *mut c_void, src: *const c_void, n: size_t) -> *mut c_void { return memmove(dest, src, n); } #[no_mangle] pub extern "C" fn memmove(dest: *mut c_void, src: *const c_void, n: size_t) -> *mut c_void { let dest1: *mut c_char = dest as *mut c_char; let src1: *const c_char = src as *const c_char; if (dest1 as *const c_char) < src1 { let mut i = 0; while i < n { unsafe { *(dest1).add(i) = *(src1).add(i); } i += 1; } } else if (dest1 as *const c_char) > src1 { let mut i = n; while i > 0 { i -= 1; unsafe { *(dest1).add(i) = *(src1).add(i); } } } return dest; } #[no_mangle] pub extern "C" fn memset(dest: *mut c_void, c: c_int, n: size_t) -> *mut c_void { let dest1: *mut c_char = dest as *mut c_char; let mut i = n; while i > 0 { i -= 1; unsafe { *(dest1).add(i) = c as c_char; } } return dest; }
20.807692
102
0.597043
5deae94fe0c8e785086b005f72b626051e1e9d43
2,186
use std::error::Error; use std::fmt; use rustc_middle::mir::AssertKind; use rustc_span::{Span, Symbol}; use super::InterpCx; use crate::interpret::{ConstEvalErr, InterpErrorInfo, Machine}; /// The CTFE machine has some custom error kinds. #[derive(Clone, Debug)] pub enum ConstEvalErrKind { NeedsRfc(String), ConstAccessesStatic, ModifiedGlobal, AssertFailure(AssertKind<u64>), Panic { msg: Symbol, line: u32, col: u32, file: Symbol }, } // The errors become `MachineStop` with plain strings when being raised. // `ConstEvalErr` (in `librustc_middle/mir/interpret/error.rs`) knows to // handle these. impl<'tcx> Into<InterpErrorInfo<'tcx>> for ConstEvalErrKind { fn into(self) -> InterpErrorInfo<'tcx> { err_machine_stop!(self.to_string()).into() } } impl fmt::Display for ConstEvalErrKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::ConstEvalErrKind::*; match *self { NeedsRfc(ref msg) => { write!(f, "\"{}\" needs an rfc before being allowed inside constants", msg) } ConstAccessesStatic => write!(f, "constant accesses static"), ModifiedGlobal => { write!(f, "modifying a static's initial value from another static's initializer") } AssertFailure(ref msg) => write!(f, "{:?}", msg), Panic { msg, line, col, file } => { write!(f, "the evaluated program panicked at '{}', {}:{}:{}", msg, file, line, col) } } } } impl Error for ConstEvalErrKind {} /// Turn an interpreter error into something to report to the user. /// As a side-effect, if RUSTC_CTFE_BACKTRACE is set, this prints the backtrace. /// Should be called only if the error is actually going to to be reported! pub fn error_to_const_error<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>>( ecx: &InterpCx<'mir, 'tcx, M>, error: InterpErrorInfo<'tcx>, span: Option<Span>, ) -> ConstEvalErr<'tcx> { error.print_backtrace(); let stacktrace = ecx.generate_stacktrace(); ConstEvalErr { error: error.kind, stacktrace, span: span.unwrap_or_else(|| ecx.cur_span()) } }
35.258065
99
0.635407
fbe4ecdfe16d07e8508adc81ab352834b06cff86
546
use super::region::*; use super::region_id::*; use flo_curves::bezier::path::*; use std::time::{Duration}; /// /// Collects a list of animation regions into a set of IDs and paths /// pub fn collect_regions<'a, Region: 'a+AnimationRegion, RegionIter: IntoIterator<Item=&'a Region>>(regions: RegionIter, time: Duration) -> Vec<(RegionId, Vec<SimpleBezierPath>)> { regions .into_iter() .enumerate() .map(|(region_idx, region)| { (RegionId(region_idx), region.region(time)) }) .collect() }
27.3
178
0.630037
d752b9e7e6f2f9fffb75b72dac116ace3c056e1c
31
pub mod pty; pub mod sessions;
10.333333
17
0.741935
390ca53738bfaa26f650fbf3a4d129a55154557b
4,185
use crate::serialization::op_code::OpCode; use crate::serialization::sigma_byte_reader::SigmaByteRead; use crate::serialization::sigma_byte_writer::SigmaByteWrite; use crate::serialization::SigmaParsingError; use crate::serialization::SigmaSerializable; use crate::serialization::SigmaSerializeResult; // use crate::types::stuple::STuple; use crate::types::stype::SType; use super::expr::Expr; use super::expr::InvalidArgumentError; use crate::has_opcode::HasStaticOpCode; /// Takes two collections as input and produces the concatenated collection (input + col2) #[derive(PartialEq, Eq, Debug, Clone)] pub struct Append { /// Collection - First Parameter; first half of the combined collection pub input: Box<Expr>, /// Collection - Second Parameter; later half of the combined collection pub col_2: Box<Expr>, } impl Append { /// Create new object, returns an error if any of the requirements failed pub fn new(input: Expr, col_2: Expr) -> Result<Self, InvalidArgumentError> { match (input.post_eval_tpe(), col_2.post_eval_tpe()) { (SType::SColl(x), SType::SColl(y)) => { if x == y { Ok(Append{input: input.into(), col_2: col_2.into()}) } else { Err(InvalidArgumentError(format!( "Expected Append input and col_2 collection to have the same types; got input={0:?} col_2={1:?}", x, y))) } } (SType::SColl(_), _) => { Err(InvalidArgumentError(format!( "Expected Append col_2 param to be a collection; got col_2={:?}", col_2.tpe()))) } (_, SType::SColl(_)) => { Err(InvalidArgumentError(format!( "Expected Append input param to be a collection; got input={:?}", input.tpe()))) }, (_, _) => { Err(InvalidArgumentError(format!( "Expected Append input and col_2 param to be a collection; got input={:?} col_2={:?}", input.tpe(), col_2.tpe()))) } } } /// Type pub fn tpe(&self) -> SType { // Type is supposed to be the same on input and col_2 // Append::new checks types but later modifications are unchecked // return type of input collection self.input.tpe() } } impl HasStaticOpCode for Append { const OP_CODE: OpCode = OpCode::APPEND; } impl SigmaSerializable for Append { fn sigma_serialize<W: SigmaByteWrite>(&self, w: &mut W) -> SigmaSerializeResult { self.input.sigma_serialize(w)?; self.col_2.sigma_serialize(w)?; Ok(()) } fn sigma_parse<R: SigmaByteRead>(r: &mut R) -> Result<Self, SigmaParsingError> { let input = Expr::sigma_parse(r)?; let col_2 = Expr::sigma_parse(r)?; Ok(Append::new(input, col_2)?) } } #[cfg(test)] #[cfg(feature = "arbitrary")] #[allow(clippy::panic)] mod tests { use super::*; use crate::mir::expr::arbitrary::ArbExprParams; use crate::mir::expr::Expr; use crate::serialization::sigma_serialize_roundtrip; use proptest::prelude::*; impl Arbitrary for Append { type Strategy = BoxedStrategy<Self>; type Parameters = (); fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy { ( any_with::<Expr>(ArbExprParams { tpe: SType::SColl(SType::SBoolean.into()), depth: 1, }), any_with::<Expr>(ArbExprParams { tpe: SType::SColl(SType::SBoolean.into()), depth: 1, }), ) .prop_map(|(input, col_2)| Self { input: input.into(), col_2: col_2.into(), }) .boxed() } } proptest! { #![proptest_config(ProptestConfig::with_cases(16))] #[test] fn ser_roundtrip(v in any::<Append>()) { let expr: Expr = v.into(); prop_assert_eq![sigma_serialize_roundtrip(&expr), expr]; } } }
34.303279
137
0.564158
09ef1b4e5ebc326a2659a5a141fae3844a605a2e
138,312
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. use std::fmt::Write; /// See [`CancelJobRunInput`](crate::input::CancelJobRunInput) pub mod cancel_job_run_input { /// A builder for [`CancelJobRunInput`](crate::input::CancelJobRunInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) id: std::option::Option<std::string::String>, pub(crate) virtual_cluster_id: std::option::Option<std::string::String>, } impl Builder { /// <p>The ID of the job run to cancel.</p> pub fn id(mut self, input: impl Into<std::string::String>) -> Self { self.id = Some(input.into()); self } pub fn set_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.id = input; self } /// <p>The ID of the virtual cluster for which the job run will be canceled.</p> pub fn virtual_cluster_id(mut self, input: impl Into<std::string::String>) -> Self { self.virtual_cluster_id = Some(input.into()); self } pub fn set_virtual_cluster_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.virtual_cluster_id = input; self } /// Consumes the builder and constructs a [`CancelJobRunInput`](crate::input::CancelJobRunInput) pub fn build( self, ) -> std::result::Result<crate::input::CancelJobRunInput, smithy_http::operation::BuildError> { Ok(crate::input::CancelJobRunInput { id: self.id, virtual_cluster_id: self.virtual_cluster_id, }) } } } #[doc(hidden)] pub type CancelJobRunInputOperationOutputAlias = crate::operation::CancelJobRun; #[doc(hidden)] pub type CancelJobRunInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CancelJobRunInput { /// Consumes the builder and constructs an Operation<[`CancelJobRun`](crate::operation::CancelJobRun)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::CancelJobRun, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::CancelJobRun::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "CancelJobRun", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { let input_1 = &self.virtual_cluster_id; let input_1 = input_1 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", })?; let virtual_cluster_id = smithy_http::label::fmt_string(input_1, false); if virtual_cluster_id.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", }); } let input_2 = &self.id; let input_2 = input_2 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "id", details: "cannot be empty or unset", })?; let id = smithy_http::label::fmt_string(input_2, false); if id.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "id", details: "cannot be empty or unset", }); } write!( output, "/virtualclusters/{virtualClusterId}/jobruns/{id}", virtualClusterId = virtual_cluster_id, id = id ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CancelJobRunInput`](crate::input::CancelJobRunInput) pub fn builder() -> crate::input::cancel_job_run_input::Builder { crate::input::cancel_job_run_input::Builder::default() } } /// See [`CreateManagedEndpointInput`](crate::input::CreateManagedEndpointInput) pub mod create_managed_endpoint_input { /// A builder for [`CreateManagedEndpointInput`](crate::input::CreateManagedEndpointInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) name: std::option::Option<std::string::String>, pub(crate) virtual_cluster_id: std::option::Option<std::string::String>, pub(crate) r#type: std::option::Option<std::string::String>, pub(crate) release_label: std::option::Option<std::string::String>, pub(crate) execution_role_arn: std::option::Option<std::string::String>, pub(crate) certificate_arn: std::option::Option<std::string::String>, pub(crate) configuration_overrides: std::option::Option<crate::model::ConfigurationOverrides>, pub(crate) client_token: std::option::Option<std::string::String>, pub(crate) tags: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, } impl Builder { /// <p>The name of the managed endpoint.</p> pub fn name(mut self, input: impl Into<std::string::String>) -> Self { self.name = Some(input.into()); self } pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.name = input; self } /// <p>The ID of the virtual cluster for which a managed endpoint is created.</p> pub fn virtual_cluster_id(mut self, input: impl Into<std::string::String>) -> Self { self.virtual_cluster_id = Some(input.into()); self } pub fn set_virtual_cluster_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.virtual_cluster_id = input; self } /// <p>The type of the managed endpoint.</p> pub fn r#type(mut self, input: impl Into<std::string::String>) -> Self { self.r#type = Some(input.into()); self } pub fn set_type(mut self, input: std::option::Option<std::string::String>) -> Self { self.r#type = input; self } /// <p>The Amazon EMR release version.</p> pub fn release_label(mut self, input: impl Into<std::string::String>) -> Self { self.release_label = Some(input.into()); self } pub fn set_release_label( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.release_label = input; self } /// <p>The ARN of the execution role.</p> pub fn execution_role_arn(mut self, input: impl Into<std::string::String>) -> Self { self.execution_role_arn = Some(input.into()); self } pub fn set_execution_role_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.execution_role_arn = input; self } /// <p>The certificate ARN of the managed endpoint.</p> pub fn certificate_arn(mut self, input: impl Into<std::string::String>) -> Self { self.certificate_arn = Some(input.into()); self } pub fn set_certificate_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.certificate_arn = input; self } /// <p>The configuration settings that will be used to override existing configurations.</p> pub fn configuration_overrides( mut self, input: crate::model::ConfigurationOverrides, ) -> Self { self.configuration_overrides = Some(input); self } pub fn set_configuration_overrides( mut self, input: std::option::Option<crate::model::ConfigurationOverrides>, ) -> Self { self.configuration_overrides = input; self } /// <p>The client idempotency token for this create call.</p> pub fn client_token(mut self, input: impl Into<std::string::String>) -> Self { self.client_token = Some(input.into()); self } pub fn set_client_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.client_token = input; self } pub fn tags( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.tags.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.tags = Some(hash_map); self } pub fn set_tags( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.tags = input; self } /// Consumes the builder and constructs a [`CreateManagedEndpointInput`](crate::input::CreateManagedEndpointInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateManagedEndpointInput, smithy_http::operation::BuildError, > { Ok(crate::input::CreateManagedEndpointInput { name: self.name, virtual_cluster_id: self.virtual_cluster_id, r#type: self.r#type, release_label: self.release_label, execution_role_arn: self.execution_role_arn, certificate_arn: self.certificate_arn, configuration_overrides: self.configuration_overrides, client_token: self.client_token, tags: self.tags, }) } } } #[doc(hidden)] pub type CreateManagedEndpointInputOperationOutputAlias = crate::operation::CreateManagedEndpoint; #[doc(hidden)] pub type CreateManagedEndpointInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateManagedEndpointInput { /// Consumes the builder and constructs an Operation<[`CreateManagedEndpoint`](crate::operation::CreateManagedEndpoint)> #[allow(clippy::let_and_return)] pub fn make_operation( mut self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::CreateManagedEndpoint, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ if self.client_token.is_none() { self.client_token = Some(_config.make_token.make_idempotency_token()); } let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_create_managed_endpoint(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::CreateManagedEndpoint::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "CreateManagedEndpoint", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { let input_3 = &self.virtual_cluster_id; let input_3 = input_3 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", })?; let virtual_cluster_id = smithy_http::label::fmt_string(input_3, false); if virtual_cluster_id.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", }); } write!( output, "/virtualclusters/{virtualClusterId}/endpoints", virtualClusterId = virtual_cluster_id ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateManagedEndpointInput`](crate::input::CreateManagedEndpointInput) pub fn builder() -> crate::input::create_managed_endpoint_input::Builder { crate::input::create_managed_endpoint_input::Builder::default() } } /// See [`CreateVirtualClusterInput`](crate::input::CreateVirtualClusterInput) pub mod create_virtual_cluster_input { /// A builder for [`CreateVirtualClusterInput`](crate::input::CreateVirtualClusterInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) name: std::option::Option<std::string::String>, pub(crate) container_provider: std::option::Option<crate::model::ContainerProvider>, pub(crate) client_token: std::option::Option<std::string::String>, pub(crate) tags: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, } impl Builder { /// <p>The specified name of the virtual cluster.</p> pub fn name(mut self, input: impl Into<std::string::String>) -> Self { self.name = Some(input.into()); self } pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.name = input; self } /// <p>The container provider of the virtual cluster.</p> pub fn container_provider(mut self, input: crate::model::ContainerProvider) -> Self { self.container_provider = Some(input); self } pub fn set_container_provider( mut self, input: std::option::Option<crate::model::ContainerProvider>, ) -> Self { self.container_provider = input; self } /// <p>The client token of the virtual cluster.</p> pub fn client_token(mut self, input: impl Into<std::string::String>) -> Self { self.client_token = Some(input.into()); self } pub fn set_client_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.client_token = input; self } pub fn tags( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.tags.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.tags = Some(hash_map); self } pub fn set_tags( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.tags = input; self } /// Consumes the builder and constructs a [`CreateVirtualClusterInput`](crate::input::CreateVirtualClusterInput) pub fn build( self, ) -> std::result::Result< crate::input::CreateVirtualClusterInput, smithy_http::operation::BuildError, > { Ok(crate::input::CreateVirtualClusterInput { name: self.name, container_provider: self.container_provider, client_token: self.client_token, tags: self.tags, }) } } } #[doc(hidden)] pub type CreateVirtualClusterInputOperationOutputAlias = crate::operation::CreateVirtualCluster; #[doc(hidden)] pub type CreateVirtualClusterInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl CreateVirtualClusterInput { /// Consumes the builder and constructs an Operation<[`CreateVirtualCluster`](crate::operation::CreateVirtualCluster)> #[allow(clippy::let_and_return)] pub fn make_operation( mut self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::CreateVirtualCluster, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ if self.client_token.is_none() { self.client_token = Some(_config.make_token.make_idempotency_token()); } let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_create_virtual_cluster(&self) .map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::CreateVirtualCluster::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "CreateVirtualCluster", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/virtualclusters").expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`CreateVirtualClusterInput`](crate::input::CreateVirtualClusterInput) pub fn builder() -> crate::input::create_virtual_cluster_input::Builder { crate::input::create_virtual_cluster_input::Builder::default() } } /// See [`DeleteManagedEndpointInput`](crate::input::DeleteManagedEndpointInput) pub mod delete_managed_endpoint_input { /// A builder for [`DeleteManagedEndpointInput`](crate::input::DeleteManagedEndpointInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) id: std::option::Option<std::string::String>, pub(crate) virtual_cluster_id: std::option::Option<std::string::String>, } impl Builder { /// <p>The ID of the managed endpoint.</p> pub fn id(mut self, input: impl Into<std::string::String>) -> Self { self.id = Some(input.into()); self } pub fn set_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.id = input; self } /// <p>The ID of the endpoint's virtual cluster.</p> pub fn virtual_cluster_id(mut self, input: impl Into<std::string::String>) -> Self { self.virtual_cluster_id = Some(input.into()); self } pub fn set_virtual_cluster_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.virtual_cluster_id = input; self } /// Consumes the builder and constructs a [`DeleteManagedEndpointInput`](crate::input::DeleteManagedEndpointInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteManagedEndpointInput, smithy_http::operation::BuildError, > { Ok(crate::input::DeleteManagedEndpointInput { id: self.id, virtual_cluster_id: self.virtual_cluster_id, }) } } } #[doc(hidden)] pub type DeleteManagedEndpointInputOperationOutputAlias = crate::operation::DeleteManagedEndpoint; #[doc(hidden)] pub type DeleteManagedEndpointInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteManagedEndpointInput { /// Consumes the builder and constructs an Operation<[`DeleteManagedEndpoint`](crate::operation::DeleteManagedEndpoint)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::DeleteManagedEndpoint, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::DeleteManagedEndpoint::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "DeleteManagedEndpoint", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { let input_4 = &self.virtual_cluster_id; let input_4 = input_4 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", })?; let virtual_cluster_id = smithy_http::label::fmt_string(input_4, false); if virtual_cluster_id.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", }); } let input_5 = &self.id; let input_5 = input_5 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "id", details: "cannot be empty or unset", })?; let id = smithy_http::label::fmt_string(input_5, false); if id.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "id", details: "cannot be empty or unset", }); } write!( output, "/virtualclusters/{virtualClusterId}/endpoints/{id}", virtualClusterId = virtual_cluster_id, id = id ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteManagedEndpointInput`](crate::input::DeleteManagedEndpointInput) pub fn builder() -> crate::input::delete_managed_endpoint_input::Builder { crate::input::delete_managed_endpoint_input::Builder::default() } } /// See [`DeleteVirtualClusterInput`](crate::input::DeleteVirtualClusterInput) pub mod delete_virtual_cluster_input { /// A builder for [`DeleteVirtualClusterInput`](crate::input::DeleteVirtualClusterInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) id: std::option::Option<std::string::String>, } impl Builder { /// <p>The ID of the virtual cluster that will be deleted.</p> pub fn id(mut self, input: impl Into<std::string::String>) -> Self { self.id = Some(input.into()); self } pub fn set_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.id = input; self } /// Consumes the builder and constructs a [`DeleteVirtualClusterInput`](crate::input::DeleteVirtualClusterInput) pub fn build( self, ) -> std::result::Result< crate::input::DeleteVirtualClusterInput, smithy_http::operation::BuildError, > { Ok(crate::input::DeleteVirtualClusterInput { id: self.id }) } } } #[doc(hidden)] pub type DeleteVirtualClusterInputOperationOutputAlias = crate::operation::DeleteVirtualCluster; #[doc(hidden)] pub type DeleteVirtualClusterInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DeleteVirtualClusterInput { /// Consumes the builder and constructs an Operation<[`DeleteVirtualCluster`](crate::operation::DeleteVirtualCluster)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::DeleteVirtualCluster, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::DeleteVirtualCluster::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "DeleteVirtualCluster", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { let input_6 = &self.id; let input_6 = input_6 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "id", details: "cannot be empty or unset", })?; let id = smithy_http::label::fmt_string(input_6, false); if id.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "id", details: "cannot be empty or unset", }); } write!(output, "/virtualclusters/{id}", id = id).expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DeleteVirtualClusterInput`](crate::input::DeleteVirtualClusterInput) pub fn builder() -> crate::input::delete_virtual_cluster_input::Builder { crate::input::delete_virtual_cluster_input::Builder::default() } } /// See [`DescribeJobRunInput`](crate::input::DescribeJobRunInput) pub mod describe_job_run_input { /// A builder for [`DescribeJobRunInput`](crate::input::DescribeJobRunInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) id: std::option::Option<std::string::String>, pub(crate) virtual_cluster_id: std::option::Option<std::string::String>, } impl Builder { /// <p>The ID of the job run request. </p> pub fn id(mut self, input: impl Into<std::string::String>) -> Self { self.id = Some(input.into()); self } pub fn set_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.id = input; self } /// <p>The ID of the virtual cluster for which the job run is submitted.</p> pub fn virtual_cluster_id(mut self, input: impl Into<std::string::String>) -> Self { self.virtual_cluster_id = Some(input.into()); self } pub fn set_virtual_cluster_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.virtual_cluster_id = input; self } /// Consumes the builder and constructs a [`DescribeJobRunInput`](crate::input::DescribeJobRunInput) pub fn build( self, ) -> std::result::Result< crate::input::DescribeJobRunInput, smithy_http::operation::BuildError, > { Ok(crate::input::DescribeJobRunInput { id: self.id, virtual_cluster_id: self.virtual_cluster_id, }) } } } #[doc(hidden)] pub type DescribeJobRunInputOperationOutputAlias = crate::operation::DescribeJobRun; #[doc(hidden)] pub type DescribeJobRunInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DescribeJobRunInput { /// Consumes the builder and constructs an Operation<[`DescribeJobRun`](crate::operation::DescribeJobRun)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::DescribeJobRun, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::DescribeJobRun::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "DescribeJobRun", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { let input_7 = &self.virtual_cluster_id; let input_7 = input_7 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", })?; let virtual_cluster_id = smithy_http::label::fmt_string(input_7, false); if virtual_cluster_id.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", }); } let input_8 = &self.id; let input_8 = input_8 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "id", details: "cannot be empty or unset", })?; let id = smithy_http::label::fmt_string(input_8, false); if id.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "id", details: "cannot be empty or unset", }); } write!( output, "/virtualclusters/{virtualClusterId}/jobruns/{id}", virtualClusterId = virtual_cluster_id, id = id ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DescribeJobRunInput`](crate::input::DescribeJobRunInput) pub fn builder() -> crate::input::describe_job_run_input::Builder { crate::input::describe_job_run_input::Builder::default() } } /// See [`DescribeManagedEndpointInput`](crate::input::DescribeManagedEndpointInput) pub mod describe_managed_endpoint_input { /// A builder for [`DescribeManagedEndpointInput`](crate::input::DescribeManagedEndpointInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) id: std::option::Option<std::string::String>, pub(crate) virtual_cluster_id: std::option::Option<std::string::String>, } impl Builder { /// <p>This output displays ID of the managed endpoint.</p> pub fn id(mut self, input: impl Into<std::string::String>) -> Self { self.id = Some(input.into()); self } pub fn set_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.id = input; self } /// <p>The ID of the endpoint's virtual cluster.</p> pub fn virtual_cluster_id(mut self, input: impl Into<std::string::String>) -> Self { self.virtual_cluster_id = Some(input.into()); self } pub fn set_virtual_cluster_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.virtual_cluster_id = input; self } /// Consumes the builder and constructs a [`DescribeManagedEndpointInput`](crate::input::DescribeManagedEndpointInput) pub fn build( self, ) -> std::result::Result< crate::input::DescribeManagedEndpointInput, smithy_http::operation::BuildError, > { Ok(crate::input::DescribeManagedEndpointInput { id: self.id, virtual_cluster_id: self.virtual_cluster_id, }) } } } #[doc(hidden)] pub type DescribeManagedEndpointInputOperationOutputAlias = crate::operation::DescribeManagedEndpoint; #[doc(hidden)] pub type DescribeManagedEndpointInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DescribeManagedEndpointInput { /// Consumes the builder and constructs an Operation<[`DescribeManagedEndpoint`](crate::operation::DescribeManagedEndpoint)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::DescribeManagedEndpoint, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::DescribeManagedEndpoint::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "DescribeManagedEndpoint", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { let input_9 = &self.virtual_cluster_id; let input_9 = input_9 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", })?; let virtual_cluster_id = smithy_http::label::fmt_string(input_9, false); if virtual_cluster_id.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", }); } let input_10 = &self.id; let input_10 = input_10 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "id", details: "cannot be empty or unset", })?; let id = smithy_http::label::fmt_string(input_10, false); if id.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "id", details: "cannot be empty or unset", }); } write!( output, "/virtualclusters/{virtualClusterId}/endpoints/{id}", virtualClusterId = virtual_cluster_id, id = id ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DescribeManagedEndpointInput`](crate::input::DescribeManagedEndpointInput) pub fn builder() -> crate::input::describe_managed_endpoint_input::Builder { crate::input::describe_managed_endpoint_input::Builder::default() } } /// See [`DescribeVirtualClusterInput`](crate::input::DescribeVirtualClusterInput) pub mod describe_virtual_cluster_input { /// A builder for [`DescribeVirtualClusterInput`](crate::input::DescribeVirtualClusterInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) id: std::option::Option<std::string::String>, } impl Builder { /// <p>The ID of the virtual cluster that will be described.</p> pub fn id(mut self, input: impl Into<std::string::String>) -> Self { self.id = Some(input.into()); self } pub fn set_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.id = input; self } /// Consumes the builder and constructs a [`DescribeVirtualClusterInput`](crate::input::DescribeVirtualClusterInput) pub fn build( self, ) -> std::result::Result< crate::input::DescribeVirtualClusterInput, smithy_http::operation::BuildError, > { Ok(crate::input::DescribeVirtualClusterInput { id: self.id }) } } } #[doc(hidden)] pub type DescribeVirtualClusterInputOperationOutputAlias = crate::operation::DescribeVirtualCluster; #[doc(hidden)] pub type DescribeVirtualClusterInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl DescribeVirtualClusterInput { /// Consumes the builder and constructs an Operation<[`DescribeVirtualCluster`](crate::operation::DescribeVirtualCluster)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::DescribeVirtualCluster, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::DescribeVirtualCluster::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "DescribeVirtualCluster", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { let input_11 = &self.id; let input_11 = input_11 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "id", details: "cannot be empty or unset", })?; let id = smithy_http::label::fmt_string(input_11, false); if id.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "id", details: "cannot be empty or unset", }); } write!(output, "/virtualclusters/{id}", id = id).expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`DescribeVirtualClusterInput`](crate::input::DescribeVirtualClusterInput) pub fn builder() -> crate::input::describe_virtual_cluster_input::Builder { crate::input::describe_virtual_cluster_input::Builder::default() } } /// See [`ListJobRunsInput`](crate::input::ListJobRunsInput) pub mod list_job_runs_input { /// A builder for [`ListJobRunsInput`](crate::input::ListJobRunsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) virtual_cluster_id: std::option::Option<std::string::String>, pub(crate) created_before: std::option::Option<smithy_types::Instant>, pub(crate) created_after: std::option::Option<smithy_types::Instant>, pub(crate) name: std::option::Option<std::string::String>, pub(crate) states: std::option::Option<std::vec::Vec<crate::model::JobRunState>>, pub(crate) max_results: std::option::Option<i32>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// <p>The ID of the virtual cluster for which to list the job run. </p> pub fn virtual_cluster_id(mut self, input: impl Into<std::string::String>) -> Self { self.virtual_cluster_id = Some(input.into()); self } pub fn set_virtual_cluster_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.virtual_cluster_id = input; self } /// <p>The date and time before which the job runs were submitted.</p> pub fn created_before(mut self, input: smithy_types::Instant) -> Self { self.created_before = Some(input); self } pub fn set_created_before( mut self, input: std::option::Option<smithy_types::Instant>, ) -> Self { self.created_before = input; self } /// <p>The date and time after which the job runs were submitted.</p> pub fn created_after(mut self, input: smithy_types::Instant) -> Self { self.created_after = Some(input); self } pub fn set_created_after( mut self, input: std::option::Option<smithy_types::Instant>, ) -> Self { self.created_after = input; self } /// <p>The name of the job run.</p> pub fn name(mut self, input: impl Into<std::string::String>) -> Self { self.name = Some(input.into()); self } pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.name = input; self } pub fn states(mut self, input: impl Into<crate::model::JobRunState>) -> Self { let mut v = self.states.unwrap_or_default(); v.push(input.into()); self.states = Some(v); self } pub fn set_states( mut self, input: std::option::Option<std::vec::Vec<crate::model::JobRunState>>, ) -> Self { self.states = input; self } /// <p>The maximum number of job runs that can be listed.</p> pub fn max_results(mut self, input: i32) -> Self { self.max_results = Some(input); self } pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.max_results = input; self } /// <p>The token for the next set of job runs to return.</p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListJobRunsInput`](crate::input::ListJobRunsInput) pub fn build( self, ) -> std::result::Result<crate::input::ListJobRunsInput, smithy_http::operation::BuildError> { Ok(crate::input::ListJobRunsInput { virtual_cluster_id: self.virtual_cluster_id, created_before: self.created_before, created_after: self.created_after, name: self.name, states: self.states, max_results: self.max_results, next_token: self.next_token, }) } } } #[doc(hidden)] pub type ListJobRunsInputOperationOutputAlias = crate::operation::ListJobRuns; #[doc(hidden)] pub type ListJobRunsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListJobRunsInput { /// Consumes the builder and constructs an Operation<[`ListJobRuns`](crate::operation::ListJobRuns)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::ListJobRuns, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::ListJobRuns::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "ListJobRuns", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { let input_12 = &self.virtual_cluster_id; let input_12 = input_12 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", })?; let virtual_cluster_id = smithy_http::label::fmt_string(input_12, false); if virtual_cluster_id.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", }); } write!( output, "/virtualclusters/{virtualClusterId}/jobruns", virtualClusterId = virtual_cluster_id ) .expect("formatting should succeed"); Ok(()) } fn uri_query(&self, mut output: &mut String) { let mut query = smithy_http::query::Writer::new(&mut output); if let Some(inner_13) = &self.created_before { query.push_kv( "createdBefore", &smithy_http::query::fmt_timestamp( inner_13, smithy_types::instant::Format::DateTime, ), ); } if let Some(inner_14) = &self.created_after { query.push_kv( "createdAfter", &smithy_http::query::fmt_timestamp( inner_14, smithy_types::instant::Format::DateTime, ), ); } if let Some(inner_15) = &self.name { query.push_kv("name", &smithy_http::query::fmt_string(&inner_15)); } if let Some(inner_16) = &self.states { for inner_17 in inner_16 { query.push_kv("states", &smithy_http::query::fmt_string(&inner_17)); } } if let Some(inner_18) = &self.max_results { query.push_kv( "maxResults", &smithy_types::primitive::Encoder::from(*inner_18).encode(), ); } if let Some(inner_19) = &self.next_token { query.push_kv("nextToken", &smithy_http::query::fmt_string(&inner_19)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; self.uri_query(&mut uri); Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListJobRunsInput`](crate::input::ListJobRunsInput) pub fn builder() -> crate::input::list_job_runs_input::Builder { crate::input::list_job_runs_input::Builder::default() } } /// See [`ListManagedEndpointsInput`](crate::input::ListManagedEndpointsInput) pub mod list_managed_endpoints_input { /// A builder for [`ListManagedEndpointsInput`](crate::input::ListManagedEndpointsInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) virtual_cluster_id: std::option::Option<std::string::String>, pub(crate) created_before: std::option::Option<smithy_types::Instant>, pub(crate) created_after: std::option::Option<smithy_types::Instant>, pub(crate) types: std::option::Option<std::vec::Vec<std::string::String>>, pub(crate) states: std::option::Option<std::vec::Vec<crate::model::EndpointState>>, pub(crate) max_results: std::option::Option<i32>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// <p>The ID of the virtual cluster.</p> pub fn virtual_cluster_id(mut self, input: impl Into<std::string::String>) -> Self { self.virtual_cluster_id = Some(input.into()); self } pub fn set_virtual_cluster_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.virtual_cluster_id = input; self } /// <p>The date and time before which the endpoints are created.</p> pub fn created_before(mut self, input: smithy_types::Instant) -> Self { self.created_before = Some(input); self } pub fn set_created_before( mut self, input: std::option::Option<smithy_types::Instant>, ) -> Self { self.created_before = input; self } /// <p> The date and time after which the endpoints are created.</p> pub fn created_after(mut self, input: smithy_types::Instant) -> Self { self.created_after = Some(input); self } pub fn set_created_after( mut self, input: std::option::Option<smithy_types::Instant>, ) -> Self { self.created_after = input; self } pub fn types(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.types.unwrap_or_default(); v.push(input.into()); self.types = Some(v); self } pub fn set_types( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.types = input; self } pub fn states(mut self, input: impl Into<crate::model::EndpointState>) -> Self { let mut v = self.states.unwrap_or_default(); v.push(input.into()); self.states = Some(v); self } pub fn set_states( mut self, input: std::option::Option<std::vec::Vec<crate::model::EndpointState>>, ) -> Self { self.states = input; self } /// <p>The maximum number of managed endpoints that can be listed.</p> pub fn max_results(mut self, input: i32) -> Self { self.max_results = Some(input); self } pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.max_results = input; self } /// <p> The token for the next set of managed endpoints to return. </p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListManagedEndpointsInput`](crate::input::ListManagedEndpointsInput) pub fn build( self, ) -> std::result::Result< crate::input::ListManagedEndpointsInput, smithy_http::operation::BuildError, > { Ok(crate::input::ListManagedEndpointsInput { virtual_cluster_id: self.virtual_cluster_id, created_before: self.created_before, created_after: self.created_after, types: self.types, states: self.states, max_results: self.max_results, next_token: self.next_token, }) } } } #[doc(hidden)] pub type ListManagedEndpointsInputOperationOutputAlias = crate::operation::ListManagedEndpoints; #[doc(hidden)] pub type ListManagedEndpointsInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListManagedEndpointsInput { /// Consumes the builder and constructs an Operation<[`ListManagedEndpoints`](crate::operation::ListManagedEndpoints)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::ListManagedEndpoints, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::ListManagedEndpoints::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "ListManagedEndpoints", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { let input_20 = &self.virtual_cluster_id; let input_20 = input_20 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", })?; let virtual_cluster_id = smithy_http::label::fmt_string(input_20, false); if virtual_cluster_id.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", }); } write!( output, "/virtualclusters/{virtualClusterId}/endpoints", virtualClusterId = virtual_cluster_id ) .expect("formatting should succeed"); Ok(()) } fn uri_query(&self, mut output: &mut String) { let mut query = smithy_http::query::Writer::new(&mut output); if let Some(inner_21) = &self.created_before { query.push_kv( "createdBefore", &smithy_http::query::fmt_timestamp( inner_21, smithy_types::instant::Format::DateTime, ), ); } if let Some(inner_22) = &self.created_after { query.push_kv( "createdAfter", &smithy_http::query::fmt_timestamp( inner_22, smithy_types::instant::Format::DateTime, ), ); } if let Some(inner_23) = &self.types { for inner_24 in inner_23 { query.push_kv("types", &smithy_http::query::fmt_string(&inner_24)); } } if let Some(inner_25) = &self.states { for inner_26 in inner_25 { query.push_kv("states", &smithy_http::query::fmt_string(&inner_26)); } } if let Some(inner_27) = &self.max_results { query.push_kv( "maxResults", &smithy_types::primitive::Encoder::from(*inner_27).encode(), ); } if let Some(inner_28) = &self.next_token { query.push_kv("nextToken", &smithy_http::query::fmt_string(&inner_28)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; self.uri_query(&mut uri); Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListManagedEndpointsInput`](crate::input::ListManagedEndpointsInput) pub fn builder() -> crate::input::list_managed_endpoints_input::Builder { crate::input::list_managed_endpoints_input::Builder::default() } } /// See [`ListTagsForResourceInput`](crate::input::ListTagsForResourceInput) pub mod list_tags_for_resource_input { /// A builder for [`ListTagsForResourceInput`](crate::input::ListTagsForResourceInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) resource_arn: std::option::Option<std::string::String>, } impl Builder { /// <p>The ARN of tagged resources.</p> pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self { self.resource_arn = Some(input.into()); self } pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.resource_arn = input; self } /// Consumes the builder and constructs a [`ListTagsForResourceInput`](crate::input::ListTagsForResourceInput) pub fn build( self, ) -> std::result::Result< crate::input::ListTagsForResourceInput, smithy_http::operation::BuildError, > { Ok(crate::input::ListTagsForResourceInput { resource_arn: self.resource_arn, }) } } } #[doc(hidden)] pub type ListTagsForResourceInputOperationOutputAlias = crate::operation::ListTagsForResource; #[doc(hidden)] pub type ListTagsForResourceInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListTagsForResourceInput { /// Consumes the builder and constructs an Operation<[`ListTagsForResource`](crate::operation::ListTagsForResource)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::ListTagsForResource, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::ListTagsForResource::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "ListTagsForResource", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { let input_29 = &self.resource_arn; let input_29 = input_29 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "resource_arn", details: "cannot be empty or unset", })?; let resource_arn = smithy_http::label::fmt_string(input_29, false); if resource_arn.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "resource_arn", details: "cannot be empty or unset", }); } write!(output, "/tags/{resourceArn}", resourceArn = resource_arn) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListTagsForResourceInput`](crate::input::ListTagsForResourceInput) pub fn builder() -> crate::input::list_tags_for_resource_input::Builder { crate::input::list_tags_for_resource_input::Builder::default() } } /// See [`ListVirtualClustersInput`](crate::input::ListVirtualClustersInput) pub mod list_virtual_clusters_input { /// A builder for [`ListVirtualClustersInput`](crate::input::ListVirtualClustersInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) container_provider_id: std::option::Option<std::string::String>, pub(crate) container_provider_type: std::option::Option<crate::model::ContainerProviderType>, pub(crate) created_after: std::option::Option<smithy_types::Instant>, pub(crate) created_before: std::option::Option<smithy_types::Instant>, pub(crate) states: std::option::Option<std::vec::Vec<crate::model::VirtualClusterState>>, pub(crate) max_results: std::option::Option<i32>, pub(crate) next_token: std::option::Option<std::string::String>, } impl Builder { /// <p>The container provider ID of the virtual cluster.</p> pub fn container_provider_id(mut self, input: impl Into<std::string::String>) -> Self { self.container_provider_id = Some(input.into()); self } pub fn set_container_provider_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.container_provider_id = input; self } /// <p>The container provider type of the virtual cluster. EKS is the only supported type as of now.</p> pub fn container_provider_type( mut self, input: crate::model::ContainerProviderType, ) -> Self { self.container_provider_type = Some(input); self } pub fn set_container_provider_type( mut self, input: std::option::Option<crate::model::ContainerProviderType>, ) -> Self { self.container_provider_type = input; self } /// <p>The date and time after which the virtual clusters are created.</p> pub fn created_after(mut self, input: smithy_types::Instant) -> Self { self.created_after = Some(input); self } pub fn set_created_after( mut self, input: std::option::Option<smithy_types::Instant>, ) -> Self { self.created_after = input; self } /// <p>The date and time before which the virtual clusters are created.</p> pub fn created_before(mut self, input: smithy_types::Instant) -> Self { self.created_before = Some(input); self } pub fn set_created_before( mut self, input: std::option::Option<smithy_types::Instant>, ) -> Self { self.created_before = input; self } pub fn states(mut self, input: impl Into<crate::model::VirtualClusterState>) -> Self { let mut v = self.states.unwrap_or_default(); v.push(input.into()); self.states = Some(v); self } pub fn set_states( mut self, input: std::option::Option<std::vec::Vec<crate::model::VirtualClusterState>>, ) -> Self { self.states = input; self } /// <p>The maximum number of virtual clusters that can be listed.</p> pub fn max_results(mut self, input: i32) -> Self { self.max_results = Some(input); self } pub fn set_max_results(mut self, input: std::option::Option<i32>) -> Self { self.max_results = input; self } /// <p>The token for the next set of virtual clusters to return. </p> pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self { self.next_token = Some(input.into()); self } pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.next_token = input; self } /// Consumes the builder and constructs a [`ListVirtualClustersInput`](crate::input::ListVirtualClustersInput) pub fn build( self, ) -> std::result::Result< crate::input::ListVirtualClustersInput, smithy_http::operation::BuildError, > { Ok(crate::input::ListVirtualClustersInput { container_provider_id: self.container_provider_id, container_provider_type: self.container_provider_type, created_after: self.created_after, created_before: self.created_before, states: self.states, max_results: self.max_results, next_token: self.next_token, }) } } } #[doc(hidden)] pub type ListVirtualClustersInputOperationOutputAlias = crate::operation::ListVirtualClusters; #[doc(hidden)] pub type ListVirtualClustersInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl ListVirtualClustersInput { /// Consumes the builder and constructs an Operation<[`ListVirtualClusters`](crate::operation::ListVirtualClusters)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::ListVirtualClusters, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::ListVirtualClusters::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "ListVirtualClusters", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { write!(output, "/virtualclusters").expect("formatting should succeed"); Ok(()) } fn uri_query(&self, mut output: &mut String) { let mut query = smithy_http::query::Writer::new(&mut output); if let Some(inner_30) = &self.container_provider_id { query.push_kv( "containerProviderId", &smithy_http::query::fmt_string(&inner_30), ); } if let Some(inner_31) = &self.container_provider_type { query.push_kv( "containerProviderType", &smithy_http::query::fmt_string(&inner_31), ); } if let Some(inner_32) = &self.created_after { query.push_kv( "createdAfter", &smithy_http::query::fmt_timestamp( inner_32, smithy_types::instant::Format::DateTime, ), ); } if let Some(inner_33) = &self.created_before { query.push_kv( "createdBefore", &smithy_http::query::fmt_timestamp( inner_33, smithy_types::instant::Format::DateTime, ), ); } if let Some(inner_34) = &self.states { for inner_35 in inner_34 { query.push_kv("states", &smithy_http::query::fmt_string(&inner_35)); } } if let Some(inner_36) = &self.max_results { query.push_kv( "maxResults", &smithy_types::primitive::Encoder::from(*inner_36).encode(), ); } if let Some(inner_37) = &self.next_token { query.push_kv("nextToken", &smithy_http::query::fmt_string(&inner_37)); } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; self.uri_query(&mut uri); Ok(builder.method("GET").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`ListVirtualClustersInput`](crate::input::ListVirtualClustersInput) pub fn builder() -> crate::input::list_virtual_clusters_input::Builder { crate::input::list_virtual_clusters_input::Builder::default() } } /// See [`StartJobRunInput`](crate::input::StartJobRunInput) pub mod start_job_run_input { /// A builder for [`StartJobRunInput`](crate::input::StartJobRunInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) name: std::option::Option<std::string::String>, pub(crate) virtual_cluster_id: std::option::Option<std::string::String>, pub(crate) client_token: std::option::Option<std::string::String>, pub(crate) execution_role_arn: std::option::Option<std::string::String>, pub(crate) release_label: std::option::Option<std::string::String>, pub(crate) job_driver: std::option::Option<crate::model::JobDriver>, pub(crate) configuration_overrides: std::option::Option<crate::model::ConfigurationOverrides>, pub(crate) tags: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, } impl Builder { /// <p>The name of the job run.</p> pub fn name(mut self, input: impl Into<std::string::String>) -> Self { self.name = Some(input.into()); self } pub fn set_name(mut self, input: std::option::Option<std::string::String>) -> Self { self.name = input; self } /// <p>The virtual cluster ID for which the job run request is submitted.</p> pub fn virtual_cluster_id(mut self, input: impl Into<std::string::String>) -> Self { self.virtual_cluster_id = Some(input.into()); self } pub fn set_virtual_cluster_id( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.virtual_cluster_id = input; self } /// <p>The client idempotency token of the job run request. </p> pub fn client_token(mut self, input: impl Into<std::string::String>) -> Self { self.client_token = Some(input.into()); self } pub fn set_client_token(mut self, input: std::option::Option<std::string::String>) -> Self { self.client_token = input; self } /// <p>The execution role ARN for the job run.</p> pub fn execution_role_arn(mut self, input: impl Into<std::string::String>) -> Self { self.execution_role_arn = Some(input.into()); self } pub fn set_execution_role_arn( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.execution_role_arn = input; self } /// <p>The Amazon EMR release version to use for the job run.</p> pub fn release_label(mut self, input: impl Into<std::string::String>) -> Self { self.release_label = Some(input.into()); self } pub fn set_release_label( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.release_label = input; self } /// <p>The job driver for the job run.</p> pub fn job_driver(mut self, input: crate::model::JobDriver) -> Self { self.job_driver = Some(input); self } pub fn set_job_driver( mut self, input: std::option::Option<crate::model::JobDriver>, ) -> Self { self.job_driver = input; self } /// <p>The configuration overrides for the job run.</p> pub fn configuration_overrides( mut self, input: crate::model::ConfigurationOverrides, ) -> Self { self.configuration_overrides = Some(input); self } pub fn set_configuration_overrides( mut self, input: std::option::Option<crate::model::ConfigurationOverrides>, ) -> Self { self.configuration_overrides = input; self } pub fn tags( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.tags.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.tags = Some(hash_map); self } pub fn set_tags( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.tags = input; self } /// Consumes the builder and constructs a [`StartJobRunInput`](crate::input::StartJobRunInput) pub fn build( self, ) -> std::result::Result<crate::input::StartJobRunInput, smithy_http::operation::BuildError> { Ok(crate::input::StartJobRunInput { name: self.name, virtual_cluster_id: self.virtual_cluster_id, client_token: self.client_token, execution_role_arn: self.execution_role_arn, release_label: self.release_label, job_driver: self.job_driver, configuration_overrides: self.configuration_overrides, tags: self.tags, }) } } } #[doc(hidden)] pub type StartJobRunInputOperationOutputAlias = crate::operation::StartJobRun; #[doc(hidden)] pub type StartJobRunInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl StartJobRunInput { /// Consumes the builder and constructs an Operation<[`StartJobRun`](crate::operation::StartJobRun)> #[allow(clippy::let_and_return)] pub fn make_operation( mut self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::StartJobRun, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ if self.client_token.is_none() { self.client_token = Some(_config.make_token.make_idempotency_token()); } let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_start_job_run(&self).map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::StartJobRun::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "StartJobRun", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { let input_38 = &self.virtual_cluster_id; let input_38 = input_38 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", })?; let virtual_cluster_id = smithy_http::label::fmt_string(input_38, false); if virtual_cluster_id.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "virtual_cluster_id", details: "cannot be empty or unset", }); } write!( output, "/virtualclusters/{virtualClusterId}/jobruns", virtualClusterId = virtual_cluster_id ) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`StartJobRunInput`](crate::input::StartJobRunInput) pub fn builder() -> crate::input::start_job_run_input::Builder { crate::input::start_job_run_input::Builder::default() } } /// See [`TagResourceInput`](crate::input::TagResourceInput) pub mod tag_resource_input { /// A builder for [`TagResourceInput`](crate::input::TagResourceInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) resource_arn: std::option::Option<std::string::String>, pub(crate) tags: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, } impl Builder { /// <p>The ARN of resources.</p> pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self { self.resource_arn = Some(input.into()); self } pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.resource_arn = input; self } pub fn tags( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.tags.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.tags = Some(hash_map); self } pub fn set_tags( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.tags = input; self } /// Consumes the builder and constructs a [`TagResourceInput`](crate::input::TagResourceInput) pub fn build( self, ) -> std::result::Result<crate::input::TagResourceInput, smithy_http::operation::BuildError> { Ok(crate::input::TagResourceInput { resource_arn: self.resource_arn, tags: self.tags, }) } } } #[doc(hidden)] pub type TagResourceInputOperationOutputAlias = crate::operation::TagResource; #[doc(hidden)] pub type TagResourceInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl TagResourceInput { /// Consumes the builder and constructs an Operation<[`TagResource`](crate::operation::TagResource)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::TagResource, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = crate::operation_ser::serialize_operation_tag_resource(&self).map_err(|err| { smithy_http::operation::BuildError::SerializationError(err.into()) })?; let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::TagResource::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "TagResource", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { let input_39 = &self.resource_arn; let input_39 = input_39 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "resource_arn", details: "cannot be empty or unset", })?; let resource_arn = smithy_http::label::fmt_string(input_39, false); if resource_arn.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "resource_arn", details: "cannot be empty or unset", }); } write!(output, "/tags/{resourceArn}", resourceArn = resource_arn) .expect("formatting should succeed"); Ok(()) } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; Ok(builder.method("POST").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`TagResourceInput`](crate::input::TagResourceInput) pub fn builder() -> crate::input::tag_resource_input::Builder { crate::input::tag_resource_input::Builder::default() } } /// See [`UntagResourceInput`](crate::input::UntagResourceInput) pub mod untag_resource_input { /// A builder for [`UntagResourceInput`](crate::input::UntagResourceInput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) resource_arn: std::option::Option<std::string::String>, pub(crate) tag_keys: std::option::Option<std::vec::Vec<std::string::String>>, } impl Builder { /// <p>The ARN of resources.</p> pub fn resource_arn(mut self, input: impl Into<std::string::String>) -> Self { self.resource_arn = Some(input.into()); self } pub fn set_resource_arn(mut self, input: std::option::Option<std::string::String>) -> Self { self.resource_arn = input; self } pub fn tag_keys(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.tag_keys.unwrap_or_default(); v.push(input.into()); self.tag_keys = Some(v); self } pub fn set_tag_keys( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.tag_keys = input; self } /// Consumes the builder and constructs a [`UntagResourceInput`](crate::input::UntagResourceInput) pub fn build( self, ) -> std::result::Result<crate::input::UntagResourceInput, smithy_http::operation::BuildError> { Ok(crate::input::UntagResourceInput { resource_arn: self.resource_arn, tag_keys: self.tag_keys, }) } } } #[doc(hidden)] pub type UntagResourceInputOperationOutputAlias = crate::operation::UntagResource; #[doc(hidden)] pub type UntagResourceInputOperationRetryAlias = aws_http::AwsErrorRetryPolicy; impl UntagResourceInput { /// Consumes the builder and constructs an Operation<[`UntagResource`](crate::operation::UntagResource)> #[allow(clippy::let_and_return)] pub fn make_operation( &self, _config: &crate::config::Config, ) -> std::result::Result< smithy_http::operation::Operation< crate::operation::UntagResource, aws_http::AwsErrorRetryPolicy, >, smithy_http::operation::BuildError, > { Ok({ let request = self.request_builder_base()?; let body = smithy_http::body::SdkBody::from(""); let request = Self::assemble(request, body); #[allow(unused_mut)] let mut request = smithy_http::operation::Request::new(request.map(smithy_http::body::SdkBody::from)); request.properties_mut().insert( aws_http::user_agent::AwsUserAgent::new_from_environment( crate::API_METADATA.clone(), ), ); #[allow(unused_mut)] let mut signing_config = aws_sig_auth::signer::OperationSigningConfig::default_config(); request.properties_mut().insert(signing_config); request .properties_mut() .insert(aws_types::SigningService::from_static( _config.signing_service(), )); aws_endpoint::set_endpoint_resolver( &mut request.properties_mut(), _config.endpoint_resolver.clone(), ); if let Some(region) = &_config.region { request.properties_mut().insert(region.clone()); } aws_auth::provider::set_provider( &mut request.properties_mut(), _config.credentials_provider.clone(), ); let op = smithy_http::operation::Operation::new( request, crate::operation::UntagResource::new(), ) .with_metadata(smithy_http::operation::Metadata::new( "UntagResource", "emrcontainers", )); let op = op.with_retry_policy(aws_http::AwsErrorRetryPolicy::new()); op }) } fn uri_base(&self, output: &mut String) -> Result<(), smithy_http::operation::BuildError> { let input_40 = &self.resource_arn; let input_40 = input_40 .as_ref() .ok_or(smithy_http::operation::BuildError::MissingField { field: "resource_arn", details: "cannot be empty or unset", })?; let resource_arn = smithy_http::label::fmt_string(input_40, false); if resource_arn.is_empty() { return Err(smithy_http::operation::BuildError::MissingField { field: "resource_arn", details: "cannot be empty or unset", }); } write!(output, "/tags/{resourceArn}", resourceArn = resource_arn) .expect("formatting should succeed"); Ok(()) } fn uri_query(&self, mut output: &mut String) { let mut query = smithy_http::query::Writer::new(&mut output); if let Some(inner_41) = &self.tag_keys { for inner_42 in inner_41 { query.push_kv("tagKeys", &smithy_http::query::fmt_string(&inner_42)); } } } #[allow(clippy::unnecessary_wraps)] fn update_http_builder( &self, builder: http::request::Builder, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut uri = String::new(); self.uri_base(&mut uri)?; self.uri_query(&mut uri); Ok(builder.method("DELETE").uri(uri)) } #[allow(clippy::unnecessary_wraps)] fn request_builder_base( &self, ) -> std::result::Result<http::request::Builder, smithy_http::operation::BuildError> { let mut builder = self.update_http_builder(http::request::Builder::new())?; builder = smithy_http::header::set_header_if_absent(builder, "content-type", "application/json"); Ok(builder) } fn assemble( mut builder: http::request::Builder, body: smithy_http::body::SdkBody, ) -> http::request::Request<smithy_http::body::SdkBody> { if let Some(content_length) = body.content_length() { builder = builder.header(http::header::CONTENT_LENGTH, content_length) } builder.body(body).expect("should be valid request") } /// Creates a new builder-style object to manufacture [`UntagResourceInput`](crate::input::UntagResourceInput) pub fn builder() -> crate::input::untag_resource_input::Builder { crate::input::untag_resource_input::Builder::default() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct UntagResourceInput { /// <p>The ARN of resources.</p> pub resource_arn: std::option::Option<std::string::String>, /// <p>The tag keys of the resources.</p> pub tag_keys: std::option::Option<std::vec::Vec<std::string::String>>, } impl std::fmt::Debug for UntagResourceInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("UntagResourceInput"); formatter.field("resource_arn", &self.resource_arn); formatter.field("tag_keys", &self.tag_keys); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct TagResourceInput { /// <p>The ARN of resources.</p> pub resource_arn: std::option::Option<std::string::String>, /// <p>The tags assigned to resources.</p> pub tags: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, } impl std::fmt::Debug for TagResourceInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("TagResourceInput"); formatter.field("resource_arn", &self.resource_arn); formatter.field("tags", &self.tags); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct StartJobRunInput { /// <p>The name of the job run.</p> pub name: std::option::Option<std::string::String>, /// <p>The virtual cluster ID for which the job run request is submitted.</p> pub virtual_cluster_id: std::option::Option<std::string::String>, /// <p>The client idempotency token of the job run request. </p> pub client_token: std::option::Option<std::string::String>, /// <p>The execution role ARN for the job run.</p> pub execution_role_arn: std::option::Option<std::string::String>, /// <p>The Amazon EMR release version to use for the job run.</p> pub release_label: std::option::Option<std::string::String>, /// <p>The job driver for the job run.</p> pub job_driver: std::option::Option<crate::model::JobDriver>, /// <p>The configuration overrides for the job run.</p> pub configuration_overrides: std::option::Option<crate::model::ConfigurationOverrides>, /// <p>The tags assigned to job runs.</p> pub tags: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, } impl std::fmt::Debug for StartJobRunInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("StartJobRunInput"); formatter.field("name", &self.name); formatter.field("virtual_cluster_id", &self.virtual_cluster_id); formatter.field("client_token", &self.client_token); formatter.field("execution_role_arn", &self.execution_role_arn); formatter.field("release_label", &self.release_label); formatter.field("job_driver", &self.job_driver); formatter.field("configuration_overrides", &self.configuration_overrides); formatter.field("tags", &self.tags); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListVirtualClustersInput { /// <p>The container provider ID of the virtual cluster.</p> pub container_provider_id: std::option::Option<std::string::String>, /// <p>The container provider type of the virtual cluster. EKS is the only supported type as of now.</p> pub container_provider_type: std::option::Option<crate::model::ContainerProviderType>, /// <p>The date and time after which the virtual clusters are created.</p> pub created_after: std::option::Option<smithy_types::Instant>, /// <p>The date and time before which the virtual clusters are created.</p> pub created_before: std::option::Option<smithy_types::Instant>, /// <p>The states of the requested virtual clusters.</p> pub states: std::option::Option<std::vec::Vec<crate::model::VirtualClusterState>>, /// <p>The maximum number of virtual clusters that can be listed.</p> pub max_results: std::option::Option<i32>, /// <p>The token for the next set of virtual clusters to return. </p> pub next_token: std::option::Option<std::string::String>, } impl std::fmt::Debug for ListVirtualClustersInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListVirtualClustersInput"); formatter.field("container_provider_id", &self.container_provider_id); formatter.field("container_provider_type", &self.container_provider_type); formatter.field("created_after", &self.created_after); formatter.field("created_before", &self.created_before); formatter.field("states", &self.states); formatter.field("max_results", &self.max_results); formatter.field("next_token", &self.next_token); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListTagsForResourceInput { /// <p>The ARN of tagged resources.</p> pub resource_arn: std::option::Option<std::string::String>, } impl std::fmt::Debug for ListTagsForResourceInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListTagsForResourceInput"); formatter.field("resource_arn", &self.resource_arn); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListManagedEndpointsInput { /// <p>The ID of the virtual cluster.</p> pub virtual_cluster_id: std::option::Option<std::string::String>, /// <p>The date and time before which the endpoints are created.</p> pub created_before: std::option::Option<smithy_types::Instant>, /// <p> The date and time after which the endpoints are created.</p> pub created_after: std::option::Option<smithy_types::Instant>, /// <p>The types of the managed endpoints.</p> pub types: std::option::Option<std::vec::Vec<std::string::String>>, /// <p>The states of the managed endpoints.</p> pub states: std::option::Option<std::vec::Vec<crate::model::EndpointState>>, /// <p>The maximum number of managed endpoints that can be listed.</p> pub max_results: std::option::Option<i32>, /// <p> The token for the next set of managed endpoints to return. </p> pub next_token: std::option::Option<std::string::String>, } impl std::fmt::Debug for ListManagedEndpointsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListManagedEndpointsInput"); formatter.field("virtual_cluster_id", &self.virtual_cluster_id); formatter.field("created_before", &self.created_before); formatter.field("created_after", &self.created_after); formatter.field("types", &self.types); formatter.field("states", &self.states); formatter.field("max_results", &self.max_results); formatter.field("next_token", &self.next_token); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ListJobRunsInput { /// <p>The ID of the virtual cluster for which to list the job run. </p> pub virtual_cluster_id: std::option::Option<std::string::String>, /// <p>The date and time before which the job runs were submitted.</p> pub created_before: std::option::Option<smithy_types::Instant>, /// <p>The date and time after which the job runs were submitted.</p> pub created_after: std::option::Option<smithy_types::Instant>, /// <p>The name of the job run.</p> pub name: std::option::Option<std::string::String>, /// <p>The states of the job run.</p> pub states: std::option::Option<std::vec::Vec<crate::model::JobRunState>>, /// <p>The maximum number of job runs that can be listed.</p> pub max_results: std::option::Option<i32>, /// <p>The token for the next set of job runs to return.</p> pub next_token: std::option::Option<std::string::String>, } impl std::fmt::Debug for ListJobRunsInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ListJobRunsInput"); formatter.field("virtual_cluster_id", &self.virtual_cluster_id); formatter.field("created_before", &self.created_before); formatter.field("created_after", &self.created_after); formatter.field("name", &self.name); formatter.field("states", &self.states); formatter.field("max_results", &self.max_results); formatter.field("next_token", &self.next_token); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeVirtualClusterInput { /// <p>The ID of the virtual cluster that will be described.</p> pub id: std::option::Option<std::string::String>, } impl std::fmt::Debug for DescribeVirtualClusterInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeVirtualClusterInput"); formatter.field("id", &self.id); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeManagedEndpointInput { /// <p>This output displays ID of the managed endpoint.</p> pub id: std::option::Option<std::string::String>, /// <p>The ID of the endpoint's virtual cluster.</p> pub virtual_cluster_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for DescribeManagedEndpointInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeManagedEndpointInput"); formatter.field("id", &self.id); formatter.field("virtual_cluster_id", &self.virtual_cluster_id); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DescribeJobRunInput { /// <p>The ID of the job run request. </p> pub id: std::option::Option<std::string::String>, /// <p>The ID of the virtual cluster for which the job run is submitted.</p> pub virtual_cluster_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for DescribeJobRunInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DescribeJobRunInput"); formatter.field("id", &self.id); formatter.field("virtual_cluster_id", &self.virtual_cluster_id); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteVirtualClusterInput { /// <p>The ID of the virtual cluster that will be deleted.</p> pub id: std::option::Option<std::string::String>, } impl std::fmt::Debug for DeleteVirtualClusterInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteVirtualClusterInput"); formatter.field("id", &self.id); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DeleteManagedEndpointInput { /// <p>The ID of the managed endpoint.</p> pub id: std::option::Option<std::string::String>, /// <p>The ID of the endpoint's virtual cluster.</p> pub virtual_cluster_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for DeleteManagedEndpointInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DeleteManagedEndpointInput"); formatter.field("id", &self.id); formatter.field("virtual_cluster_id", &self.virtual_cluster_id); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateVirtualClusterInput { /// <p>The specified name of the virtual cluster.</p> pub name: std::option::Option<std::string::String>, /// <p>The container provider of the virtual cluster.</p> pub container_provider: std::option::Option<crate::model::ContainerProvider>, /// <p>The client token of the virtual cluster.</p> pub client_token: std::option::Option<std::string::String>, /// <p>The tags assigned to the virtual cluster.</p> pub tags: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, } impl std::fmt::Debug for CreateVirtualClusterInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateVirtualClusterInput"); formatter.field("name", &self.name); formatter.field("container_provider", &self.container_provider); formatter.field("client_token", &self.client_token); formatter.field("tags", &self.tags); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CreateManagedEndpointInput { /// <p>The name of the managed endpoint.</p> pub name: std::option::Option<std::string::String>, /// <p>The ID of the virtual cluster for which a managed endpoint is created.</p> pub virtual_cluster_id: std::option::Option<std::string::String>, /// <p>The type of the managed endpoint.</p> pub r#type: std::option::Option<std::string::String>, /// <p>The Amazon EMR release version.</p> pub release_label: std::option::Option<std::string::String>, /// <p>The ARN of the execution role.</p> pub execution_role_arn: std::option::Option<std::string::String>, /// <p>The certificate ARN of the managed endpoint.</p> pub certificate_arn: std::option::Option<std::string::String>, /// <p>The configuration settings that will be used to override existing configurations.</p> pub configuration_overrides: std::option::Option<crate::model::ConfigurationOverrides>, /// <p>The client idempotency token for this create call.</p> pub client_token: std::option::Option<std::string::String>, /// <p>The tags of the managed endpoint. /// </p> pub tags: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, } impl std::fmt::Debug for CreateManagedEndpointInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CreateManagedEndpointInput"); formatter.field("name", &self.name); formatter.field("virtual_cluster_id", &self.virtual_cluster_id); formatter.field("r#type", &self.r#type); formatter.field("release_label", &self.release_label); formatter.field("execution_role_arn", &self.execution_role_arn); formatter.field("certificate_arn", &self.certificate_arn); formatter.field("configuration_overrides", &self.configuration_overrides); formatter.field("client_token", &self.client_token); formatter.field("tags", &self.tags); formatter.finish() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct CancelJobRunInput { /// <p>The ID of the job run to cancel.</p> pub id: std::option::Option<std::string::String>, /// <p>The ID of the virtual cluster for which the job run will be canceled.</p> pub virtual_cluster_id: std::option::Option<std::string::String>, } impl std::fmt::Debug for CancelJobRunInput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("CancelJobRunInput"); formatter.field("id", &self.id); formatter.field("virtual_cluster_id", &self.virtual_cluster_id); formatter.finish() } }
41.685353
134
0.58731
d6b264db2ac98d87402e1cc3ce670481a0870ee6
25,319
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::EIR { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct TS_TIMERR { bits: bool, } impl TS_TIMERR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct TS_AVAILR { bits: bool, } impl TS_AVAILR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct WAKEUPR { bits: bool, } impl WAKEUPR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct PLRR { bits: bool, } impl PLRR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct UNR { bits: bool, } impl UNR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct RLR { bits: bool, } impl RLR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct LCR { bits: bool, } impl LCR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct EBERRR { bits: bool, } impl EBERRR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct MIIR { bits: bool, } impl MIIR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct RXBR { bits: bool, } impl RXBR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct RXFR { bits: bool, } impl RXFR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct TXBR { bits: bool, } impl TXBR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct TXFR { bits: bool, } impl TXFR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct GRAR { bits: bool, } impl GRAR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct BABTR { bits: bool, } impl BABTR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct BABRR { bits: bool, } impl BABRR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Proxy"] pub struct _TS_TIMERW<'a> { w: &'a mut W, } impl<'a> _TS_TIMERW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 15; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _TS_AVAILW<'a> { w: &'a mut W, } impl<'a> _TS_AVAILW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _WAKEUPW<'a> { w: &'a mut W, } impl<'a> _WAKEUPW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 17; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _PLRW<'a> { w: &'a mut W, } impl<'a> _PLRW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 18; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _UNW<'a> { w: &'a mut W, } impl<'a> _UNW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 19; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _RLW<'a> { w: &'a mut W, } impl<'a> _RLW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 20; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _LCW<'a> { w: &'a mut W, } impl<'a> _LCW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 21; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _EBERRW<'a> { w: &'a mut W, } impl<'a> _EBERRW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 22; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _MIIW<'a> { w: &'a mut W, } impl<'a> _MIIW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 23; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _RXBW<'a> { w: &'a mut W, } impl<'a> _RXBW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _RXFW<'a> { w: &'a mut W, } impl<'a> _RXFW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 25; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _TXBW<'a> { w: &'a mut W, } impl<'a> _TXBW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 26; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _TXFW<'a> { w: &'a mut W, } impl<'a> _TXFW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 27; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _GRAW<'a> { w: &'a mut W, } impl<'a> _GRAW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 28; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BABTW<'a> { w: &'a mut W, } impl<'a> _BABTW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 29; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BABRW<'a> { w: &'a mut W, } impl<'a> _BABRW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 30; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 15 - Timestamp Timer"] #[inline] pub fn ts_timer(&self) -> TS_TIMERR { let bits = { const MASK: bool = true; const OFFSET: u8 = 15; ((self.bits >> OFFSET) & MASK as u32) != 0 }; TS_TIMERR { bits } } #[doc = "Bit 16 - Transmit Timestamp Available"] #[inline] pub fn ts_avail(&self) -> TS_AVAILR { let bits = { const MASK: bool = true; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) != 0 }; TS_AVAILR { bits } } #[doc = "Bit 17 - Node Wakeup Request Indication"] #[inline] pub fn wakeup(&self) -> WAKEUPR { let bits = { const MASK: bool = true; const OFFSET: u8 = 17; ((self.bits >> OFFSET) & MASK as u32) != 0 }; WAKEUPR { bits } } #[doc = "Bit 18 - Payload Receive Error"] #[inline] pub fn plr(&self) -> PLRR { let bits = { const MASK: bool = true; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) != 0 }; PLRR { bits } } #[doc = "Bit 19 - Transmit FIFO Underrun"] #[inline] pub fn un(&self) -> UNR { let bits = { const MASK: bool = true; const OFFSET: u8 = 19; ((self.bits >> OFFSET) & MASK as u32) != 0 }; UNR { bits } } #[doc = "Bit 20 - Collision Retry Limit"] #[inline] pub fn rl(&self) -> RLR { let bits = { const MASK: bool = true; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) != 0 }; RLR { bits } } #[doc = "Bit 21 - Late Collision"] #[inline] pub fn lc(&self) -> LCR { let bits = { const MASK: bool = true; const OFFSET: u8 = 21; ((self.bits >> OFFSET) & MASK as u32) != 0 }; LCR { bits } } #[doc = "Bit 22 - Ethernet Bus Error"] #[inline] pub fn eberr(&self) -> EBERRR { let bits = { const MASK: bool = true; const OFFSET: u8 = 22; ((self.bits >> OFFSET) & MASK as u32) != 0 }; EBERRR { bits } } #[doc = "Bit 23 - MII Interrupt."] #[inline] pub fn mii(&self) -> MIIR { let bits = { const MASK: bool = true; const OFFSET: u8 = 23; ((self.bits >> OFFSET) & MASK as u32) != 0 }; MIIR { bits } } #[doc = "Bit 24 - Receive Buffer Interrupt"] #[inline] pub fn rxb(&self) -> RXBR { let bits = { const MASK: bool = true; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) != 0 }; RXBR { bits } } #[doc = "Bit 25 - Receive Frame Interrupt"] #[inline] pub fn rxf(&self) -> RXFR { let bits = { const MASK: bool = true; const OFFSET: u8 = 25; ((self.bits >> OFFSET) & MASK as u32) != 0 }; RXFR { bits } } #[doc = "Bit 26 - Transmit Buffer Interrupt"] #[inline] pub fn txb(&self) -> TXBR { let bits = { const MASK: bool = true; const OFFSET: u8 = 26; ((self.bits >> OFFSET) & MASK as u32) != 0 }; TXBR { bits } } #[doc = "Bit 27 - Transmit Frame Interrupt"] #[inline] pub fn txf(&self) -> TXFR { let bits = { const MASK: bool = true; const OFFSET: u8 = 27; ((self.bits >> OFFSET) & MASK as u32) != 0 }; TXFR { bits } } #[doc = "Bit 28 - Graceful Stop Complete"] #[inline] pub fn gra(&self) -> GRAR { let bits = { const MASK: bool = true; const OFFSET: u8 = 28; ((self.bits >> OFFSET) & MASK as u32) != 0 }; GRAR { bits } } #[doc = "Bit 29 - Babbling Transmit Error"] #[inline] pub fn babt(&self) -> BABTR { let bits = { const MASK: bool = true; const OFFSET: u8 = 29; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BABTR { bits } } #[doc = "Bit 30 - Babbling Receive Error"] #[inline] pub fn babr(&self) -> BABRR { let bits = { const MASK: bool = true; const OFFSET: u8 = 30; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BABRR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 15 - Timestamp Timer"] #[inline] pub fn ts_timer(&mut self) -> _TS_TIMERW { _TS_TIMERW { w: self } } #[doc = "Bit 16 - Transmit Timestamp Available"] #[inline] pub fn ts_avail(&mut self) -> _TS_AVAILW { _TS_AVAILW { w: self } } #[doc = "Bit 17 - Node Wakeup Request Indication"] #[inline] pub fn wakeup(&mut self) -> _WAKEUPW { _WAKEUPW { w: self } } #[doc = "Bit 18 - Payload Receive Error"] #[inline] pub fn plr(&mut self) -> _PLRW { _PLRW { w: self } } #[doc = "Bit 19 - Transmit FIFO Underrun"] #[inline] pub fn un(&mut self) -> _UNW { _UNW { w: self } } #[doc = "Bit 20 - Collision Retry Limit"] #[inline] pub fn rl(&mut self) -> _RLW { _RLW { w: self } } #[doc = "Bit 21 - Late Collision"] #[inline] pub fn lc(&mut self) -> _LCW { _LCW { w: self } } #[doc = "Bit 22 - Ethernet Bus Error"] #[inline] pub fn eberr(&mut self) -> _EBERRW { _EBERRW { w: self } } #[doc = "Bit 23 - MII Interrupt."] #[inline] pub fn mii(&mut self) -> _MIIW { _MIIW { w: self } } #[doc = "Bit 24 - Receive Buffer Interrupt"] #[inline] pub fn rxb(&mut self) -> _RXBW { _RXBW { w: self } } #[doc = "Bit 25 - Receive Frame Interrupt"] #[inline] pub fn rxf(&mut self) -> _RXFW { _RXFW { w: self } } #[doc = "Bit 26 - Transmit Buffer Interrupt"] #[inline] pub fn txb(&mut self) -> _TXBW { _TXBW { w: self } } #[doc = "Bit 27 - Transmit Frame Interrupt"] #[inline] pub fn txf(&mut self) -> _TXFW { _TXFW { w: self } } #[doc = "Bit 28 - Graceful Stop Complete"] #[inline] pub fn gra(&mut self) -> _GRAW { _GRAW { w: self } } #[doc = "Bit 29 - Babbling Transmit Error"] #[inline] pub fn babt(&mut self) -> _BABTW { _BABTW { w: self } } #[doc = "Bit 30 - Babbling Receive Error"] #[inline] pub fn babr(&mut self) -> _BABRW { _BABRW { w: self } } }
25.093162
59
0.490304
e4bc2533ac68c8e485748fd375845c04404e4031
2,118
use std::error::Error; use std::fs; pub struct Config { pub query: String, pub filename: String, pub case_sensitive: String, } impl Config { pub fn new(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[0].clone(); let filename = args[1].clone(); let case_sensitive = args[2].clone(); Ok(Config { query, filename, case_sensitive, }) } } pub fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.filename)?; let results = if config.case_sensitive == "true" { search_case_sensitive(&config.query, &contents) } else { search_case_insensitive(&config.query, &contents) }; for line in results { println!("{}", line); } Ok(()) } pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let query = query.to_lowercase(); let mut results = Vec::new(); for line in contents.lines() { if line.to_lowercase().contains(&query) { results.push(line); } } results } pub fn search_case_sensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut results = Vec::new(); for line in contents.lines() { if line.contains(&query) { results.push(line); } } results } #[cfg(test)] mod test { use super::*; #[test] fn static_search_insenstive() { let query = "rust"; let contents = "\ Rust: safe, fast, productive. Pick three. Trust me."; assert_eq!( vec!["Rust:", " Trust me."], search_case_insensitive(query, contents) ); } #[test] fn case_sensitive() { let query = "Rust"; let contents = "\ Rust: safe, fast, productive. Pick three. Trust me."; assert_eq!(vec!["Rust:",], search_case_sensitive(query, contents)); } }
21.18
84
0.530217
760fc96c84146505eea4014fb18fff6c09f5d5b5
8,527
use core::fmt::Debug; use std::collections::HashMap; type Universe = HashMap<Coordinate, bool>; trait UniverseFuncs { fn is_active(&self, coordinate: &Coordinate) -> bool; fn dimension_count(&self) -> usize; } impl UniverseFuncs for Universe { fn is_active(&self, coordinate: &Coordinate) -> bool { match self.get(coordinate) { Some(true) => true, _ => false, } } fn dimension_count(&self) -> usize { self.keys().next().unwrap().count() } } struct CoordinateIterator { lower: Coordinate, upper: Coordinate, current: Coordinate, } impl CoordinateIterator { fn new(lower: &Coordinate, upper: &Coordinate) -> CoordinateIterator { CoordinateIterator { lower: lower.clone(), upper: upper.clone(), current: lower.add_last(-1), } } fn from_universe(universe: &Universe) -> CoordinateIterator { CoordinateIterator::new( &Coordinate::new( &(0..universe.dimension_count()) .into_iter() .map(|index| universe.keys().map(|c| c.nth(index)).min().unwrap() - 1) .collect(), ), &Coordinate::new( &(0..universe.dimension_count()) .into_iter() .map(|index| universe.keys().map(|c| c.nth(index)).max().unwrap() + 1) .collect(), ), ) } fn _get_limits(universe: &Universe) -> (Coordinate, Coordinate) { ( Coordinate::new( &(0..universe.dimension_count()) .into_iter() .map(|index| universe.keys().map(|c| c.nth(index)).min().unwrap()) .collect(), ), Coordinate::new( &(0..universe.dimension_count()) .into_iter() .map(|index| universe.keys().map(|c| c.nth(index)).max().unwrap()) .collect(), ), ) } fn next_coordinate_value( current: &Coordinate, lower_limits: &Coordinate, upper_limits: &Coordinate, ) -> Coordinate { let mut result = current.to_vec(); for index in (0..current.count()).rev() { if current.nth(index) < upper_limits.nth(index) { result[index] += 1; for overflow in index + 1..current.count() { result[overflow] = lower_limits.nth(overflow); } break; } } Coordinate::new(&result) } } impl Iterator for CoordinateIterator { type Item = Coordinate; fn next(&mut self) -> Option<<Self as std::iter::Iterator>::Item> { if self.current == self.upper { None } else { let mut result = self.current.to_vec(); for index in (0..self.current.count()).rev() { if self.current.nth(index) < self.upper.nth(index) { result[index] += 1; for overflow in index + 1..self.current.count() { result[overflow] = self.lower.nth(overflow); } break; } } self.current = CoordinateIterator::next_coordinate_value(&self.current, &self.lower, &self.upper); Some(Coordinate::new(&result)) } } } impl Debug for Coordinate { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { f.debug_list().entries(&self.coordinates).finish() } } struct Coordinate { coordinates: Vec<i32>, } impl std::cmp::Eq for Coordinate {} impl std::cmp::PartialEq for Coordinate { fn eq(&self, other: &Self) -> bool { self.coordinates == other.coordinates } } impl std::hash::Hash for Coordinate { fn hash<H>(&self, state: &mut H) where H: std::hash::Hasher, { self.coordinates.hash(state); } } impl Coordinate { fn new(coordinates: &Vec<i32>) -> Coordinate { Coordinate { coordinates: coordinates.into_iter().map(|c| *c).collect(), } } fn nth(&self, index: usize) -> i32 { self.coordinates[index] } fn count(&self) -> usize { self.coordinates.len() } fn add(&self, value: i32) -> Coordinate { Coordinate::new( &self .coordinates .iter() .map(|c| c + value) .collect::<Vec<i32>>(), ) } fn add_last(&self, value: i32) -> Coordinate { let mut coordinates = self.to_vec(); coordinates[self.count() - 1] += value; Coordinate::new(&coordinates) } fn add_dimension(&self) -> Coordinate { let mut coordinates = self.to_vec(); coordinates.insert(0, 0); Coordinate::new(&coordinates) } fn to_vec(&self) -> Vec<i32> { self.coordinates.clone() } fn clone(&self) -> Coordinate { Coordinate::new(&self.to_vec()) } } fn _print_universe(universe: &Universe) { let dimension_count = universe.dimension_count(); let (lower_limits, upper_limits) = CoordinateIterator::_get_limits(universe); const OUTER_DIMENSIONS: [&str; 2] = ["z", "w"]; for coordinate in CoordinateIterator::new(&lower_limits, &upper_limits) { if coordinate.nth(dimension_count - 1) == lower_limits.nth(dimension_count - 1) && coordinate.nth(dimension_count - 2) == lower_limits.nth(dimension_count - 2) { println!(); print!( "{}", (0..dimension_count - 2) .into_iter() .map(|index| format!("{}={}", OUTER_DIMENSIONS[index], coordinate.nth(index))) .collect::<Vec<String>>() .join(",") ); } if coordinate.nth(dimension_count - 1) == lower_limits.nth(dimension_count - 1) { println!(); } print!( "{}", if universe.is_active(&coordinate) { '#' } else { '.' } ); } println!(); } fn get_active_neighbor_count(universe: &Universe, coordinate: &Coordinate) -> usize { CoordinateIterator::new(&coordinate.add(-1), &coordinate.add(1)) .filter(|neighbor| neighbor != coordinate && universe.is_active(&neighbor)) .count() } fn next_cycle(universe: &Universe) -> Universe { let mut new_state = Universe::new(); for coordinate in CoordinateIterator::from_universe(universe) { let active_native_neighbor_count = get_active_neighbor_count(universe, &coordinate); new_state.insert( coordinate.clone(), if let Some(true) = universe.get(&coordinate) { active_native_neighbor_count == 2 || active_native_neighbor_count == 3 } else { active_native_neighbor_count == 3 }, ); } new_state } fn run_cycles(universe: &Universe) -> usize { let mut universe: Universe = universe.into_iter().map(|(c, v)| (c.clone(), *v)).collect(); for _ in 0..6 { universe = next_cycle(&universe); } universe.values().filter(|v| **v).count() } fn solve(universe: &Universe) -> (usize, usize) { ( run_cycles(universe), run_cycles( &universe .into_iter() .map(|(coordinate, value)| (coordinate.add_dimension(), *value)) .collect(), ), ) } fn get_input(file_path: &String) -> Universe { let mut universe = Universe::new(); for (y, line) in std::fs::read_to_string(file_path) .expect("Error reading input file!") .lines() .enumerate() { for (x, c) in line.chars().enumerate() { universe.insert(Coordinate::new(&vec![0, y as i32, x as i32]), c == '#'); } } universe } fn main() { let args: Vec<String> = std::env::args().collect(); if args.len() != 2 { panic!("Please, add input file path as parameter"); } let now = std::time::Instant::now(); let (part1_result, part2_result) = solve(&get_input(&args[1])); let end = now.elapsed().as_secs_f32(); println!("P1: {}", part1_result); println!("P2: {}", part2_result); println!(); println!("Time: {:.7}", end); }
29.302405
99
0.523044
4a9870278b934c57b9af8feb6c5701fe3f815019
52,202
#[doc = "Register `CFG1` reader"] pub struct R(crate::R<CFG1_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CFG1_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CFG1_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<CFG1_SPEC>) -> Self { R(reader) } } #[doc = "Register `CFG1` writer"] pub struct W(crate::W<CFG1_SPEC>); impl core::ops::Deref for W { type Target = crate::W<CFG1_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<CFG1_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<CFG1_SPEC>) -> Self { W(writer) } } #[doc = "Main enable for I 2S function in this Flexcomm\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MAINENABLE_A { #[doc = "0: All I 2S channel pairs in this Flexcomm are disabled and the internal state machines, counters, and flags are reset. No other channel pairs can be enabled."] DISABLED = 0, #[doc = "1: This I 2S channel pair is enabled. Other channel pairs in this Flexcomm may be enabled in their individual PAIRENABLE bits."] ENABLED = 1, } impl From<MAINENABLE_A> for bool { #[inline(always)] fn from(variant: MAINENABLE_A) -> Self { variant as u8 != 0 } } #[doc = "Field `MAINENABLE` reader - Main enable for I 2S function in this Flexcomm"] pub struct MAINENABLE_R(crate::FieldReader<bool, MAINENABLE_A>); impl MAINENABLE_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { MAINENABLE_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MAINENABLE_A { match self.bits { false => MAINENABLE_A::DISABLED, true => MAINENABLE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { **self == MAINENABLE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { **self == MAINENABLE_A::ENABLED } } impl core::ops::Deref for MAINENABLE_R { type Target = crate::FieldReader<bool, MAINENABLE_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MAINENABLE` writer - Main enable for I 2S function in this Flexcomm"] pub struct MAINENABLE_W<'a> { w: &'a mut W, } impl<'a> MAINENABLE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MAINENABLE_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "All I 2S channel pairs in this Flexcomm are disabled and the internal state machines, counters, and flags are reset. No other channel pairs can be enabled."] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(MAINENABLE_A::DISABLED) } #[doc = "This I 2S channel pair is enabled. Other channel pairs in this Flexcomm may be enabled in their individual PAIRENABLE bits."] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(MAINENABLE_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01); self.w } } #[doc = "Data flow Pause. Allows pausing data flow between the I2S serializer/deserializer and the FIFO. This could be done in order to change streams, or while restarting after a data underflow or overflow. When paused, FIFO operations can be done without corrupting data that is in the process of being sent or received. Once a data pause has been requested, the interface may need to complete sending data that was in progress before interrupting the flow of data. Software must check that the pause is actually in effect before taking action. This is done by monitoring the DATAPAUSED flag in the STAT register. When DATAPAUSE is cleared, data transfer will resume at the beginning of the next frame.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DATAPAUSE_A { #[doc = "0: Normal operation, or resuming normal operation at the next frame if the I2S has already been paused."] NORMAL = 0, #[doc = "1: A pause in the data flow is being requested. It is in effect when DATAPAUSED in STAT = 1."] PAUSE = 1, } impl From<DATAPAUSE_A> for bool { #[inline(always)] fn from(variant: DATAPAUSE_A) -> Self { variant as u8 != 0 } } #[doc = "Field `DATAPAUSE` reader - Data flow Pause. Allows pausing data flow between the I2S serializer/deserializer and the FIFO. This could be done in order to change streams, or while restarting after a data underflow or overflow. When paused, FIFO operations can be done without corrupting data that is in the process of being sent or received. Once a data pause has been requested, the interface may need to complete sending data that was in progress before interrupting the flow of data. Software must check that the pause is actually in effect before taking action. This is done by monitoring the DATAPAUSED flag in the STAT register. When DATAPAUSE is cleared, data transfer will resume at the beginning of the next frame."] pub struct DATAPAUSE_R(crate::FieldReader<bool, DATAPAUSE_A>); impl DATAPAUSE_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { DATAPAUSE_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DATAPAUSE_A { match self.bits { false => DATAPAUSE_A::NORMAL, true => DATAPAUSE_A::PAUSE, } } #[doc = "Checks if the value of the field is `NORMAL`"] #[inline(always)] pub fn is_normal(&self) -> bool { **self == DATAPAUSE_A::NORMAL } #[doc = "Checks if the value of the field is `PAUSE`"] #[inline(always)] pub fn is_pause(&self) -> bool { **self == DATAPAUSE_A::PAUSE } } impl core::ops::Deref for DATAPAUSE_R { type Target = crate::FieldReader<bool, DATAPAUSE_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DATAPAUSE` writer - Data flow Pause. Allows pausing data flow between the I2S serializer/deserializer and the FIFO. This could be done in order to change streams, or while restarting after a data underflow or overflow. When paused, FIFO operations can be done without corrupting data that is in the process of being sent or received. Once a data pause has been requested, the interface may need to complete sending data that was in progress before interrupting the flow of data. Software must check that the pause is actually in effect before taking action. This is done by monitoring the DATAPAUSED flag in the STAT register. When DATAPAUSE is cleared, data transfer will resume at the beginning of the next frame."] pub struct DATAPAUSE_W<'a> { w: &'a mut W, } impl<'a> DATAPAUSE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DATAPAUSE_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Normal operation, or resuming normal operation at the next frame if the I2S has already been paused."] #[inline(always)] pub fn normal(self) -> &'a mut W { self.variant(DATAPAUSE_A::NORMAL) } #[doc = "A pause in the data flow is being requested. It is in effect when DATAPAUSED in STAT = 1."] #[inline(always)] pub fn pause(self) -> &'a mut W { self.variant(DATAPAUSE_A::PAUSE) } #[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 = "Provides the number of I2S channel pairs in this Flexcomm This is a read-only field whose value may be different in other Flexcomms. 00 = there is 1 I2S channel pair in this Flexcomm. 01 = there are 2 I2S channel pairs in this Flexcomm. 10 = there are 3 I2S channel pairs in this Flexcomm. 11 = there are 4 I2S channel pairs in this Flexcomm.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum PAIRCOUNT_A { #[doc = "0: 1 I2S channel pairs in this flexcomm"] PAIRS_1 = 0, #[doc = "1: 2 I2S channel pairs in this flexcomm"] PAIRS_2 = 1, #[doc = "2: 3 I2S channel pairs in this flexcomm"] PAIRS_3 = 2, #[doc = "3: 4 I2S channel pairs in this flexcomm"] PAIRS_4 = 3, } impl From<PAIRCOUNT_A> for u8 { #[inline(always)] fn from(variant: PAIRCOUNT_A) -> Self { variant as _ } } #[doc = "Field `PAIRCOUNT` reader - Provides the number of I2S channel pairs in this Flexcomm This is a read-only field whose value may be different in other Flexcomms. 00 = there is 1 I2S channel pair in this Flexcomm. 01 = there are 2 I2S channel pairs in this Flexcomm. 10 = there are 3 I2S channel pairs in this Flexcomm. 11 = there are 4 I2S channel pairs in this Flexcomm."] pub struct PAIRCOUNT_R(crate::FieldReader<u8, PAIRCOUNT_A>); impl PAIRCOUNT_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { PAIRCOUNT_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PAIRCOUNT_A { match self.bits { 0 => PAIRCOUNT_A::PAIRS_1, 1 => PAIRCOUNT_A::PAIRS_2, 2 => PAIRCOUNT_A::PAIRS_3, 3 => PAIRCOUNT_A::PAIRS_4, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `PAIRS_1`"] #[inline(always)] pub fn is_pairs_1(&self) -> bool { **self == PAIRCOUNT_A::PAIRS_1 } #[doc = "Checks if the value of the field is `PAIRS_2`"] #[inline(always)] pub fn is_pairs_2(&self) -> bool { **self == PAIRCOUNT_A::PAIRS_2 } #[doc = "Checks if the value of the field is `PAIRS_3`"] #[inline(always)] pub fn is_pairs_3(&self) -> bool { **self == PAIRCOUNT_A::PAIRS_3 } #[doc = "Checks if the value of the field is `PAIRS_4`"] #[inline(always)] pub fn is_pairs_4(&self) -> bool { **self == PAIRCOUNT_A::PAIRS_4 } } impl core::ops::Deref for PAIRCOUNT_R { type Target = crate::FieldReader<u8, PAIRCOUNT_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PAIRCOUNT` writer - Provides the number of I2S channel pairs in this Flexcomm This is a read-only field whose value may be different in other Flexcomms. 00 = there is 1 I2S channel pair in this Flexcomm. 01 = there are 2 I2S channel pairs in this Flexcomm. 10 = there are 3 I2S channel pairs in this Flexcomm. 11 = there are 4 I2S channel pairs in this Flexcomm."] pub struct PAIRCOUNT_W<'a> { w: &'a mut W, } impl<'a> PAIRCOUNT_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PAIRCOUNT_A) -> &'a mut W { self.bits(variant.into()) } #[doc = "1 I2S channel pairs in this flexcomm"] #[inline(always)] pub fn pairs_1(self) -> &'a mut W { self.variant(PAIRCOUNT_A::PAIRS_1) } #[doc = "2 I2S channel pairs in this flexcomm"] #[inline(always)] pub fn pairs_2(self) -> &'a mut W { self.variant(PAIRCOUNT_A::PAIRS_2) } #[doc = "3 I2S channel pairs in this flexcomm"] #[inline(always)] pub fn pairs_3(self) -> &'a mut W { self.variant(PAIRCOUNT_A::PAIRS_3) } #[doc = "4 I2S channel pairs in this flexcomm"] #[inline(always)] pub fn pairs_4(self) -> &'a mut W { self.variant(PAIRCOUNT_A::PAIRS_4) } #[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 << 2)) | ((value as u32 & 0x03) << 2); self.w } } #[doc = "Master / slave configuration selection, determining how SCK and WS are used by all channel pairs in this Flexcomm.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum MSTSLVCFG_A { #[doc = "0: Normal slave mode, the default mode. SCK and WS are received from a master and used to transmit or receive data."] NORMAL_SLAVE_MODE = 0, #[doc = "1: WS synchronized master. WS is received from another master and used to synchronize the generation of SCK, when divided from the Flexcomm function clock."] WS_SYNC_MASTER = 1, #[doc = "2: Master using an existing SCK. SCK is received and used directly to generate WS, as well as transmitting or receiving data."] MASTER_USING_SCK = 2, #[doc = "3: Normal master mode. SCK and WS are generated so they can be sent to one or more slave devices."] NORMAL_MASTER = 3, } impl From<MSTSLVCFG_A> for u8 { #[inline(always)] fn from(variant: MSTSLVCFG_A) -> Self { variant as _ } } #[doc = "Field `MSTSLVCFG` reader - Master / slave configuration selection, determining how SCK and WS are used by all channel pairs in this Flexcomm."] pub struct MSTSLVCFG_R(crate::FieldReader<u8, MSTSLVCFG_A>); impl MSTSLVCFG_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { MSTSLVCFG_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MSTSLVCFG_A { match self.bits { 0 => MSTSLVCFG_A::NORMAL_SLAVE_MODE, 1 => MSTSLVCFG_A::WS_SYNC_MASTER, 2 => MSTSLVCFG_A::MASTER_USING_SCK, 3 => MSTSLVCFG_A::NORMAL_MASTER, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NORMAL_SLAVE_MODE`"] #[inline(always)] pub fn is_normal_slave_mode(&self) -> bool { **self == MSTSLVCFG_A::NORMAL_SLAVE_MODE } #[doc = "Checks if the value of the field is `WS_SYNC_MASTER`"] #[inline(always)] pub fn is_ws_sync_master(&self) -> bool { **self == MSTSLVCFG_A::WS_SYNC_MASTER } #[doc = "Checks if the value of the field is `MASTER_USING_SCK`"] #[inline(always)] pub fn is_master_using_sck(&self) -> bool { **self == MSTSLVCFG_A::MASTER_USING_SCK } #[doc = "Checks if the value of the field is `NORMAL_MASTER`"] #[inline(always)] pub fn is_normal_master(&self) -> bool { **self == MSTSLVCFG_A::NORMAL_MASTER } } impl core::ops::Deref for MSTSLVCFG_R { type Target = crate::FieldReader<u8, MSTSLVCFG_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MSTSLVCFG` writer - Master / slave configuration selection, determining how SCK and WS are used by all channel pairs in this Flexcomm."] pub struct MSTSLVCFG_W<'a> { w: &'a mut W, } impl<'a> MSTSLVCFG_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MSTSLVCFG_A) -> &'a mut W { self.bits(variant.into()) } #[doc = "Normal slave mode, the default mode. SCK and WS are received from a master and used to transmit or receive data."] #[inline(always)] pub fn normal_slave_mode(self) -> &'a mut W { self.variant(MSTSLVCFG_A::NORMAL_SLAVE_MODE) } #[doc = "WS synchronized master. WS is received from another master and used to synchronize the generation of SCK, when divided from the Flexcomm function clock."] #[inline(always)] pub fn ws_sync_master(self) -> &'a mut W { self.variant(MSTSLVCFG_A::WS_SYNC_MASTER) } #[doc = "Master using an existing SCK. SCK is received and used directly to generate WS, as well as transmitting or receiving data."] #[inline(always)] pub fn master_using_sck(self) -> &'a mut W { self.variant(MSTSLVCFG_A::MASTER_USING_SCK) } #[doc = "Normal master mode. SCK and WS are generated so they can be sent to one or more slave devices."] #[inline(always)] pub fn normal_master(self) -> &'a mut W { self.variant(MSTSLVCFG_A::NORMAL_MASTER) } #[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 << 4)) | ((value as u32 & 0x03) << 4); self.w } } #[doc = "Selects the basic I2S operating mode. Other configurations modify this to obtain all supported cases. See Formats and modes for examples.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum MODE_A { #[doc = "0: I2S mode a.k.a. 'classic' mode. WS has a 50% duty cycle, with (for each enabled channel pair) one piece of left channel data occurring during the first phase, and one pieces of right channel data occurring during the second phase. In this mode, the data region begins one clock after the leading WS edge for the frame. For a 50% WS duty cycle, FRAMELEN must define an even number of I2S clocks for the frame. If FRAMELEN defines an odd number of clocks per frame, the extra clock will occur on the right."] CLASSIC_MODE = 0, #[doc = "1: DSP mode where WS has a 50% duty cycle. See remark for mode 0."] DSP_MODE_WS_50_DUTYCYCLE = 1, #[doc = "2: DSP mode where WS has a one clock long pulse at the beginning of each data frame."] DSP_MODE_WS_1_CLOCK = 2, #[doc = "3: DSP mode where WS has a one data slot long pulse at the beginning of each data frame."] DSP_MODE_WS_1_DATA = 3, } impl From<MODE_A> for u8 { #[inline(always)] fn from(variant: MODE_A) -> Self { variant as _ } } #[doc = "Field `MODE` reader - Selects the basic I2S operating mode. Other configurations modify this to obtain all supported cases. See Formats and modes for examples."] pub struct MODE_R(crate::FieldReader<u8, MODE_A>); impl MODE_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { MODE_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MODE_A { match self.bits { 0 => MODE_A::CLASSIC_MODE, 1 => MODE_A::DSP_MODE_WS_50_DUTYCYCLE, 2 => MODE_A::DSP_MODE_WS_1_CLOCK, 3 => MODE_A::DSP_MODE_WS_1_DATA, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `CLASSIC_MODE`"] #[inline(always)] pub fn is_classic_mode(&self) -> bool { **self == MODE_A::CLASSIC_MODE } #[doc = "Checks if the value of the field is `DSP_MODE_WS_50_DUTYCYCLE`"] #[inline(always)] pub fn is_dsp_mode_ws_50_dutycycle(&self) -> bool { **self == MODE_A::DSP_MODE_WS_50_DUTYCYCLE } #[doc = "Checks if the value of the field is `DSP_MODE_WS_1_CLOCK`"] #[inline(always)] pub fn is_dsp_mode_ws_1_clock(&self) -> bool { **self == MODE_A::DSP_MODE_WS_1_CLOCK } #[doc = "Checks if the value of the field is `DSP_MODE_WS_1_DATA`"] #[inline(always)] pub fn is_dsp_mode_ws_1_data(&self) -> bool { **self == MODE_A::DSP_MODE_WS_1_DATA } } impl core::ops::Deref for MODE_R { type Target = crate::FieldReader<u8, MODE_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `MODE` writer - Selects the basic I2S operating mode. Other configurations modify this to obtain all supported cases. See Formats and modes for examples."] pub struct MODE_W<'a> { w: &'a mut W, } impl<'a> MODE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MODE_A) -> &'a mut W { self.bits(variant.into()) } #[doc = "I2S mode a.k.a. 'classic' mode. WS has a 50% duty cycle, with (for each enabled channel pair) one piece of left channel data occurring during the first phase, and one pieces of right channel data occurring during the second phase. In this mode, the data region begins one clock after the leading WS edge for the frame. For a 50% WS duty cycle, FRAMELEN must define an even number of I2S clocks for the frame. If FRAMELEN defines an odd number of clocks per frame, the extra clock will occur on the right."] #[inline(always)] pub fn classic_mode(self) -> &'a mut W { self.variant(MODE_A::CLASSIC_MODE) } #[doc = "DSP mode where WS has a 50% duty cycle. See remark for mode 0."] #[inline(always)] pub fn dsp_mode_ws_50_dutycycle(self) -> &'a mut W { self.variant(MODE_A::DSP_MODE_WS_50_DUTYCYCLE) } #[doc = "DSP mode where WS has a one clock long pulse at the beginning of each data frame."] #[inline(always)] pub fn dsp_mode_ws_1_clock(self) -> &'a mut W { self.variant(MODE_A::DSP_MODE_WS_1_CLOCK) } #[doc = "DSP mode where WS has a one data slot long pulse at the beginning of each data frame."] #[inline(always)] pub fn dsp_mode_ws_1_data(self) -> &'a mut W { self.variant(MODE_A::DSP_MODE_WS_1_DATA) } #[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 << 6)) | ((value as u32 & 0x03) << 6); self.w } } #[doc = "Right channel data is in the Low portion of FIFO data. Essentially, this swaps left and right channel data as it is transferred to or from the FIFO. This bit is not used if the data width is greater than 24 bits or if PDMDATA = 1. Note that if the ONECHANNEL field (bit 10 of this register) = 1, the one channel to be used is the nominally the left channel. POSITION can still place that data in the frame where right channel data is normally located. if all enabled channel pairs have ONECHANNEL = 1, then RIGHTLOW = 1 is not allowed.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RIGHTLOW_A { #[doc = "0: The right channel is taken from the high part of the FIFO data. For example, when data is 16 bits, FIFO bits 31:16 are used for the right channel."] RIGHT_HIGH = 0, #[doc = "1: The right channel is taken from the low part of the FIFO data. For example, when data is 16 bits, FIFO bits 15:0 are used for the right channel."] RIGHT_LOW = 1, } impl From<RIGHTLOW_A> for bool { #[inline(always)] fn from(variant: RIGHTLOW_A) -> Self { variant as u8 != 0 } } #[doc = "Field `RIGHTLOW` reader - Right channel data is in the Low portion of FIFO data. Essentially, this swaps left and right channel data as it is transferred to or from the FIFO. This bit is not used if the data width is greater than 24 bits or if PDMDATA = 1. Note that if the ONECHANNEL field (bit 10 of this register) = 1, the one channel to be used is the nominally the left channel. POSITION can still place that data in the frame where right channel data is normally located. if all enabled channel pairs have ONECHANNEL = 1, then RIGHTLOW = 1 is not allowed."] pub struct RIGHTLOW_R(crate::FieldReader<bool, RIGHTLOW_A>); impl RIGHTLOW_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { RIGHTLOW_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RIGHTLOW_A { match self.bits { false => RIGHTLOW_A::RIGHT_HIGH, true => RIGHTLOW_A::RIGHT_LOW, } } #[doc = "Checks if the value of the field is `RIGHT_HIGH`"] #[inline(always)] pub fn is_right_high(&self) -> bool { **self == RIGHTLOW_A::RIGHT_HIGH } #[doc = "Checks if the value of the field is `RIGHT_LOW`"] #[inline(always)] pub fn is_right_low(&self) -> bool { **self == RIGHTLOW_A::RIGHT_LOW } } impl core::ops::Deref for RIGHTLOW_R { type Target = crate::FieldReader<bool, RIGHTLOW_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `RIGHTLOW` writer - Right channel data is in the Low portion of FIFO data. Essentially, this swaps left and right channel data as it is transferred to or from the FIFO. This bit is not used if the data width is greater than 24 bits or if PDMDATA = 1. Note that if the ONECHANNEL field (bit 10 of this register) = 1, the one channel to be used is the nominally the left channel. POSITION can still place that data in the frame where right channel data is normally located. if all enabled channel pairs have ONECHANNEL = 1, then RIGHTLOW = 1 is not allowed."] pub struct RIGHTLOW_W<'a> { w: &'a mut W, } impl<'a> RIGHTLOW_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RIGHTLOW_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "The right channel is taken from the high part of the FIFO data. For example, when data is 16 bits, FIFO bits 31:16 are used for the right channel."] #[inline(always)] pub fn right_high(self) -> &'a mut W { self.variant(RIGHTLOW_A::RIGHT_HIGH) } #[doc = "The right channel is taken from the low part of the FIFO data. For example, when data is 16 bits, FIFO bits 15:0 are used for the right channel."] #[inline(always)] pub fn right_low(self) -> &'a mut W { self.variant(RIGHTLOW_A::RIGHT_LOW) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | ((value as u32 & 0x01) << 8); self.w } } #[doc = "Left Justify data.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LEFTJUST_A { #[doc = "0: Data is transferred between the FIFO and the I2S serializer/deserializer right justified, i.e. starting from bit 0 and continuing to the position defined by DATALEN. This would correspond to right justified data in the stream on the data bus."] RIGHT_JUSTIFIED = 0, #[doc = "1: Data is transferred between the FIFO and the I2S serializer/deserializer left justified, i.e. starting from the MSB of the FIFO entry and continuing for the number of bits defined by DATALEN. This would correspond to left justified data in the stream on the data bus."] LEFT_JUSTIFIED = 1, } impl From<LEFTJUST_A> for bool { #[inline(always)] fn from(variant: LEFTJUST_A) -> Self { variant as u8 != 0 } } #[doc = "Field `LEFTJUST` reader - Left Justify data."] pub struct LEFTJUST_R(crate::FieldReader<bool, LEFTJUST_A>); impl LEFTJUST_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { LEFTJUST_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LEFTJUST_A { match self.bits { false => LEFTJUST_A::RIGHT_JUSTIFIED, true => LEFTJUST_A::LEFT_JUSTIFIED, } } #[doc = "Checks if the value of the field is `RIGHT_JUSTIFIED`"] #[inline(always)] pub fn is_right_justified(&self) -> bool { **self == LEFTJUST_A::RIGHT_JUSTIFIED } #[doc = "Checks if the value of the field is `LEFT_JUSTIFIED`"] #[inline(always)] pub fn is_left_justified(&self) -> bool { **self == LEFTJUST_A::LEFT_JUSTIFIED } } impl core::ops::Deref for LEFTJUST_R { type Target = crate::FieldReader<bool, LEFTJUST_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `LEFTJUST` writer - Left Justify data."] pub struct LEFTJUST_W<'a> { w: &'a mut W, } impl<'a> LEFTJUST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LEFTJUST_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Data is transferred between the FIFO and the I2S serializer/deserializer right justified, i.e. starting from bit 0 and continuing to the position defined by DATALEN. This would correspond to right justified data in the stream on the data bus."] #[inline(always)] pub fn right_justified(self) -> &'a mut W { self.variant(LEFTJUST_A::RIGHT_JUSTIFIED) } #[doc = "Data is transferred between the FIFO and the I2S serializer/deserializer left justified, i.e. starting from the MSB of the FIFO entry and continuing for the number of bits defined by DATALEN. This would correspond to left justified data in the stream on the data bus."] #[inline(always)] pub fn left_justified(self) -> &'a mut W { self.variant(LEFTJUST_A::LEFT_JUSTIFIED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | ((value as u32 & 0x01) << 9); self.w } } #[doc = "Single channel mode. Applies to both transmit and receive. This configuration bit applies only to the first I2S channel pair. Other channel pairs may select this mode independently in their separate CFG1 registers.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ONECHANNEL_A { #[doc = "0: I2S data for this channel pair is treated as left and right channels."] DUAL_CHANNEL = 0, #[doc = "1: I2S data for this channel pair is treated as a single channel, functionally the left channel for this pair. In mode 0 only, the right side of the frame begins at POSITION = 0x100. This is because mode 0 makes a clear distinction between the left and right sides of the frame. When ONECHANNEL = 1, the single channel of data may be placed on the right by setting POSITION to 0x100 + the data position within the right side (e.g. 0x108 would place data starting at the 8th clock after the middle of the frame). In other modes, data for the single channel of data is placed at the clock defined by POSITION."] SINGLE_CHANNEL = 1, } impl From<ONECHANNEL_A> for bool { #[inline(always)] fn from(variant: ONECHANNEL_A) -> Self { variant as u8 != 0 } } #[doc = "Field `ONECHANNEL` reader - Single channel mode. Applies to both transmit and receive. This configuration bit applies only to the first I2S channel pair. Other channel pairs may select this mode independently in their separate CFG1 registers."] pub struct ONECHANNEL_R(crate::FieldReader<bool, ONECHANNEL_A>); impl ONECHANNEL_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { ONECHANNEL_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ONECHANNEL_A { match self.bits { false => ONECHANNEL_A::DUAL_CHANNEL, true => ONECHANNEL_A::SINGLE_CHANNEL, } } #[doc = "Checks if the value of the field is `DUAL_CHANNEL`"] #[inline(always)] pub fn is_dual_channel(&self) -> bool { **self == ONECHANNEL_A::DUAL_CHANNEL } #[doc = "Checks if the value of the field is `SINGLE_CHANNEL`"] #[inline(always)] pub fn is_single_channel(&self) -> bool { **self == ONECHANNEL_A::SINGLE_CHANNEL } } impl core::ops::Deref for ONECHANNEL_R { type Target = crate::FieldReader<bool, ONECHANNEL_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `ONECHANNEL` writer - Single channel mode. Applies to both transmit and receive. This configuration bit applies only to the first I2S channel pair. Other channel pairs may select this mode independently in their separate CFG1 registers."] pub struct ONECHANNEL_W<'a> { w: &'a mut W, } impl<'a> ONECHANNEL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ONECHANNEL_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "I2S data for this channel pair is treated as left and right channels."] #[inline(always)] pub fn dual_channel(self) -> &'a mut W { self.variant(ONECHANNEL_A::DUAL_CHANNEL) } #[doc = "I2S data for this channel pair is treated as a single channel, functionally the left channel for this pair. In mode 0 only, the right side of the frame begins at POSITION = 0x100. This is because mode 0 makes a clear distinction between the left and right sides of the frame. When ONECHANNEL = 1, the single channel of data may be placed on the right by setting POSITION to 0x100 + the data position within the right side (e.g. 0x108 would place data starting at the 8th clock after the middle of the frame). In other modes, data for the single channel of data is placed at the clock defined by POSITION."] #[inline(always)] pub fn single_channel(self) -> &'a mut W { self.variant(ONECHANNEL_A::SINGLE_CHANNEL) } #[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 << 10)) | ((value as u32 & 0x01) << 10); self.w } } #[doc = "SCK polarity.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SCK_POL_A { #[doc = "0: Data is launched on SCK falling edges and sampled on SCK rising edges (standard for I2S)."] FALLING_EDGE = 0, #[doc = "1: Data is launched on SCK rising edges and sampled on SCK falling edges."] RISING_EDGE = 1, } impl From<SCK_POL_A> for bool { #[inline(always)] fn from(variant: SCK_POL_A) -> Self { variant as u8 != 0 } } #[doc = "Field `SCK_POL` reader - SCK polarity."] pub struct SCK_POL_R(crate::FieldReader<bool, SCK_POL_A>); impl SCK_POL_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { SCK_POL_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SCK_POL_A { match self.bits { false => SCK_POL_A::FALLING_EDGE, true => SCK_POL_A::RISING_EDGE, } } #[doc = "Checks if the value of the field is `FALLING_EDGE`"] #[inline(always)] pub fn is_falling_edge(&self) -> bool { **self == SCK_POL_A::FALLING_EDGE } #[doc = "Checks if the value of the field is `RISING_EDGE`"] #[inline(always)] pub fn is_rising_edge(&self) -> bool { **self == SCK_POL_A::RISING_EDGE } } impl core::ops::Deref for SCK_POL_R { type Target = crate::FieldReader<bool, SCK_POL_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `SCK_POL` writer - SCK polarity."] pub struct SCK_POL_W<'a> { w: &'a mut W, } impl<'a> SCK_POL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SCK_POL_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Data is launched on SCK falling edges and sampled on SCK rising edges (standard for I2S)."] #[inline(always)] pub fn falling_edge(self) -> &'a mut W { self.variant(SCK_POL_A::FALLING_EDGE) } #[doc = "Data is launched on SCK rising edges and sampled on SCK falling edges."] #[inline(always)] pub fn rising_edge(self) -> &'a mut W { self.variant(SCK_POL_A::RISING_EDGE) } #[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 = "WS polarity.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum WS_POL_A { #[doc = "0: Data frames begin at a falling edge of WS (standard for classic I2S)."] NOT_INVERTED = 0, #[doc = "1: WS is inverted, resulting in a data frame beginning at a rising edge of WS (standard for most 'non-classic' variations of I2S)."] INVERTED = 1, } impl From<WS_POL_A> for bool { #[inline(always)] fn from(variant: WS_POL_A) -> Self { variant as u8 != 0 } } #[doc = "Field `WS_POL` reader - WS polarity."] pub struct WS_POL_R(crate::FieldReader<bool, WS_POL_A>); impl WS_POL_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { WS_POL_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> WS_POL_A { match self.bits { false => WS_POL_A::NOT_INVERTED, true => WS_POL_A::INVERTED, } } #[doc = "Checks if the value of the field is `NOT_INVERTED`"] #[inline(always)] pub fn is_not_inverted(&self) -> bool { **self == WS_POL_A::NOT_INVERTED } #[doc = "Checks if the value of the field is `INVERTED`"] #[inline(always)] pub fn is_inverted(&self) -> bool { **self == WS_POL_A::INVERTED } } impl core::ops::Deref for WS_POL_R { type Target = crate::FieldReader<bool, WS_POL_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `WS_POL` writer - WS polarity."] pub struct WS_POL_W<'a> { w: &'a mut W, } impl<'a> WS_POL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: WS_POL_A) -> &'a mut W { self.bit(variant.into()) } #[doc = "Data frames begin at a falling edge of WS (standard for classic I2S)."] #[inline(always)] pub fn not_inverted(self) -> &'a mut W { self.variant(WS_POL_A::NOT_INVERTED) } #[doc = "WS is inverted, resulting in a data frame beginning at a rising edge of WS (standard for most 'non-classic' variations of I2S)."] #[inline(always)] pub fn inverted(self) -> &'a mut W { self.variant(WS_POL_A::INVERTED) } #[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 << 13)) | ((value as u32 & 0x01) << 13); self.w } } #[doc = "Field `DATALEN` reader - Data Length, minus 1 encoded, defines the number of data bits to be transmitted or received for all I2S channel pairs in this Flexcomm. Note that data is only driven to or received from SDA for the number of bits defined by DATALEN. DATALEN is also used in these ways by the I2S: Determines the size of data transfers between the FIFO and the I2S serializer/deserializer. See FIFO buffer configurations and usage In mode 1, 2, and 3, determines the location of right data following left data in the frame. In mode 3 (where WS has a one data slot long pulse at the beginning of each data frame) determines the duration of the WS pulse. Values: 0x00 to 0x02 = not supported 0x03 = data is 4 bits in length 0x04 = data is 5 bits in length 0x1F = data is 32 bits in length"] pub struct DATALEN_R(crate::FieldReader<u8, u8>); impl DATALEN_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { DATALEN_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for DATALEN_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DATALEN` writer - Data Length, minus 1 encoded, defines the number of data bits to be transmitted or received for all I2S channel pairs in this Flexcomm. Note that data is only driven to or received from SDA for the number of bits defined by DATALEN. DATALEN is also used in these ways by the I2S: Determines the size of data transfers between the FIFO and the I2S serializer/deserializer. See FIFO buffer configurations and usage In mode 1, 2, and 3, determines the location of right data following left data in the frame. In mode 3 (where WS has a one data slot long pulse at the beginning of each data frame) determines the duration of the WS pulse. Values: 0x00 to 0x02 = not supported 0x03 = data is 4 bits in length 0x04 = data is 5 bits in length 0x1F = data is 32 bits in length"] pub struct DATALEN_W<'a> { w: &'a mut W, } impl<'a> DATALEN_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 & !(0x1f << 16)) | ((value as u32 & 0x1f) << 16); self.w } } impl R { #[doc = "Bit 0 - Main enable for I 2S function in this Flexcomm"] #[inline(always)] pub fn mainenable(&self) -> MAINENABLE_R { MAINENABLE_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Data flow Pause. Allows pausing data flow between the I2S serializer/deserializer and the FIFO. This could be done in order to change streams, or while restarting after a data underflow or overflow. When paused, FIFO operations can be done without corrupting data that is in the process of being sent or received. Once a data pause has been requested, the interface may need to complete sending data that was in progress before interrupting the flow of data. Software must check that the pause is actually in effect before taking action. This is done by monitoring the DATAPAUSED flag in the STAT register. When DATAPAUSE is cleared, data transfer will resume at the beginning of the next frame."] #[inline(always)] pub fn datapause(&self) -> DATAPAUSE_R { DATAPAUSE_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bits 2:3 - Provides the number of I2S channel pairs in this Flexcomm This is a read-only field whose value may be different in other Flexcomms. 00 = there is 1 I2S channel pair in this Flexcomm. 01 = there are 2 I2S channel pairs in this Flexcomm. 10 = there are 3 I2S channel pairs in this Flexcomm. 11 = there are 4 I2S channel pairs in this Flexcomm."] #[inline(always)] pub fn paircount(&self) -> PAIRCOUNT_R { PAIRCOUNT_R::new(((self.bits >> 2) & 0x03) as u8) } #[doc = "Bits 4:5 - Master / slave configuration selection, determining how SCK and WS are used by all channel pairs in this Flexcomm."] #[inline(always)] pub fn mstslvcfg(&self) -> MSTSLVCFG_R { MSTSLVCFG_R::new(((self.bits >> 4) & 0x03) as u8) } #[doc = "Bits 6:7 - Selects the basic I2S operating mode. Other configurations modify this to obtain all supported cases. See Formats and modes for examples."] #[inline(always)] pub fn mode(&self) -> MODE_R { MODE_R::new(((self.bits >> 6) & 0x03) as u8) } #[doc = "Bit 8 - Right channel data is in the Low portion of FIFO data. Essentially, this swaps left and right channel data as it is transferred to or from the FIFO. This bit is not used if the data width is greater than 24 bits or if PDMDATA = 1. Note that if the ONECHANNEL field (bit 10 of this register) = 1, the one channel to be used is the nominally the left channel. POSITION can still place that data in the frame where right channel data is normally located. if all enabled channel pairs have ONECHANNEL = 1, then RIGHTLOW = 1 is not allowed."] #[inline(always)] pub fn rightlow(&self) -> RIGHTLOW_R { RIGHTLOW_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - Left Justify data."] #[inline(always)] pub fn leftjust(&self) -> LEFTJUST_R { LEFTJUST_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - Single channel mode. Applies to both transmit and receive. This configuration bit applies only to the first I2S channel pair. Other channel pairs may select this mode independently in their separate CFG1 registers."] #[inline(always)] pub fn onechannel(&self) -> ONECHANNEL_R { ONECHANNEL_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 12 - SCK polarity."] #[inline(always)] pub fn sck_pol(&self) -> SCK_POL_R { SCK_POL_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - WS polarity."] #[inline(always)] pub fn ws_pol(&self) -> WS_POL_R { WS_POL_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bits 16:20 - Data Length, minus 1 encoded, defines the number of data bits to be transmitted or received for all I2S channel pairs in this Flexcomm. Note that data is only driven to or received from SDA for the number of bits defined by DATALEN. DATALEN is also used in these ways by the I2S: Determines the size of data transfers between the FIFO and the I2S serializer/deserializer. See FIFO buffer configurations and usage In mode 1, 2, and 3, determines the location of right data following left data in the frame. In mode 3 (where WS has a one data slot long pulse at the beginning of each data frame) determines the duration of the WS pulse. Values: 0x00 to 0x02 = not supported 0x03 = data is 4 bits in length 0x04 = data is 5 bits in length 0x1F = data is 32 bits in length"] #[inline(always)] pub fn datalen(&self) -> DATALEN_R { DATALEN_R::new(((self.bits >> 16) & 0x1f) as u8) } } impl W { #[doc = "Bit 0 - Main enable for I 2S function in this Flexcomm"] #[inline(always)] pub fn mainenable(&mut self) -> MAINENABLE_W { MAINENABLE_W { w: self } } #[doc = "Bit 1 - Data flow Pause. Allows pausing data flow between the I2S serializer/deserializer and the FIFO. This could be done in order to change streams, or while restarting after a data underflow or overflow. When paused, FIFO operations can be done without corrupting data that is in the process of being sent or received. Once a data pause has been requested, the interface may need to complete sending data that was in progress before interrupting the flow of data. Software must check that the pause is actually in effect before taking action. This is done by monitoring the DATAPAUSED flag in the STAT register. When DATAPAUSE is cleared, data transfer will resume at the beginning of the next frame."] #[inline(always)] pub fn datapause(&mut self) -> DATAPAUSE_W { DATAPAUSE_W { w: self } } #[doc = "Bits 2:3 - Provides the number of I2S channel pairs in this Flexcomm This is a read-only field whose value may be different in other Flexcomms. 00 = there is 1 I2S channel pair in this Flexcomm. 01 = there are 2 I2S channel pairs in this Flexcomm. 10 = there are 3 I2S channel pairs in this Flexcomm. 11 = there are 4 I2S channel pairs in this Flexcomm."] #[inline(always)] pub fn paircount(&mut self) -> PAIRCOUNT_W { PAIRCOUNT_W { w: self } } #[doc = "Bits 4:5 - Master / slave configuration selection, determining how SCK and WS are used by all channel pairs in this Flexcomm."] #[inline(always)] pub fn mstslvcfg(&mut self) -> MSTSLVCFG_W { MSTSLVCFG_W { w: self } } #[doc = "Bits 6:7 - Selects the basic I2S operating mode. Other configurations modify this to obtain all supported cases. See Formats and modes for examples."] #[inline(always)] pub fn mode(&mut self) -> MODE_W { MODE_W { w: self } } #[doc = "Bit 8 - Right channel data is in the Low portion of FIFO data. Essentially, this swaps left and right channel data as it is transferred to or from the FIFO. This bit is not used if the data width is greater than 24 bits or if PDMDATA = 1. Note that if the ONECHANNEL field (bit 10 of this register) = 1, the one channel to be used is the nominally the left channel. POSITION can still place that data in the frame where right channel data is normally located. if all enabled channel pairs have ONECHANNEL = 1, then RIGHTLOW = 1 is not allowed."] #[inline(always)] pub fn rightlow(&mut self) -> RIGHTLOW_W { RIGHTLOW_W { w: self } } #[doc = "Bit 9 - Left Justify data."] #[inline(always)] pub fn leftjust(&mut self) -> LEFTJUST_W { LEFTJUST_W { w: self } } #[doc = "Bit 10 - Single channel mode. Applies to both transmit and receive. This configuration bit applies only to the first I2S channel pair. Other channel pairs may select this mode independently in their separate CFG1 registers."] #[inline(always)] pub fn onechannel(&mut self) -> ONECHANNEL_W { ONECHANNEL_W { w: self } } #[doc = "Bit 12 - SCK polarity."] #[inline(always)] pub fn sck_pol(&mut self) -> SCK_POL_W { SCK_POL_W { w: self } } #[doc = "Bit 13 - WS polarity."] #[inline(always)] pub fn ws_pol(&mut self) -> WS_POL_W { WS_POL_W { w: self } } #[doc = "Bits 16:20 - Data Length, minus 1 encoded, defines the number of data bits to be transmitted or received for all I2S channel pairs in this Flexcomm. Note that data is only driven to or received from SDA for the number of bits defined by DATALEN. DATALEN is also used in these ways by the I2S: Determines the size of data transfers between the FIFO and the I2S serializer/deserializer. See FIFO buffer configurations and usage In mode 1, 2, and 3, determines the location of right data following left data in the frame. In mode 3 (where WS has a one data slot long pulse at the beginning of each data frame) determines the duration of the WS pulse. Values: 0x00 to 0x02 = not supported 0x03 = data is 4 bits in length 0x04 = data is 5 bits in length 0x1F = data is 32 bits in length"] #[inline(always)] pub fn datalen(&mut self) -> DATALEN_W { DATALEN_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 = "Configuration register 1 for the primary channel pair.\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 [cfg1](index.html) module"] pub struct CFG1_SPEC; impl crate::RegisterSpec for CFG1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [cfg1::R](R) reader structure"] impl crate::Readable for CFG1_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [cfg1::W](W) writer structure"] impl crate::Writable for CFG1_SPEC { type Writer = W; } #[doc = "`reset()` method sets CFG1 to value 0"] impl crate::Resettable for CFG1_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
47.542805
804
0.654362
335bdb2ba3610106f92ebf2724466f9b7323a471
8,305
use nix::mount::{mount, MsFlags}; use nix::sched::{unshare, CloneFlags}; use nix::sys::signal::{kill, Signal}; use nix::sys::wait::{waitpid, WaitPidFlag, WaitStatus}; use nix::unistd; use nix::unistd::{fork, ForkResult}; use std::env; use std::fs; use std::io; use std::io::prelude::*; use std::os::unix::fs::symlink; use std::os::unix::process::CommandExt; use std::path::Path; use std::path::PathBuf; use std::process; use std::string::String; use tempfile::TempDir; const NONE: Option<&'static [u8]> = None; fn bind_mount(source: &Path, dest: &Path) { if let Err(e) = mount( Some(source), dest, Some("none"), MsFlags::MS_BIND | MsFlags::MS_REC, NONE, ) { eprintln!( "failed to bind mount {} to {}: {}", source.display(), dest.display(), e ); } } fn bind_mount_directory(entry: &fs::DirEntry) { let mountpoint = PathBuf::from("/").join(entry.file_name()); if let Err(e) = fs::create_dir(&mountpoint) { if e.kind() != io::ErrorKind::AlreadyExists { let e2: io::Result<()> = Err(e); e2.unwrap_or_else(|_| panic!("failed to create {}", &mountpoint.display())); } } bind_mount(&entry.path(), &mountpoint) } fn bind_mount_file(entry: &fs::DirEntry) { let mountpoint = PathBuf::from("/").join(entry.file_name()); fs::File::create(&mountpoint) .unwrap_or_else(|_| panic!("failed to create {}", &mountpoint.display())); bind_mount(&entry.path(), &mountpoint) } fn mirror_symlink(entry: &fs::DirEntry) { let path = entry.path(); let target = fs::read_link(&path) .unwrap_or_else(|_| panic!("failed to resolve symlink {}", &path.display())); let link_path = PathBuf::from("/").join(entry.file_name()); symlink(&target, &link_path).unwrap_or_else(|_| { panic!( "failed to create symlink {} -> {}", &link_path.display(), &target.display() ) }); } fn bind_mount_direntry(entry: io::Result<fs::DirEntry>) { let entry = entry.expect("error while listing from /nix directory"); // do not bind mount an existing nix installation if entry.file_name() == PathBuf::from("nix") { return; } let path = entry.path(); let stat = entry .metadata() .unwrap_or_else(|_| panic!("cannot get stat of {}", path.display())); if stat.is_dir() { bind_mount_directory(&entry); } else if stat.is_file() { bind_mount_file(&entry); } else if stat.file_type().is_symlink() { mirror_symlink(&entry); } } fn run_chroot(nixdir: &Path, rootdir: &Path, cmd: &str, args: &[String]) { let cwd = env::current_dir().expect("cannot get current working directory"); let uid = unistd::getuid(); let gid = unistd::getgid(); unshare(CloneFlags::CLONE_NEWNS | CloneFlags::CLONE_NEWUSER).expect("unshare failed"); // prepare pivot_root call: // rootdir must be a mount point mount( Some(rootdir), rootdir, Some("none"), MsFlags::MS_BIND | MsFlags::MS_REC, NONE, ) .expect("failed to re-bind mount / to our new chroot"); mount( Some(rootdir), rootdir, Some("none"), MsFlags::MS_PRIVATE | MsFlags::MS_REC, NONE, ).expect("failed to re-mount our chroot as private mount"); // create the mount point for the old root // The old root cannot be unmounted/removed after pivot_root, the only way to // keep / clean is to hide the directory with another mountpoint. Therefore // we pivot the old root to /nix. This is somewhat confusing, though. let nix_mountpoint = rootdir.join("nix"); fs::create_dir(&nix_mountpoint) .unwrap_or_else(|_| panic!("failed to create {}/nix", &nix_mountpoint.display())); unistd::pivot_root(rootdir, &nix_mountpoint).unwrap_or_else(|_| { panic!( "pivot_root({},{})", rootdir.display(), nix_mountpoint.display() ) }); env::set_current_dir("/").expect("cannot change directory to /"); // bind mount all / stuff into rootdir // the orginal content of / now available under /nix let nix_root = PathBuf::from("/nix"); let dir = fs::read_dir(&nix_root).expect("failed to list /nix directory"); for entry in dir { bind_mount_direntry(entry); } // mount the store and hide the old root // we fetch nixdir under the old root let nix_store = nix_root.join(nixdir); mount( Some(&nix_store), "/nix", Some("none"), MsFlags::MS_BIND | MsFlags::MS_REC, NONE, ) .unwrap_or_else(|_| panic!("failed to bind mount {} to /nix", nix_store.display())); // fixes issue #1 where writing to /proc/self/gid_map fails // see user_namespaces(7) for more documentation if let Ok(mut file) = fs::File::create("/proc/self/setgroups") { let _ = file.write_all(b"deny"); } let mut uid_map = fs::File::create("/proc/self/uid_map").expect("failed to open /proc/self/uid_map"); uid_map .write_all(format!("{} {} 1", uid, uid).as_bytes()) .expect("failed to write new uid mapping to /proc/self/uid_map"); let mut gid_map = fs::File::create("/proc/self/gid_map").expect("failed to open /proc/self/gid_map"); gid_map .write_all(format!("{} {} 1", gid, gid).as_bytes()) .expect("failed to write new gid mapping to /proc/self/gid_map"); // restore cwd env::set_current_dir(&cwd) .unwrap_or_else(|_| panic!("cannot restore working directory {}", cwd.display())); let err = process::Command::new(cmd) .args(args) .env("NIX_CONF_DIR", "/nix/etc/nix") .exec(); eprintln!("failed to execute {}: {}", &cmd, err); process::exit(1); } fn wait_for_child(child_pid: unistd::Pid, tempdir: TempDir, rootdir: &Path) { loop { match waitpid(child_pid, Some(WaitPidFlag::WUNTRACED)) { Ok(WaitStatus::Signaled(child, Signal::SIGSTOP, _)) => { let _ = kill(unistd::getpid(), Signal::SIGSTOP); let _ = kill(child, Signal::SIGCONT); } Ok(WaitStatus::Signaled(_, signal, _)) => { kill(unistd::getpid(), signal) .unwrap_or_else(|_| panic!("failed to send {} signal to our self", signal)); } Ok(WaitStatus::Exited(_, status)) => { tempdir.close().unwrap_or_else(|_| { panic!( "failed to remove temporary directory: {}", rootdir.display() ) }); process::exit(status); } Ok(what) => { tempdir.close().unwrap_or_else(|_| { panic!( "failed to remove temporary directory: {}", rootdir.display() ) }); eprintln!("unexpected wait event happend: {:?}", what); process::exit(1); } Err(e) => { tempdir.close().unwrap_or_else(|_| { panic!( "failed to remove temporary directory: {}", rootdir.display() ) }); eprintln!("waitpid failed: {}", e); process::exit(1); } }; } } fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 3 { eprintln!("Usage: {} <nixpath> <command>\n", args[0]); process::exit(1); } let tempdir = TempDir::new().expect("failed to create temporary directory for mount point"); let rootdir = PathBuf::from(tempdir.path()); let nixdir = fs::canonicalize(&args[1]) .unwrap_or_else(|_| panic!("failed to resolve nix directory {}", &args[1])); match fork() { Ok(ForkResult::Parent { child, .. }) => wait_for_child(child, tempdir, &rootdir), Ok(ForkResult::Child) => run_chroot(&nixdir, &rootdir, &args[2], &args[3..]), Err(e) => { eprintln!("fork failed: {}", e); } }; }
32.956349
96
0.556773
f5eb92c1bb5aa0522b736321736d31c22551ec06
176,296
// ignore-tidy-filelength //! Rustdoc's HTML rendering module. //! //! This modules contains the bulk of the logic necessary for rendering a //! rustdoc `clean::Crate` instance to a set of static HTML pages. This //! rendering process is largely driven by the `format!` syntax extension to //! perform all I/O into files and streams. //! //! The rendering process is largely driven by the `Context` and `Cache` //! structures. The cache is pre-populated by crawling the crate in question, //! and then it is shared among the various rendering threads. The cache is meant //! to be a fairly large structure not implementing `Clone` (because it's shared //! among threads). The context, however, should be a lightweight structure. This //! is cloned per-thread and contains information about what is currently being //! rendered. //! //! In order to speed up rendering (mostly because of markdown rendering), the //! rendering process has been parallelized. This parallelization is only //! exposed through the `crate` method on the context, and then also from the //! fact that the shared cache is stored in TLS (and must be accessed as such). //! //! In addition to rendering the crate itself, this module is also responsible //! for creating the corresponding search index and source file renderings. //! These threads are not parallelized (they haven't been a bottleneck yet), and //! both occur before the crate is rendered. crate mod cache; #[cfg(test)] mod tests; use std::cell::{Cell, RefCell}; use std::cmp::Ordering; use std::collections::{BTreeMap, VecDeque}; use std::default::Default; use std::ffi::OsStr; use std::fmt::{self, Write}; use std::fs::{self, File}; use std::io::prelude::*; use std::io::{self, BufReader}; use std::path::{Component, Path, PathBuf}; use std::rc::Rc; use std::str; use std::string::ToString; use std::sync::mpsc::{channel, Receiver}; use std::sync::Arc; use itertools::Itertools; use rustc_ast_pretty::pprust; use rustc_attr::{Deprecation, StabilityLevel}; use rustc_data_structures::flock; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; use rustc_hir::def::CtorKind; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_hir::Mutability; use rustc_middle::middle::stability; use rustc_middle::ty::TyCtxt; use rustc_session::Session; use rustc_span::edition::Edition; use rustc_span::hygiene::MacroKind; use rustc_span::source_map::FileName; use rustc_span::symbol::{kw, sym, Symbol}; use serde::ser::SerializeSeq; use serde::{Serialize, Serializer}; use crate::clean::{self, AttributesExt, GetDefId, RenderedLink, SelfTy, TypeKind}; use crate::config::{RenderInfo, RenderOptions}; use crate::docfs::{DocFS, PathError}; use crate::error::Error; use crate::formats::cache::Cache; use crate::formats::item_type::ItemType; use crate::formats::{AssocItemRender, FormatRenderer, Impl, RenderMode}; use crate::html::escape::Escape; use crate::html::format::Function; use crate::html::format::{href, print_default_space, print_generic_bounds, WhereClause}; use crate::html::format::{print_abi_with_space, Buffer, PrintWithSpace}; use crate::html::markdown::{ self, plain_text_summary, ErrorCodes, IdMap, Markdown, MarkdownHtml, MarkdownSummaryLine, }; use crate::html::sources; use crate::html::{highlight, layout, static_files}; use cache::{build_index, ExternalLocation}; /// A pair of name and its optional document. crate type NameDoc = (String, Option<String>); crate fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ { crate::html::format::display_fn(move |f| { if !v.ends_with('/') && !v.is_empty() { write!(f, "{}/", v) } else { f.write_str(v) } }) } /// Major driving force in all rustdoc rendering. This contains information /// about where in the tree-like hierarchy rendering is occurring and controls /// how the current page is being rendered. /// /// It is intended that this context is a lightweight object which can be fairly /// easily cloned because it is cloned per work-job (about once per item in the /// rustdoc tree). #[derive(Clone)] crate struct Context<'tcx> { /// Current hierarchy of components leading down to what's currently being /// rendered crate current: Vec<String>, /// The current destination folder of where HTML artifacts should be placed. /// This changes as the context descends into the module hierarchy. crate dst: PathBuf, /// A flag, which when `true`, will render pages which redirect to the /// real location of an item. This is used to allow external links to /// publicly reused items to redirect to the right location. crate render_redirect_pages: bool, /// The map used to ensure all generated 'id=' attributes are unique. id_map: Rc<RefCell<IdMap>>, /// Tracks section IDs for `Deref` targets so they match in both the main /// body and the sidebar. deref_id_map: Rc<RefCell<FxHashMap<DefId, String>>>, crate shared: Arc<SharedContext<'tcx>>, all: Rc<RefCell<AllTypes>>, /// Storage for the errors produced while generating documentation so they /// can be printed together at the end. crate errors: Rc<Receiver<String>>, crate cache: Rc<Cache>, } crate struct SharedContext<'tcx> { crate tcx: TyCtxt<'tcx>, /// The path to the crate root source minus the file name. /// Used for simplifying paths to the highlighted source code files. crate src_root: PathBuf, /// This describes the layout of each page, and is not modified after /// creation of the context (contains info like the favicon and added html). crate layout: layout::Layout, /// This flag indicates whether `[src]` links should be generated or not. If /// the source files are present in the html rendering, then this will be /// `true`. crate include_sources: bool, /// The local file sources we've emitted and their respective url-paths. crate local_sources: FxHashMap<PathBuf, String>, /// Whether the collapsed pass ran crate collapsed: bool, /// The base-URL of the issue tracker for when an item has been tagged with /// an issue number. crate issue_tracker_base_url: Option<String>, /// The directories that have already been created in this doc run. Used to reduce the number /// of spurious `create_dir_all` calls. crate created_dirs: RefCell<FxHashSet<PathBuf>>, /// This flag indicates whether listings of modules (in the side bar and documentation itself) /// should be ordered alphabetically or in order of appearance (in the source code). crate sort_modules_alphabetically: bool, /// Additional CSS files to be added to the generated docs. crate style_files: Vec<StylePath>, /// Suffix to be added on resource files (if suffix is "-v2" then "light.css" becomes /// "light-v2.css"). crate resource_suffix: String, /// Optional path string to be used to load static files on output pages. If not set, uses /// combinations of `../` to reach the documentation root. crate static_root_path: Option<String>, /// The fs handle we are working with. crate fs: DocFS, /// The default edition used to parse doctests. crate edition: Edition, crate codes: ErrorCodes, playground: Option<markdown::Playground>, } impl<'tcx> Context<'tcx> { fn path(&self, filename: &str) -> PathBuf { // We use splitn vs Path::extension here because we might get a filename // like `style.min.css` and we want to process that into // `style-suffix.min.css`. Path::extension would just return `css` // which would result in `style.min-suffix.css` which isn't what we // want. let (base, ext) = filename.split_once('.').unwrap(); let filename = format!("{}{}.{}", base, self.shared.resource_suffix, ext); self.dst.join(&filename) } fn tcx(&self) -> TyCtxt<'tcx> { self.shared.tcx } fn sess(&self) -> &'tcx Session { &self.shared.tcx.sess } } impl SharedContext<'_> { crate fn ensure_dir(&self, dst: &Path) -> Result<(), Error> { let mut dirs = self.created_dirs.borrow_mut(); if !dirs.contains(dst) { try_err!(self.fs.create_dir_all(dst), dst); dirs.insert(dst.to_path_buf()); } Ok(()) } /// Based on whether the `collapse-docs` pass was run, return either the `doc_value` or the /// `collapsed_doc_value` of the given item. crate fn maybe_collapsed_doc_value<'a>(&self, item: &'a clean::Item) -> Option<String> { if self.collapsed { item.collapsed_doc_value() } else { item.doc_value() } } } // Helper structs for rendering items/sidebars and carrying along contextual // information /// Struct representing one entry in the JS search index. These are all emitted /// by hand to a large JS file at the end of cache-creation. #[derive(Debug)] crate struct IndexItem { crate ty: ItemType, crate name: String, crate path: String, crate desc: String, crate parent: Option<DefId>, crate parent_idx: Option<usize>, crate search_type: Option<IndexItemFunctionType>, } impl Serialize for IndexItem { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { assert_eq!( self.parent.is_some(), self.parent_idx.is_some(), "`{}` is missing idx", self.name ); (self.ty, &self.name, &self.path, &self.desc, self.parent_idx, &self.search_type) .serialize(serializer) } } /// A type used for the search index. #[derive(Debug)] crate struct RenderType { ty: Option<DefId>, idx: Option<usize>, name: Option<String>, generics: Option<Vec<Generic>>, } impl Serialize for RenderType { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(name) = &self.name { let mut seq = serializer.serialize_seq(None)?; if let Some(id) = self.idx { seq.serialize_element(&id)?; } else { seq.serialize_element(&name)?; } if let Some(generics) = &self.generics { seq.serialize_element(&generics)?; } seq.end() } else { serializer.serialize_none() } } } /// A type used for the search index. #[derive(Debug)] crate struct Generic { name: String, defid: Option<DefId>, idx: Option<usize>, } impl Serialize for Generic { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(id) = self.idx { serializer.serialize_some(&id) } else { serializer.serialize_some(&self.name) } } } /// Full type of functions/methods in the search index. #[derive(Debug)] crate struct IndexItemFunctionType { inputs: Vec<TypeWithKind>, output: Option<Vec<TypeWithKind>>, } impl Serialize for IndexItemFunctionType { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { // If we couldn't figure out a type, just write `null`. let mut iter = self.inputs.iter(); if match self.output { Some(ref output) => iter.chain(output.iter()).any(|ref i| i.ty.name.is_none()), None => iter.any(|ref i| i.ty.name.is_none()), } { serializer.serialize_none() } else { let mut seq = serializer.serialize_seq(None)?; seq.serialize_element(&self.inputs)?; if let Some(output) = &self.output { if output.len() > 1 { seq.serialize_element(&output)?; } else { seq.serialize_element(&output[0])?; } } seq.end() } } } #[derive(Debug)] crate struct TypeWithKind { ty: RenderType, kind: TypeKind, } impl From<(RenderType, TypeKind)> for TypeWithKind { fn from(x: (RenderType, TypeKind)) -> TypeWithKind { TypeWithKind { ty: x.0, kind: x.1 } } } impl Serialize for TypeWithKind { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut seq = serializer.serialize_seq(None)?; seq.serialize_element(&self.ty.name)?; let x: ItemType = self.kind.into(); seq.serialize_element(&x)?; seq.end() } } #[derive(Debug, Clone)] crate struct StylePath { /// The path to the theme crate path: PathBuf, /// What the `disabled` attribute should be set to in the HTML tag crate disabled: bool, } thread_local!(crate static CURRENT_DEPTH: Cell<usize> = Cell::new(0)); crate const INITIAL_IDS: [&'static str; 15] = [ "main", "search", "help", "TOC", "render-detail", "associated-types", "associated-const", "required-methods", "provided-methods", "implementors", "synthetic-implementors", "implementors-list", "synthetic-implementors-list", "methods", "implementations", ]; /// Generates the documentation for `crate` into the directory `dst` impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> { fn descr() -> &'static str { "html" } fn init( mut krate: clean::Crate, options: RenderOptions, _render_info: RenderInfo, edition: Edition, mut cache: Cache, tcx: TyCtxt<'tcx>, ) -> Result<(Self, clean::Crate), Error> { // need to save a copy of the options for rendering the index page let md_opts = options.clone(); let RenderOptions { output, external_html, id_map, playground_url, sort_modules_alphabetically, themes: style_files, default_settings, extension_css, resource_suffix, static_root_path, generate_search_filter, unstable_features, .. } = options; let src_root = match krate.src { FileName::Real(ref p) => match p.local_path().parent() { Some(p) => p.to_path_buf(), None => PathBuf::new(), }, _ => PathBuf::new(), }; // If user passed in `--playground-url` arg, we fill in crate name here let mut playground = None; if let Some(url) = playground_url { playground = Some(markdown::Playground { crate_name: Some(krate.name.to_string()), url }); } let mut layout = layout::Layout { logo: String::new(), favicon: String::new(), external_html, default_settings, krate: krate.name.to_string(), css_file_extension: extension_css, generate_search_filter, }; let mut issue_tracker_base_url = None; let mut include_sources = true; // Crawl the crate attributes looking for attributes which control how we're // going to emit HTML if let Some(attrs) = krate.module.as_ref().map(|m| &m.attrs) { for attr in attrs.lists(sym::doc) { match (attr.name_or_empty(), attr.value_str()) { (sym::html_favicon_url, Some(s)) => { layout.favicon = s.to_string(); } (sym::html_logo_url, Some(s)) => { layout.logo = s.to_string(); } (sym::html_playground_url, Some(s)) => { playground = Some(markdown::Playground { crate_name: Some(krate.name.to_string()), url: s.to_string(), }); } (sym::issue_tracker_base_url, Some(s)) => { issue_tracker_base_url = Some(s.to_string()); } (sym::html_no_source, None) if attr.is_word() => { include_sources = false; } _ => {} } } } let (sender, receiver) = channel(); let mut scx = SharedContext { tcx, collapsed: krate.collapsed, src_root, include_sources, local_sources: Default::default(), issue_tracker_base_url, layout, created_dirs: Default::default(), sort_modules_alphabetically, style_files, resource_suffix, static_root_path, fs: DocFS::new(sender), edition, codes: ErrorCodes::from(unstable_features.is_nightly_build()), playground, }; // Add the default themes to the `Vec` of stylepaths // // Note that these must be added before `sources::render` is called // so that the resulting source pages are styled // // `light.css` is not disabled because it is the stylesheet that stays loaded // by the browser as the theme stylesheet. The theme system (hackily) works by // changing the href to this stylesheet. All other themes are disabled to // prevent rule conflicts scx.style_files.push(StylePath { path: PathBuf::from("light.css"), disabled: false }); scx.style_files.push(StylePath { path: PathBuf::from("dark.css"), disabled: true }); scx.style_files.push(StylePath { path: PathBuf::from("ayu.css"), disabled: true }); let dst = output; scx.ensure_dir(&dst)?; krate = sources::render(&dst, &mut scx, krate)?; // Build our search index let index = build_index(&krate, &mut cache, tcx); let mut cx = Context { current: Vec::new(), dst, render_redirect_pages: false, id_map: Rc::new(RefCell::new(id_map)), deref_id_map: Rc::new(RefCell::new(FxHashMap::default())), shared: Arc::new(scx), all: Rc::new(RefCell::new(AllTypes::new())), errors: Rc::new(receiver), cache: Rc::new(cache), }; CURRENT_DEPTH.with(|s| s.set(0)); // Write shared runs within a flock; disable thread dispatching of IO temporarily. Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(true); write_shared(&cx, &krate, index, &md_opts)?; Arc::get_mut(&mut cx.shared).unwrap().fs.set_sync_only(false); Ok((cx, krate)) } fn after_krate( &mut self, krate: &clean::Crate, diag: &rustc_errors::Handler, ) -> Result<(), Error> { let final_file = self.dst.join(&*krate.name.as_str()).join("all.html"); let settings_file = self.dst.join("settings.html"); let crate_name = krate.name; let mut root_path = self.dst.to_str().expect("invalid path").to_owned(); if !root_path.ends_with('/') { root_path.push('/'); } let mut page = layout::Page { title: "List of all items in this crate", css_class: "mod", root_path: "../", static_root_path: self.shared.static_root_path.as_deref(), description: "List of all items in this crate", keywords: BASIC_KEYWORDS, resource_suffix: &self.shared.resource_suffix, extra_scripts: &[], static_extra_scripts: &[], }; let sidebar = if let Some(ref version) = self.cache.crate_version { format!( "<p class=\"location\">Crate {}</p>\ <div class=\"block version\">\ <p>Version {}</p>\ </div>\ <a id=\"all-types\" href=\"index.html\"><p>Back to index</p></a>", crate_name, Escape(version), ) } else { String::new() }; let all = self.all.replace(AllTypes::new()); let v = layout::render( &self.shared.layout, &page, sidebar, |buf: &mut Buffer| all.print(buf), &self.shared.style_files, ); self.shared.fs.write(&final_file, v.as_bytes())?; // Generating settings page. page.title = "Rustdoc settings"; page.description = "Settings of Rustdoc"; page.root_path = "./"; let mut style_files = self.shared.style_files.clone(); let sidebar = "<p class=\"location\">Settings</p><div class=\"sidebar-elems\"></div>"; style_files.push(StylePath { path: PathBuf::from("settings.css"), disabled: false }); let v = layout::render( &self.shared.layout, &page, sidebar, settings( self.shared.static_root_path.as_deref().unwrap_or("./"), &self.shared.resource_suffix, &self.shared.style_files, )?, &style_files, ); self.shared.fs.write(&settings_file, v.as_bytes())?; // Flush pending errors. Arc::get_mut(&mut self.shared).unwrap().fs.close(); let nb_errors = self.errors.iter().map(|err| diag.struct_err(&err).emit()).count(); if nb_errors > 0 { Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), "")) } else { Ok(()) } } fn mod_item_in(&mut self, item: &clean::Item, item_name: &str) -> Result<(), Error> { // Stripped modules survive the rustdoc passes (i.e., `strip-private`) // if they contain impls for public types. These modules can also // contain items such as publicly re-exported structures. // // External crates will provide links to these structures, so // these modules are recursed into, but not rendered normally // (a flag on the context). if !self.render_redirect_pages { self.render_redirect_pages = item.is_stripped(); } let scx = &self.shared; self.dst.push(item_name); self.current.push(item_name.to_owned()); info!("Recursing into {}", self.dst.display()); let buf = self.render_item(item, false); // buf will be empty if the module is stripped and there is no redirect for it if !buf.is_empty() { self.shared.ensure_dir(&self.dst)?; let joint_dst = self.dst.join("index.html"); scx.fs.write(&joint_dst, buf.as_bytes())?; } // Render sidebar-items.js used throughout this module. if !self.render_redirect_pages { let module = match *item.kind { clean::StrippedItem(box clean::ModuleItem(ref m)) | clean::ModuleItem(ref m) => m, _ => unreachable!(), }; let items = self.build_sidebar_items(module); let js_dst = self.dst.join("sidebar-items.js"); let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap()); scx.fs.write(&js_dst, &v)?; } Ok(()) } fn mod_item_out(&mut self, _item_name: &str) -> Result<(), Error> { info!("Recursed; leaving {}", self.dst.display()); // Go back to where we were at self.dst.pop(); self.current.pop(); Ok(()) } fn item(&mut self, item: clean::Item) -> Result<(), Error> { // Stripped modules survive the rustdoc passes (i.e., `strip-private`) // if they contain impls for public types. These modules can also // contain items such as publicly re-exported structures. // // External crates will provide links to these structures, so // these modules are recursed into, but not rendered normally // (a flag on the context). if !self.render_redirect_pages { self.render_redirect_pages = item.is_stripped(); } let buf = self.render_item(&item, true); // buf will be empty if the item is stripped and there is no redirect for it if !buf.is_empty() { let name = item.name.as_ref().unwrap(); let item_type = item.type_(); let file_name = &item_path(item_type, &name.as_str()); self.shared.ensure_dir(&self.dst)?; let joint_dst = self.dst.join(file_name); self.shared.fs.write(&joint_dst, buf.as_bytes())?; if !self.render_redirect_pages { self.all.borrow_mut().append(full_path(self, &item), &item_type); } // If the item is a macro, redirect from the old macro URL (with !) // to the new one (without). if item_type == ItemType::Macro { let redir_name = format!("{}.{}!.html", item_type, name); let redir_dst = self.dst.join(redir_name); let v = layout::redirect(file_name); self.shared.fs.write(&redir_dst, v.as_bytes())?; } } Ok(()) } fn cache(&self) -> &Cache { &self.cache } } fn write_shared( cx: &Context<'_>, krate: &clean::Crate, search_index: String, options: &RenderOptions, ) -> Result<(), Error> { // Write out the shared files. Note that these are shared among all rustdoc // docs placed in the output directory, so this needs to be a synchronized // operation with respect to all other rustdocs running around. let lock_file = cx.dst.join(".lock"); let _lock = try_err!(flock::Lock::new(&lock_file, true, true, true), &lock_file); // Add all the static files. These may already exist, but we just // overwrite them anyway to make sure that they're fresh and up-to-date. write_minify( &cx.shared.fs, cx.path("rustdoc.css"), static_files::RUSTDOC_CSS, options.enable_minification, )?; write_minify( &cx.shared.fs, cx.path("settings.css"), static_files::SETTINGS_CSS, options.enable_minification, )?; write_minify( &cx.shared.fs, cx.path("noscript.css"), static_files::NOSCRIPT_CSS, options.enable_minification, )?; // To avoid "light.css" to be overwritten, we'll first run over the received themes and only // then we'll run over the "official" styles. let mut themes: FxHashSet<String> = FxHashSet::default(); for entry in &cx.shared.style_files { let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path); let extension = try_none!(try_none!(entry.path.extension(), &entry.path).to_str(), &entry.path); // Handle the official themes match theme { "light" => write_minify( &cx.shared.fs, cx.path("light.css"), static_files::themes::LIGHT, options.enable_minification, )?, "dark" => write_minify( &cx.shared.fs, cx.path("dark.css"), static_files::themes::DARK, options.enable_minification, )?, "ayu" => write_minify( &cx.shared.fs, cx.path("ayu.css"), static_files::themes::AYU, options.enable_minification, )?, _ => { // Handle added third-party themes let content = try_err!(fs::read(&entry.path), &entry.path); cx.shared .fs .write(cx.path(&format!("{}.{}", theme, extension)), content.as_slice())?; } }; themes.insert(theme.to_owned()); } let write = |p, c| cx.shared.fs.write(p, c); if (*cx.shared).layout.logo.is_empty() { write(cx.path("rust-logo.png"), static_files::RUST_LOGO)?; } if (*cx.shared).layout.favicon.is_empty() { write(cx.path("favicon.svg"), static_files::RUST_FAVICON_SVG)?; write(cx.path("favicon-16x16.png"), static_files::RUST_FAVICON_PNG_16)?; write(cx.path("favicon-32x32.png"), static_files::RUST_FAVICON_PNG_32)?; } write(cx.path("brush.svg"), static_files::BRUSH_SVG)?; write(cx.path("wheel.svg"), static_files::WHEEL_SVG)?; write(cx.path("down-arrow.svg"), static_files::DOWN_ARROW_SVG)?; let mut themes: Vec<&String> = themes.iter().collect(); themes.sort(); // To avoid theme switch latencies as much as possible, we put everything theme related // at the beginning of the html files into another js file. let theme_js = format!( r#"var themes = document.getElementById("theme-choices"); var themePicker = document.getElementById("theme-picker"); function showThemeButtonState() {{ themes.style.display = "block"; themePicker.style.borderBottomRightRadius = "0"; themePicker.style.borderBottomLeftRadius = "0"; }} function hideThemeButtonState() {{ themes.style.display = "none"; themePicker.style.borderBottomRightRadius = "3px"; themePicker.style.borderBottomLeftRadius = "3px"; }} function switchThemeButtonState() {{ if (themes.style.display === "block") {{ hideThemeButtonState(); }} else {{ showThemeButtonState(); }} }}; function handleThemeButtonsBlur(e) {{ var active = document.activeElement; var related = e.relatedTarget; if (active.id !== "theme-picker" && (!active.parentNode || active.parentNode.id !== "theme-choices") && (!related || (related.id !== "theme-picker" && (!related.parentNode || related.parentNode.id !== "theme-choices")))) {{ hideThemeButtonState(); }} }} themePicker.onclick = switchThemeButtonState; themePicker.onblur = handleThemeButtonsBlur; {}.forEach(function(item) {{ var but = document.createElement("button"); but.textContent = item; but.onclick = function(el) {{ switchTheme(currentTheme, mainTheme, item, true); useSystemTheme(false); }}; but.onblur = handleThemeButtonsBlur; themes.appendChild(but); }});"#, serde_json::to_string(&themes).unwrap() ); write_minify(&cx.shared.fs, cx.path("theme.js"), &theme_js, options.enable_minification)?; write_minify( &cx.shared.fs, cx.path("main.js"), static_files::MAIN_JS, options.enable_minification, )?; write_minify( &cx.shared.fs, cx.path("settings.js"), static_files::SETTINGS_JS, options.enable_minification, )?; if cx.shared.include_sources { write_minify( &cx.shared.fs, cx.path("source-script.js"), static_files::sidebar::SOURCE_SCRIPT, options.enable_minification, )?; } { write_minify( &cx.shared.fs, cx.path("storage.js"), &format!( "var resourcesSuffix = \"{}\";{}", cx.shared.resource_suffix, static_files::STORAGE_JS ), options.enable_minification, )?; } if let Some(ref css) = cx.shared.layout.css_file_extension { let out = cx.path("theme.css"); let buffer = try_err!(fs::read_to_string(css), css); if !options.enable_minification { cx.shared.fs.write(&out, &buffer)?; } else { write_minify(&cx.shared.fs, out, &buffer, options.enable_minification)?; } } write_minify( &cx.shared.fs, cx.path("normalize.css"), static_files::NORMALIZE_CSS, options.enable_minification, )?; write(cx.dst.join("FiraSans-Regular.woff"), static_files::fira_sans::REGULAR)?; write(cx.dst.join("FiraSans-Medium.woff"), static_files::fira_sans::MEDIUM)?; write(cx.dst.join("FiraSans-LICENSE.txt"), static_files::fira_sans::LICENSE)?; write(cx.dst.join("SourceSerifPro-Regular.ttf.woff"), static_files::source_serif_pro::REGULAR)?; write(cx.dst.join("SourceSerifPro-Bold.ttf.woff"), static_files::source_serif_pro::BOLD)?; write(cx.dst.join("SourceSerifPro-It.ttf.woff"), static_files::source_serif_pro::ITALIC)?; write(cx.dst.join("SourceSerifPro-LICENSE.md"), static_files::source_serif_pro::LICENSE)?; write(cx.dst.join("SourceCodePro-Regular.woff"), static_files::source_code_pro::REGULAR)?; write(cx.dst.join("SourceCodePro-Semibold.woff"), static_files::source_code_pro::SEMIBOLD)?; write(cx.dst.join("SourceCodePro-LICENSE.txt"), static_files::source_code_pro::LICENSE)?; write(cx.dst.join("LICENSE-MIT.txt"), static_files::LICENSE_MIT)?; write(cx.dst.join("LICENSE-APACHE.txt"), static_files::LICENSE_APACHE)?; write(cx.dst.join("COPYRIGHT.txt"), static_files::COPYRIGHT)?; fn collect(path: &Path, krate: &str, key: &str) -> io::Result<(Vec<String>, Vec<String>)> { let mut ret = Vec::new(); let mut krates = Vec::new(); if path.exists() { let prefix = format!(r#"{}["{}"]"#, key, krate); for line in BufReader::new(File::open(path)?).lines() { let line = line?; if !line.starts_with(key) { continue; } if line.starts_with(&prefix) { continue; } ret.push(line.to_string()); krates.push( line[key.len() + 2..] .split('"') .next() .map(|s| s.to_owned()) .unwrap_or_else(String::new), ); } } Ok((ret, krates)) } fn collect_json(path: &Path, krate: &str) -> io::Result<(Vec<String>, Vec<String>)> { let mut ret = Vec::new(); let mut krates = Vec::new(); if path.exists() { let prefix = format!("\"{}\"", krate); for line in BufReader::new(File::open(path)?).lines() { let line = line?; if !line.starts_with('"') { continue; } if line.starts_with(&prefix) { continue; } if line.ends_with(",\\") { ret.push(line[..line.len() - 2].to_string()); } else { // Ends with "\\" (it's the case for the last added crate line) ret.push(line[..line.len() - 1].to_string()); } krates.push( line.split('"') .find(|s| !s.is_empty()) .map(|s| s.to_owned()) .unwrap_or_else(String::new), ); } } Ok((ret, krates)) } use std::ffi::OsString; #[derive(Debug)] struct Hierarchy { elem: OsString, children: FxHashMap<OsString, Hierarchy>, elems: FxHashSet<OsString>, } impl Hierarchy { fn new(elem: OsString) -> Hierarchy { Hierarchy { elem, children: FxHashMap::default(), elems: FxHashSet::default() } } fn to_json_string(&self) -> String { let mut subs: Vec<&Hierarchy> = self.children.values().collect(); subs.sort_unstable_by(|a, b| a.elem.cmp(&b.elem)); let mut files = self .elems .iter() .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion"))) .collect::<Vec<_>>(); files.sort_unstable(); let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(","); let dirs = if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) }; let files = files.join(","); let files = if files.is_empty() { String::new() } else { format!(",\"files\":[{}]", files) }; format!( "{{\"name\":\"{name}\"{dirs}{files}}}", name = self.elem.to_str().expect("invalid osstring conversion"), dirs = dirs, files = files ) } } if cx.shared.include_sources { let mut hierarchy = Hierarchy::new(OsString::new()); for source in cx .shared .local_sources .iter() .filter_map(|p| p.0.strip_prefix(&cx.shared.src_root).ok()) { let mut h = &mut hierarchy; let mut elems = source .components() .filter_map(|s| match s { Component::Normal(s) => Some(s.to_owned()), _ => None, }) .peekable(); loop { let cur_elem = elems.next().expect("empty file path"); if elems.peek().is_none() { h.elems.insert(cur_elem); break; } else { let e = cur_elem.clone(); h = h.children.entry(cur_elem.clone()).or_insert_with(|| Hierarchy::new(e)); } } } let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix)); let (mut all_sources, _krates) = try_err!(collect(&dst, &krate.name.as_str(), "sourcesIndex"), &dst); all_sources.push(format!( "sourcesIndex[\"{}\"] = {};", &krate.name, hierarchy.to_json_string() )); all_sources.sort(); let v = format!( "var N = null;var sourcesIndex = {{}};\n{}\ncreateSourceSidebar();\n", all_sources.join("\n") ); cx.shared.fs.write(&dst, v.as_bytes())?; } // Update the search index let dst = cx.dst.join(&format!("search-index{}.js", cx.shared.resource_suffix)); let (mut all_indexes, mut krates) = try_err!(collect_json(&dst, &krate.name.as_str()), &dst); all_indexes.push(search_index); // Sort the indexes by crate so the file will be generated identically even // with rustdoc running in parallel. all_indexes.sort(); { let mut v = String::from("var searchIndex = JSON.parse('{\\\n"); v.push_str(&all_indexes.join(",\\\n")); // "addSearchOptions" has to be called first so the crate filtering can be set before the // search might start (if it's set into the URL for example). v.push_str("\\\n}');\naddSearchOptions(searchIndex);initSearch(searchIndex);"); cx.shared.fs.write(&dst, &v)?; } if options.enable_index_page { if let Some(index_page) = options.index_page.clone() { let mut md_opts = options.clone(); md_opts.output = cx.dst.clone(); md_opts.external_html = (*cx.shared).layout.external_html.clone(); crate::markdown::render(&index_page, md_opts, cx.shared.edition) .map_err(|e| Error::new(e, &index_page))?; } else { let dst = cx.dst.join("index.html"); let page = layout::Page { title: "Index of crates", css_class: "mod", root_path: "./", static_root_path: cx.shared.static_root_path.as_deref(), description: "List of crates", keywords: BASIC_KEYWORDS, resource_suffix: &cx.shared.resource_suffix, extra_scripts: &[], static_extra_scripts: &[], }; krates.push(krate.name.to_string()); krates.sort(); krates.dedup(); let content = format!( "<h1 class=\"fqn\">\ <span class=\"in-band\">List of all crates</span>\ </h1><ul class=\"crate mod\">{}</ul>", krates .iter() .map(|s| { format!( "<li><a class=\"crate mod\" href=\"{}index.html\">{}</a></li>", ensure_trailing_slash(s), s ) }) .collect::<String>() ); let v = layout::render(&cx.shared.layout, &page, "", content, &cx.shared.style_files); cx.shared.fs.write(&dst, v.as_bytes())?; } } // Update the list of all implementors for traits let dst = cx.dst.join("implementors"); for (&did, imps) in &cx.cache.implementors { // Private modules can leak through to this phase of rustdoc, which // could contain implementations for otherwise private types. In some // rare cases we could find an implementation for an item which wasn't // indexed, so we just skip this step in that case. // // FIXME: this is a vague explanation for why this can't be a `get`, in // theory it should be... let &(ref remote_path, remote_item_type) = match cx.cache.paths.get(&did) { Some(p) => p, None => match cx.cache.external_paths.get(&did) { Some(p) => p, None => continue, }, }; #[derive(Serialize)] struct Implementor { text: String, synthetic: bool, types: Vec<String>, } let implementors = imps .iter() .filter_map(|imp| { // If the trait and implementation are in the same crate, then // there's no need to emit information about it (there's inlining // going on). If they're in different crates then the crate defining // the trait will be interested in our implementation. // // If the implementation is from another crate then that crate // should add it. if imp.impl_item.def_id.krate == did.krate || !imp.impl_item.def_id.is_local() { None } else { Some(Implementor { text: imp.inner_impl().print(cx.cache(), false).to_string(), synthetic: imp.inner_impl().synthetic, types: collect_paths_for_type(imp.inner_impl().for_.clone(), cx.cache()), }) } }) .collect::<Vec<_>>(); // Only create a js file if we have impls to add to it. If the trait is // documented locally though we always create the file to avoid dead // links. if implementors.is_empty() && !cx.cache.paths.contains_key(&did) { continue; } let implementors = format!( r#"implementors["{}"] = {};"#, krate.name, serde_json::to_string(&implementors).unwrap() ); let mut mydst = dst.clone(); for part in &remote_path[..remote_path.len() - 1] { mydst.push(part); } cx.shared.ensure_dir(&mydst)?; mydst.push(&format!("{}.{}.js", remote_item_type, remote_path[remote_path.len() - 1])); let (mut all_implementors, _) = try_err!(collect(&mydst, &krate.name.as_str(), "implementors"), &mydst); all_implementors.push(implementors); // Sort the implementors by crate so the file will be generated // identically even with rustdoc running in parallel. all_implementors.sort(); let mut v = String::from("(function() {var implementors = {};\n"); for implementor in &all_implementors { writeln!(v, "{}", *implementor).unwrap(); } v.push_str( "if (window.register_implementors) {\ window.register_implementors(implementors);\ } else {\ window.pending_implementors = implementors;\ }", ); v.push_str("})()"); cx.shared.fs.write(&mydst, &v)?; } Ok(()) } fn write_minify( fs: &DocFS, dst: PathBuf, contents: &str, enable_minification: bool, ) -> Result<(), Error> { if enable_minification { if dst.extension() == Some(&OsStr::new("css")) { let res = try_none!(minifier::css::minify(contents).ok(), &dst); fs.write(dst, res.as_bytes()) } else { fs.write(dst, minifier::js::minify(contents).as_bytes()) } } else { fs.write(dst, contents.as_bytes()) } } fn write_srclink(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) { if let Some(l) = cx.src_href(item) { write!(buf, "<a class=\"srclink\" href=\"{}\" title=\"goto source code\">[src]</a>", l) } } #[derive(Debug, Eq, PartialEq, Hash)] struct ItemEntry { url: String, name: String, } impl ItemEntry { fn new(mut url: String, name: String) -> ItemEntry { while url.starts_with('/') { url.remove(0); } ItemEntry { url, name } } } impl ItemEntry { crate fn print(&self) -> impl fmt::Display + '_ { crate::html::format::display_fn(move |f| { write!(f, "<a href=\"{}\">{}</a>", self.url, Escape(&self.name)) }) } } impl PartialOrd for ItemEntry { fn partial_cmp(&self, other: &ItemEntry) -> Option<::std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for ItemEntry { fn cmp(&self, other: &ItemEntry) -> ::std::cmp::Ordering { self.name.cmp(&other.name) } } #[derive(Debug)] struct AllTypes { structs: FxHashSet<ItemEntry>, enums: FxHashSet<ItemEntry>, unions: FxHashSet<ItemEntry>, primitives: FxHashSet<ItemEntry>, traits: FxHashSet<ItemEntry>, macros: FxHashSet<ItemEntry>, functions: FxHashSet<ItemEntry>, typedefs: FxHashSet<ItemEntry>, opaque_tys: FxHashSet<ItemEntry>, statics: FxHashSet<ItemEntry>, constants: FxHashSet<ItemEntry>, keywords: FxHashSet<ItemEntry>, attributes: FxHashSet<ItemEntry>, derives: FxHashSet<ItemEntry>, trait_aliases: FxHashSet<ItemEntry>, } impl AllTypes { fn new() -> AllTypes { let new_set = |cap| FxHashSet::with_capacity_and_hasher(cap, Default::default()); AllTypes { structs: new_set(100), enums: new_set(100), unions: new_set(100), primitives: new_set(26), traits: new_set(100), macros: new_set(100), functions: new_set(100), typedefs: new_set(100), opaque_tys: new_set(100), statics: new_set(100), constants: new_set(100), keywords: new_set(100), attributes: new_set(100), derives: new_set(100), trait_aliases: new_set(100), } } fn append(&mut self, item_name: String, item_type: &ItemType) { let mut url: Vec<_> = item_name.split("::").skip(1).collect(); if let Some(name) = url.pop() { let new_url = format!("{}/{}.{}.html", url.join("/"), item_type, name); url.push(name); let name = url.join("::"); match *item_type { ItemType::Struct => self.structs.insert(ItemEntry::new(new_url, name)), ItemType::Enum => self.enums.insert(ItemEntry::new(new_url, name)), ItemType::Union => self.unions.insert(ItemEntry::new(new_url, name)), ItemType::Primitive => self.primitives.insert(ItemEntry::new(new_url, name)), ItemType::Trait => self.traits.insert(ItemEntry::new(new_url, name)), ItemType::Macro => self.macros.insert(ItemEntry::new(new_url, name)), ItemType::Function => self.functions.insert(ItemEntry::new(new_url, name)), ItemType::Typedef => self.typedefs.insert(ItemEntry::new(new_url, name)), ItemType::OpaqueTy => self.opaque_tys.insert(ItemEntry::new(new_url, name)), ItemType::Static => self.statics.insert(ItemEntry::new(new_url, name)), ItemType::Constant => self.constants.insert(ItemEntry::new(new_url, name)), ItemType::ProcAttribute => self.attributes.insert(ItemEntry::new(new_url, name)), ItemType::ProcDerive => self.derives.insert(ItemEntry::new(new_url, name)), ItemType::TraitAlias => self.trait_aliases.insert(ItemEntry::new(new_url, name)), _ => true, }; } } } impl AllTypes { fn print(self, f: &mut Buffer) { fn print_entries(f: &mut Buffer, e: &FxHashSet<ItemEntry>, title: &str, class: &str) { if !e.is_empty() { let mut e: Vec<&ItemEntry> = e.iter().collect(); e.sort(); write!(f, "<h3 id=\"{}\">{}</h3><ul class=\"{} docblock\">", title, title, class); for s in e.iter() { write!(f, "<li>{}</li>", s.print()); } f.write_str("</ul>"); } } f.write_str( "<h1 class=\"fqn\">\ <span class=\"in-band\">List of all items</span>\ <span class=\"out-of-band\">\ <span id=\"render-detail\">\ <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \ title=\"collapse all docs\">\ [<span class=\"inner\">&#x2212;</span>]\ </a>\ </span> </span> <span class=\"in-band\">List of all items</span>\ </h1>", ); // Note: print_entries does not escape the title, because we know the current set of titles // don't require escaping. print_entries(f, &self.structs, "Structs", "structs"); print_entries(f, &self.enums, "Enums", "enums"); print_entries(f, &self.unions, "Unions", "unions"); print_entries(f, &self.primitives, "Primitives", "primitives"); print_entries(f, &self.traits, "Traits", "traits"); print_entries(f, &self.macros, "Macros", "macros"); print_entries(f, &self.attributes, "Attribute Macros", "attributes"); print_entries(f, &self.derives, "Derive Macros", "derives"); print_entries(f, &self.functions, "Functions", "functions"); print_entries(f, &self.typedefs, "Typedefs", "typedefs"); print_entries(f, &self.trait_aliases, "Trait Aliases", "trait-aliases"); print_entries(f, &self.opaque_tys, "Opaque Types", "opaque-types"); print_entries(f, &self.statics, "Statics", "statics"); print_entries(f, &self.constants, "Constants", "constants") } } #[derive(Debug)] enum Setting { Section { description: &'static str, sub_settings: Vec<Setting>, }, Toggle { js_data_name: &'static str, description: &'static str, default_value: bool, }, Select { js_data_name: &'static str, description: &'static str, default_value: &'static str, options: Vec<(String, String)>, }, } impl Setting { fn display(&self, root_path: &str, suffix: &str) -> String { match *self { Setting::Section { description, ref sub_settings } => format!( "<div class=\"setting-line\">\ <div class=\"title\">{}</div>\ <div class=\"sub-settings\">{}</div> </div>", description, sub_settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>() ), Setting::Toggle { js_data_name, description, default_value } => format!( "<div class=\"setting-line\">\ <label class=\"toggle\">\ <input type=\"checkbox\" id=\"{}\" {}>\ <span class=\"slider\"></span>\ </label>\ <div>{}</div>\ </div>", js_data_name, if default_value { " checked" } else { "" }, description, ), Setting::Select { js_data_name, description, default_value, ref options } => format!( "<div class=\"setting-line\">\ <div>{}</div>\ <label class=\"select-wrapper\">\ <select id=\"{}\" autocomplete=\"off\">{}</select>\ <img src=\"{}down-arrow{}.svg\" alt=\"Select item\">\ </label>\ </div>", description, js_data_name, options .iter() .map(|opt| format!( "<option value=\"{}\" {}>{}</option>", opt.0, if opt.0 == default_value { "selected" } else { "" }, opt.1, )) .collect::<String>(), root_path, suffix, ), } } } impl From<(&'static str, &'static str, bool)> for Setting { fn from(values: (&'static str, &'static str, bool)) -> Setting { Setting::Toggle { js_data_name: values.0, description: values.1, default_value: values.2 } } } impl<T: Into<Setting>> From<(&'static str, Vec<T>)> for Setting { fn from(values: (&'static str, Vec<T>)) -> Setting { Setting::Section { description: values.0, sub_settings: values.1.into_iter().map(|v| v.into()).collect::<Vec<_>>(), } } } fn settings(root_path: &str, suffix: &str, themes: &[StylePath]) -> Result<String, Error> { let theme_names: Vec<(String, String)> = themes .iter() .map(|entry| { let theme = try_none!(try_none!(entry.path.file_stem(), &entry.path).to_str(), &entry.path) .to_string(); Ok((theme.clone(), theme)) }) .collect::<Result<_, Error>>()?; // (id, explanation, default value) let settings: &[Setting] = &[ ( "Theme preferences", vec![ Setting::from(("use-system-theme", "Use system theme", true)), Setting::Select { js_data_name: "preferred-dark-theme", description: "Preferred dark theme", default_value: "dark", options: theme_names.clone(), }, Setting::Select { js_data_name: "preferred-light-theme", description: "Preferred light theme", default_value: "light", options: theme_names, }, ], ) .into(), ( "Auto-hide item declarations", vec![ ("auto-hide-struct", "Auto-hide structs declaration", true), ("auto-hide-enum", "Auto-hide enums declaration", false), ("auto-hide-union", "Auto-hide unions declaration", true), ("auto-hide-trait", "Auto-hide traits declaration", true), ("auto-hide-macro", "Auto-hide macros declaration", false), ], ) .into(), ("auto-hide-attributes", "Auto-hide item attributes.", true).into(), ("auto-hide-method-docs", "Auto-hide item methods' documentation", false).into(), ("auto-hide-trait-implementations", "Auto-hide trait implementation documentation", true) .into(), ("auto-collapse-implementors", "Auto-hide implementors of a trait", true).into(), ("go-to-only-result", "Directly go to item in search if there is only one result", false) .into(), ("line-numbers", "Show line numbers on code examples", false).into(), ("disable-shortcuts", "Disable keyboard shortcuts", false).into(), ]; Ok(format!( "<h1 class=\"fqn\">\ <span class=\"in-band\">Rustdoc settings</span>\ </h1>\ <div class=\"settings\">{}</div>\ <script src=\"{}settings{}.js\"></script>", settings.iter().map(|s| s.display(root_path, suffix)).collect::<String>(), root_path, suffix )) } impl Context<'_> { fn derive_id(&self, id: String) -> String { let mut map = self.id_map.borrow_mut(); map.derive(id) } /// String representation of how to get back to the root path of the 'doc/' /// folder in terms of a relative URL. fn root_path(&self) -> String { "../".repeat(self.current.len()) } fn render_item(&self, it: &clean::Item, pushname: bool) -> String { // A little unfortunate that this is done like this, but it sure // does make formatting *a lot* nicer. CURRENT_DEPTH.with(|slot| { slot.set(self.current.len()); }); let mut title = if it.is_primitive() || it.is_keyword() { // No need to include the namespace for primitive types and keywords String::new() } else { self.current.join("::") }; if pushname { if !title.is_empty() { title.push_str("::"); } title.push_str(&it.name.unwrap().as_str()); } title.push_str(" - Rust"); let tyname = it.type_(); let desc = if it.is_crate() { format!("API documentation for the Rust `{}` crate.", self.shared.layout.krate) } else { format!( "API documentation for the Rust `{}` {} in crate `{}`.", it.name.as_ref().unwrap(), tyname, self.shared.layout.krate ) }; let keywords = make_item_keywords(it); let page = layout::Page { css_class: tyname.as_str(), root_path: &self.root_path(), static_root_path: self.shared.static_root_path.as_deref(), title: &title, description: &desc, keywords: &keywords, resource_suffix: &self.shared.resource_suffix, extra_scripts: &[], static_extra_scripts: &[], }; { self.id_map.borrow_mut().reset(); self.id_map.borrow_mut().populate(&INITIAL_IDS); } if !self.render_redirect_pages { layout::render( &self.shared.layout, &page, |buf: &mut _| print_sidebar(self, it, buf), |buf: &mut _| print_item(self, it, buf), &self.shared.style_files, ) } else { let mut url = self.root_path(); if let Some(&(ref names, ty)) = self.cache.paths.get(&it.def_id) { for name in &names[..names.len() - 1] { url.push_str(name); url.push('/'); } url.push_str(&item_path(ty, names.last().unwrap())); layout::redirect(&url) } else { String::new() } } } /// Construct a map of items shown in the sidebar to a plain-text summary of their docs. fn build_sidebar_items(&self, m: &clean::Module) -> BTreeMap<String, Vec<NameDoc>> { // BTreeMap instead of HashMap to get a sorted output let mut map: BTreeMap<_, Vec<_>> = BTreeMap::new(); for item in &m.items { if item.is_stripped() { continue; } let short = item.type_(); let myname = match item.name { None => continue, Some(ref s) => s.to_string(), }; let short = short.to_string(); map.entry(short).or_default().push(( myname, Some(item.doc_value().map_or_else(String::new, |s| plain_text_summary(&s))), )); } if self.shared.sort_modules_alphabetically { for items in map.values_mut() { items.sort(); } } map } /// Generates a url appropriate for an `href` attribute back to the source of /// this item. /// /// The url generated, when clicked, will redirect the browser back to the /// original source code. /// /// If `None` is returned, then a source link couldn't be generated. This /// may happen, for example, with externally inlined items where the source /// of their crate documentation isn't known. fn src_href(&self, item: &clean::Item) -> Option<String> { let mut root = self.root_path(); let mut path = String::new(); let cnum = item.source.cnum(self.sess()); // We can safely ignore synthetic `SourceFile`s. let file = match item.source.filename(self.sess()) { FileName::Real(ref path) => path.local_path().to_path_buf(), _ => return None, }; let file = &file; let symbol; let (krate, path) = if cnum == LOCAL_CRATE { if let Some(path) = self.shared.local_sources.get(file) { (self.shared.layout.krate.as_str(), path) } else { return None; } } else { let (krate, src_root) = match *self.cache.extern_locations.get(&cnum)? { (name, ref src, ExternalLocation::Local) => (name, src), (name, ref src, ExternalLocation::Remote(ref s)) => { root = s.to_string(); (name, src) } (_, _, ExternalLocation::Unknown) => return None, }; sources::clean_path(&src_root, file, false, |component| { path.push_str(&component.to_string_lossy()); path.push('/'); }); let mut fname = file.file_name().expect("source has no filename").to_os_string(); fname.push(".html"); path.push_str(&fname.to_string_lossy()); symbol = krate.as_str(); (&*symbol, &path) }; let loline = item.source.lo(self.sess()).line; let hiline = item.source.hi(self.sess()).line; let lines = if loline == hiline { loline.to_string() } else { format!("{}-{}", loline, hiline) }; Some(format!( "{root}src/{krate}/{path}#{lines}", root = Escape(&root), krate = krate, path = path, lines = lines )) } } fn wrap_into_docblock<F>(w: &mut Buffer, f: F) where F: FnOnce(&mut Buffer), { w.write_str("<div class=\"docblock type-decl hidden-by-usual-hider\">"); f(w); w.write_str("</div>") } fn print_item(cx: &Context<'_>, item: &clean::Item, buf: &mut Buffer) { debug_assert!(!item.is_stripped()); // Write the breadcrumb trail header for the top buf.write_str("<h1 class=\"fqn\"><span class=\"in-band\">"); let name = match *item.kind { clean::ModuleItem(ref m) => { if m.is_crate { "Crate " } else { "Module " } } clean::FunctionItem(..) | clean::ForeignFunctionItem(..) => "Function ", clean::TraitItem(..) => "Trait ", clean::StructItem(..) => "Struct ", clean::UnionItem(..) => "Union ", clean::EnumItem(..) => "Enum ", clean::TypedefItem(..) => "Type Definition ", clean::MacroItem(..) => "Macro ", clean::ProcMacroItem(ref mac) => match mac.kind { MacroKind::Bang => "Macro ", MacroKind::Attr => "Attribute Macro ", MacroKind::Derive => "Derive Macro ", }, clean::PrimitiveItem(..) => "Primitive Type ", clean::StaticItem(..) | clean::ForeignStaticItem(..) => "Static ", clean::ConstantItem(..) => "Constant ", clean::ForeignTypeItem => "Foreign Type ", clean::KeywordItem(..) => "Keyword ", clean::OpaqueTyItem(..) => "Opaque Type ", clean::TraitAliasItem(..) => "Trait Alias ", _ => { // We don't generate pages for any other type. unreachable!(); } }; buf.write_str(name); if !item.is_primitive() && !item.is_keyword() { let cur = &cx.current; let amt = if item.is_mod() { cur.len() - 1 } else { cur.len() }; for (i, component) in cur.iter().enumerate().take(amt) { write!( buf, "<a href=\"{}index.html\">{}</a>::<wbr>", "../".repeat(cur.len() - i - 1), component ); } } write!(buf, "<a class=\"{}\" href=\"\">{}</a>", item.type_(), item.name.as_ref().unwrap()); buf.write_str("</span>"); // in-band buf.write_str("<span class=\"out-of-band\">"); render_stability_since_raw( buf, item.stable_since(cx.tcx()).as_deref(), item.const_stable_since(cx.tcx()).as_deref(), None, None, ); buf.write_str( "<span id=\"render-detail\">\ <a id=\"toggle-all-docs\" href=\"javascript:void(0)\" \ title=\"collapse all docs\">\ [<span class=\"inner\">&#x2212;</span>]\ </a>\ </span>", ); // Write `src` tag // // When this item is part of a `crate use` in a downstream crate, the // [src] link in the downstream documentation will actually come back to // this page, and this link will be auto-clicked. The `id` attribute is // used to find the link to auto-click. if cx.shared.include_sources && !item.is_primitive() { write_srclink(cx, item, buf); } buf.write_str("</span></h1>"); // out-of-band match *item.kind { clean::ModuleItem(ref m) => item_module(buf, cx, item, &m.items), clean::FunctionItem(ref f) | clean::ForeignFunctionItem(ref f) => { item_function(buf, cx, item, f) } clean::TraitItem(ref t) => item_trait(buf, cx, item, t), clean::StructItem(ref s) => item_struct(buf, cx, item, s), clean::UnionItem(ref s) => item_union(buf, cx, item, s), clean::EnumItem(ref e) => item_enum(buf, cx, item, e), clean::TypedefItem(ref t, _) => item_typedef(buf, cx, item, t), clean::MacroItem(ref m) => item_macro(buf, cx, item, m), clean::ProcMacroItem(ref m) => item_proc_macro(buf, cx, item, m), clean::PrimitiveItem(_) => item_primitive(buf, cx, item), clean::StaticItem(ref i) | clean::ForeignStaticItem(ref i) => item_static(buf, cx, item, i), clean::ConstantItem(ref c) => item_constant(buf, cx, item, c), clean::ForeignTypeItem => item_foreign_type(buf, cx, item), clean::KeywordItem(_) => item_keyword(buf, cx, item), clean::OpaqueTyItem(ref e) => item_opaque_ty(buf, cx, item, e), clean::TraitAliasItem(ref ta) => item_trait_alias(buf, cx, item, ta), _ => { // We don't generate pages for any other type. unreachable!(); } } } fn item_path(ty: ItemType, name: &str) -> String { match ty { ItemType::Module => format!("{}index.html", ensure_trailing_slash(name)), _ => format!("{}.{}.html", ty, name), } } fn full_path(cx: &Context<'_>, item: &clean::Item) -> String { let mut s = cx.current.join("::"); s.push_str("::"); s.push_str(&item.name.unwrap().as_str()); s } fn document(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: Option<&clean::Item>) { if let Some(ref name) = item.name { info!("Documenting {}", name); } document_item_info(w, cx, item, false, parent); document_full(w, item, cx, "", false); } /// Render md_text as markdown. fn render_markdown( w: &mut Buffer, cx: &Context<'_>, md_text: &str, links: Vec<RenderedLink>, prefix: &str, is_hidden: bool, ) { let mut ids = cx.id_map.borrow_mut(); write!( w, "<div class=\"docblock{}\">{}{}</div>", if is_hidden { " hidden" } else { "" }, prefix, Markdown( md_text, &links, &mut ids, cx.shared.codes, cx.shared.edition, &cx.shared.playground ) .into_string() ) } /// Writes a documentation block containing only the first paragraph of the documentation. If the /// docs are longer, a "Read more" link is appended to the end. fn document_short( w: &mut Buffer, item: &clean::Item, cx: &Context<'_>, link: AssocItemLink<'_>, prefix: &str, is_hidden: bool, parent: Option<&clean::Item>, show_def_docs: bool, ) { document_item_info(w, cx, item, is_hidden, parent); if !show_def_docs { return; } if let Some(s) = item.doc_value() { let mut summary_html = MarkdownSummaryLine(&s, &item.links(&cx.cache)).into_string(); if s.contains('\n') { let link = format!(r#" <a href="{}">Read more</a>"#, naive_assoc_href(item, link, cx.cache())); if let Some(idx) = summary_html.rfind("</p>") { summary_html.insert_str(idx, &link); } else { summary_html.push_str(&link); } } write!( w, "<div class='docblock{}'>{}{}</div>", if is_hidden { " hidden" } else { "" }, prefix, summary_html, ); } else if !prefix.is_empty() { write!( w, "<div class=\"docblock{}\">{}</div>", if is_hidden { " hidden" } else { "" }, prefix ); } } fn document_full( w: &mut Buffer, item: &clean::Item, cx: &Context<'_>, prefix: &str, is_hidden: bool, ) { if let Some(s) = cx.shared.maybe_collapsed_doc_value(item) { debug!("Doc block: =====\n{}\n=====", s); render_markdown(w, cx, &*s, item.links(&cx.cache), prefix, is_hidden); } else if !prefix.is_empty() { if is_hidden { w.write_str("<div class=\"docblock hidden\">"); } else { w.write_str("<div class=\"docblock\">"); } w.write_str(prefix); w.write_str("</div>"); } } /// Add extra information about an item such as: /// /// * Stability /// * Deprecated /// * Required features (through the `doc_cfg` feature) fn document_item_info( w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, is_hidden: bool, parent: Option<&clean::Item>, ) { let item_infos = short_item_info(item, cx, parent); if !item_infos.is_empty() { if is_hidden { w.write_str("<div class=\"item-info hidden\">"); } else { w.write_str("<div class=\"item-info\">"); } for info in item_infos { w.write_str(&info); } w.write_str("</div>"); } } fn document_non_exhaustive_header(item: &clean::Item) -> &str { if item.is_non_exhaustive() { " (Non-exhaustive)" } else { "" } } fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) { if item.is_non_exhaustive() { write!(w, "<div class=\"docblock non-exhaustive non-exhaustive-{}\">", { if item.is_struct() { "struct" } else if item.is_enum() { "enum" } else if item.is_variant() { "variant" } else { "type" } }); if item.is_struct() { w.write_str( "Non-exhaustive structs could have additional fields added in future. \ Therefore, non-exhaustive structs cannot be constructed in external crates \ using the traditional <code>Struct {{ .. }}</code> syntax; cannot be \ matched against without a wildcard <code>..</code>; and \ struct update syntax will not work.", ); } else if item.is_enum() { w.write_str( "Non-exhaustive enums could have additional variants added in future. \ Therefore, when matching against variants of non-exhaustive enums, an \ extra wildcard arm must be added to account for any future variants.", ); } else if item.is_variant() { w.write_str( "Non-exhaustive enum variants could have additional fields added in future. \ Therefore, non-exhaustive enum variants cannot be constructed in external \ crates and cannot be matched against.", ); } else { w.write_str( "This type will require a wildcard arm in any match statements or constructors.", ); } w.write_str("</div>"); } } /// Compare two strings treating multi-digit numbers as single units (i.e. natural sort order). crate fn compare_names(mut lhs: &str, mut rhs: &str) -> Ordering { /// Takes a non-numeric and a numeric part from the given &str. fn take_parts<'a>(s: &mut &'a str) -> (&'a str, &'a str) { let i = s.find(|c: char| c.is_ascii_digit()); let (a, b) = s.split_at(i.unwrap_or(s.len())); let i = b.find(|c: char| !c.is_ascii_digit()); let (b, c) = b.split_at(i.unwrap_or(b.len())); *s = c; (a, b) } while !lhs.is_empty() || !rhs.is_empty() { let (la, lb) = take_parts(&mut lhs); let (ra, rb) = take_parts(&mut rhs); // First process the non-numeric part. match la.cmp(ra) { Ordering::Equal => (), x => return x, } // Then process the numeric part, if both sides have one (and they fit in a u64). if let (Ok(ln), Ok(rn)) = (lb.parse::<u64>(), rb.parse::<u64>()) { match ln.cmp(&rn) { Ordering::Equal => (), x => return x, } } // Then process the numeric part again, but this time as strings. match lb.cmp(rb) { Ordering::Equal => (), x => return x, } } Ordering::Equal } fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[clean::Item]) { document(w, cx, item, None); let mut indices = (0..items.len()).filter(|i| !items[*i].is_stripped()).collect::<Vec<usize>>(); // the order of item types in the listing fn reorder(ty: ItemType) -> u8 { match ty { ItemType::ExternCrate => 0, ItemType::Import => 1, ItemType::Primitive => 2, ItemType::Module => 3, ItemType::Macro => 4, ItemType::Struct => 5, ItemType::Enum => 6, ItemType::Constant => 7, ItemType::Static => 8, ItemType::Trait => 9, ItemType::Function => 10, ItemType::Typedef => 12, ItemType::Union => 13, _ => 14 + ty as u8, } } fn cmp( i1: &clean::Item, i2: &clean::Item, idx1: usize, idx2: usize, tcx: TyCtxt<'_>, ) -> Ordering { let ty1 = i1.type_(); let ty2 = i2.type_(); if ty1 != ty2 { return (reorder(ty1), idx1).cmp(&(reorder(ty2), idx2)); } let s1 = i1.stability(tcx).as_ref().map(|s| s.level); let s2 = i2.stability(tcx).as_ref().map(|s| s.level); if let (Some(a), Some(b)) = (s1, s2) { match (a.is_stable(), b.is_stable()) { (true, true) | (false, false) => {} (false, true) => return Ordering::Less, (true, false) => return Ordering::Greater, } } let lhs = i1.name.unwrap_or(kw::Empty).as_str(); let rhs = i2.name.unwrap_or(kw::Empty).as_str(); compare_names(&lhs, &rhs) } if cx.shared.sort_modules_alphabetically { indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2, cx.tcx())); } // This call is to remove re-export duplicates in cases such as: // // ``` // crate mod foo { // crate mod bar { // crate trait Double { fn foo(); } // } // } // // crate use foo::bar::*; // crate use foo::*; // ``` // // `Double` will appear twice in the generated docs. // // FIXME: This code is quite ugly and could be improved. Small issue: DefId // can be identical even if the elements are different (mostly in imports). // So in case this is an import, we keep everything by adding a "unique id" // (which is the position in the vector). indices.dedup_by_key(|i| { ( items[*i].def_id, if items[*i].name.as_ref().is_some() { Some(full_path(cx, &items[*i])) } else { None }, items[*i].type_(), if items[*i].is_import() { *i } else { 0 }, ) }); debug!("{:?}", indices); let mut curty = None; for &idx in &indices { let myitem = &items[idx]; if myitem.is_stripped() { continue; } let myty = Some(myitem.type_()); if curty == Some(ItemType::ExternCrate) && myty == Some(ItemType::Import) { // Put `extern crate` and `use` re-exports in the same section. curty = myty; } else if myty != curty { if curty.is_some() { w.write_str("</table>"); } curty = myty; let (short, name) = item_ty_to_strs(&myty.unwrap()); write!( w, "<h2 id=\"{id}\" class=\"section-header\">\ <a href=\"#{id}\">{name}</a></h2>\n<table>", id = cx.derive_id(short.to_owned()), name = name ); } match *myitem.kind { clean::ExternCrateItem(ref name, ref src) => { use crate::html::format::anchor; match *src { Some(ref src) => write!( w, "<tr><td><code>{}extern crate {} as {};", myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()), anchor(myitem.def_id, &*src.as_str(), cx.cache()), name ), None => write!( w, "<tr><td><code>{}extern crate {};", myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()), anchor(myitem.def_id, &*name.as_str(), cx.cache()) ), } w.write_str("</code></td></tr>"); } clean::ImportItem(ref import) => { write!( w, "<tr><td><code>{}{}</code></td></tr>", myitem.visibility.print_with_space(cx.tcx(), myitem.def_id, cx.cache()), import.print(cx.cache()) ); } _ => { if myitem.name.is_none() { continue; } let unsafety_flag = match *myitem.kind { clean::FunctionItem(ref func) | clean::ForeignFunctionItem(ref func) if func.header.unsafety == hir::Unsafety::Unsafe => { "<a title=\"unsafe function\" href=\"#\"><sup>⚠</sup></a>" } _ => "", }; let stab = myitem.stability_class(cx.tcx()); let add = if stab.is_some() { " " } else { "" }; let doc_value = myitem.doc_value().unwrap_or_default(); write!( w, "<tr class=\"{stab}{add}module-item\">\ <td><a class=\"{class}\" href=\"{href}\" \ title=\"{title}\">{name}</a>{unsafety_flag}</td>\ <td class=\"docblock-short\">{stab_tags}{docs}</td>\ </tr>", name = *myitem.name.as_ref().unwrap(), stab_tags = extra_info_tags(myitem, item, cx.tcx()), docs = MarkdownSummaryLine(&doc_value, &myitem.links(&cx.cache)).into_string(), class = myitem.type_(), add = add, stab = stab.unwrap_or_else(String::new), unsafety_flag = unsafety_flag, href = item_path(myitem.type_(), &myitem.name.unwrap().as_str()), title = [full_path(cx, myitem), myitem.type_().to_string()] .iter() .filter_map(|s| if !s.is_empty() { Some(s.as_str()) } else { None }) .collect::<Vec<_>>() .join(" "), ); } } } if curty.is_some() { w.write_str("</table>"); } } /// Render the stability, deprecation and portability tags that are displayed in the item's summary /// at the module level. fn extra_info_tags(item: &clean::Item, parent: &clean::Item, tcx: TyCtxt<'_>) -> String { let mut tags = String::new(); fn tag_html(class: &str, title: &str, contents: &str) -> String { format!(r#"<span class="stab {}" title="{}">{}</span>"#, class, Escape(title), contents) } // The trailing space after each tag is to space it properly against the rest of the docs. if let Some(depr) = &item.deprecation(tcx) { let mut message = "Deprecated"; if !stability::deprecation_in_effect( depr.is_since_rustc_version, depr.since.map(|s| s.as_str()).as_deref(), ) { message = "Deprecation planned"; } tags += &tag_html("deprecated", "", message); } // The "rustc_private" crates are permanently unstable so it makes no sense // to render "unstable" everywhere. if item .stability(tcx) .as_ref() .map(|s| s.level.is_unstable() && s.feature != sym::rustc_private) == Some(true) { tags += &tag_html("unstable", "", "Experimental"); } let cfg = match (&item.attrs.cfg, parent.attrs.cfg.as_ref()) { (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg), (cfg, _) => cfg.as_deref().cloned(), }; debug!("Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.attrs.cfg, cfg); if let Some(ref cfg) = cfg { tags += &tag_html("portability", &cfg.render_long_plain(), &cfg.render_short_html()); } tags } fn portability(item: &clean::Item, parent: Option<&clean::Item>) -> Option<String> { let cfg = match (&item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref())) { (Some(cfg), Some(parent_cfg)) => cfg.simplify_with(parent_cfg), (cfg, _) => cfg.as_deref().cloned(), }; debug!( "Portability {:?} - {:?} = {:?}", item.attrs.cfg, parent.and_then(|p| p.attrs.cfg.as_ref()), cfg ); Some(format!("<div class=\"stab portability\">{}</div>", cfg?.render_long_html())) } /// Render the stability, deprecation and portability information that is displayed at the top of /// the item's documentation. fn short_item_info( item: &clean::Item, cx: &Context<'_>, parent: Option<&clean::Item>, ) -> Vec<String> { let mut extra_info = vec![]; let error_codes = cx.shared.codes; if let Some(Deprecation { note, since, is_since_rustc_version, suggestion: _ }) = item.deprecation(cx.tcx()) { // We display deprecation messages for #[deprecated] and #[rustc_deprecated] // but only display the future-deprecation messages for #[rustc_deprecated]. let mut message = if let Some(since) = since { let since = &since.as_str(); if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) { if *since == "TBD" { String::from("Deprecating in a future Rust version") } else { format!("Deprecating in {}", Escape(since)) } } else { format!("Deprecated since {}", Escape(since)) } } else { String::from("Deprecated") }; if let Some(note) = note { let note = note.as_str(); let mut ids = cx.id_map.borrow_mut(); let html = MarkdownHtml( &note, &mut ids, error_codes, cx.shared.edition, &cx.shared.playground, ); message.push_str(&format!(": {}", html.into_string())); } extra_info.push(format!( "<div class=\"stab deprecated\"><span class=\"emoji\">👎</span> {}</div>", message, )); } // Render unstable items. But don't render "rustc_private" crates (internal compiler crates). // Those crates are permanently unstable so it makes no sense to render "unstable" everywhere. if let Some((StabilityLevel::Unstable { reason, issue, .. }, feature)) = item .stability(cx.tcx()) .as_ref() .filter(|stab| stab.feature != sym::rustc_private) .map(|stab| (stab.level, stab.feature)) { let mut message = "<span class=\"emoji\">🔬</span> This is a nightly-only experimental API.".to_owned(); let mut feature = format!("<code>{}</code>", Escape(&feature.as_str())); if let (Some(url), Some(issue)) = (&cx.shared.issue_tracker_base_url, issue) { feature.push_str(&format!( "&nbsp;<a href=\"{url}{issue}\">#{issue}</a>", url = url, issue = issue )); } message.push_str(&format!(" ({})", feature)); if let Some(unstable_reason) = reason { let mut ids = cx.id_map.borrow_mut(); message = format!( "<details><summary>{}</summary>{}</details>", message, MarkdownHtml( &unstable_reason.as_str(), &mut ids, error_codes, cx.shared.edition, &cx.shared.playground, ) .into_string() ); } extra_info.push(format!("<div class=\"stab unstable\">{}</div>", message)); } if let Some(portability) = portability(item, parent) { extra_info.push(portability); } extra_info } fn item_constant(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, c: &clean::Constant) { w.write_str("<pre class=\"rust const\">"); render_attributes(w, it, false); write!( w, "{vis}const {name}: {typ}", vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()), name = it.name.as_ref().unwrap(), typ = c.type_.print(cx.cache()), ); if c.value.is_some() || c.is_literal { write!(w, " = {expr};", expr = Escape(&c.expr)); } else { w.write_str(";"); } if let Some(value) = &c.value { if !c.is_literal { let value_lowercase = value.to_lowercase(); let expr_lowercase = c.expr.to_lowercase(); if value_lowercase != expr_lowercase && value_lowercase.trim_end_matches("i32") != expr_lowercase { write!(w, " // {value}", value = Escape(value)); } } } w.write_str("</pre>"); document(w, cx, it, None) } fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Static) { w.write_str("<pre class=\"rust static\">"); render_attributes(w, it, false); write!( w, "{vis}static {mutability}{name}: {typ}</pre>", vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()), mutability = s.mutability.print_with_space(), name = it.name.as_ref().unwrap(), typ = s.type_.print(cx.cache()) ); document(w, cx, it, None) } fn item_function(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, f: &clean::Function) { let header_len = format!( "{}{}{}{}{:#}fn {}{:#}", it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()), f.header.constness.print_with_space(), f.header.asyncness.print_with_space(), f.header.unsafety.print_with_space(), print_abi_with_space(f.header.abi), it.name.as_ref().unwrap(), f.generics.print(cx.cache()) ) .len(); w.write_str("<pre class=\"rust fn\">"); render_attributes(w, it, false); write!( w, "{vis}{constness}{asyncness}{unsafety}{abi}fn \ {name}{generics}{decl}{spotlight}{where_clause}</pre>", vis = it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()), constness = f.header.constness.print_with_space(), asyncness = f.header.asyncness.print_with_space(), unsafety = f.header.unsafety.print_with_space(), abi = print_abi_with_space(f.header.abi), name = it.name.as_ref().unwrap(), generics = f.generics.print(cx.cache()), where_clause = WhereClause { gens: &f.generics, indent: 0, end_newline: true }.print(cx.cache()), decl = Function { decl: &f.decl, header_len, indent: 0, asyncness: f.header.asyncness } .print(cx.cache()), spotlight = spotlight_decl(&f.decl, cx.cache()), ); document(w, cx, it, None) } fn render_implementor( cx: &Context<'_>, implementor: &Impl, trait_: &clean::Item, w: &mut Buffer, implementor_dups: &FxHashMap<Symbol, (DefId, bool)>, aliases: &[String], ) { // If there's already another implementor that has the same abbridged name, use the // full path, for example in `std::iter::ExactSizeIterator` let use_absolute = match implementor.inner_impl().for_ { clean::ResolvedPath { ref path, is_generic: false, .. } | clean::BorrowedRef { type_: box clean::ResolvedPath { ref path, is_generic: false, .. }, .. } => implementor_dups[&path.last()].1, _ => false, }; render_impl( w, cx, implementor, trait_, AssocItemLink::Anchor(None), RenderMode::Normal, trait_.stable_since(cx.tcx()).as_deref(), trait_.const_stable_since(cx.tcx()).as_deref(), false, Some(use_absolute), false, false, aliases, ); } fn render_impls( cx: &Context<'_>, w: &mut Buffer, traits: &[&&Impl], containing_item: &clean::Item, ) { let mut impls = traits .iter() .map(|i| { let did = i.trait_did_full(cx.cache()).unwrap(); let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods); let mut buffer = if w.is_for_html() { Buffer::html() } else { Buffer::new() }; render_impl( &mut buffer, cx, i, containing_item, assoc_link, RenderMode::Normal, containing_item.stable_since(cx.tcx()).as_deref(), containing_item.const_stable_since(cx.tcx()).as_deref(), true, None, false, true, &[], ); buffer.into_inner() }) .collect::<Vec<_>>(); impls.sort(); w.write_str(&impls.join("")); } fn bounds(t_bounds: &[clean::GenericBound], trait_alias: bool, cache: &Cache) -> String { let mut bounds = String::new(); if !t_bounds.is_empty() { if !trait_alias { bounds.push_str(": "); } for (i, p) in t_bounds.iter().enumerate() { if i > 0 { bounds.push_str(" + "); } bounds.push_str(&p.print(cache).to_string()); } } bounds } fn compare_impl<'a, 'b>(lhs: &'a &&Impl, rhs: &'b &&Impl, cache: &Cache) -> Ordering { let lhs = format!("{}", lhs.inner_impl().print(cache, false)); let rhs = format!("{}", rhs.inner_impl().print(cache, false)); // lhs and rhs are formatted as HTML, which may be unnecessary compare_names(&lhs, &rhs) } fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Trait) { let bounds = bounds(&t.bounds, false, cx.cache()); let types = t.items.iter().filter(|m| m.is_associated_type()).collect::<Vec<_>>(); let consts = t.items.iter().filter(|m| m.is_associated_const()).collect::<Vec<_>>(); let required = t.items.iter().filter(|m| m.is_ty_method()).collect::<Vec<_>>(); let provided = t.items.iter().filter(|m| m.is_method()).collect::<Vec<_>>(); // Output the trait definition wrap_into_docblock(w, |w| { w.write_str("<pre class=\"rust trait\">"); render_attributes(w, it, true); write!( w, "{}{}{}trait {}{}{}", it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()), t.unsafety.print_with_space(), if t.is_auto { "auto " } else { "" }, it.name.as_ref().unwrap(), t.generics.print(cx.cache()), bounds ); if !t.generics.where_predicates.is_empty() { let where_ = WhereClause { gens: &t.generics, indent: 0, end_newline: true }; write!(w, "{}", where_.print(cx.cache())); } else { w.write_str(" "); } if t.items.is_empty() { w.write_str("{ }"); } else { // FIXME: we should be using a derived_id for the Anchors here w.write_str("{\n"); for t in &types { render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx); w.write_str(";\n"); } if !types.is_empty() && !consts.is_empty() { w.write_str("\n"); } for t in &consts { render_assoc_item(w, t, AssocItemLink::Anchor(None), ItemType::Trait, cx); w.write_str(";\n"); } if !consts.is_empty() && !required.is_empty() { w.write_str("\n"); } for (pos, m) in required.iter().enumerate() { render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx); w.write_str(";\n"); if pos < required.len() - 1 { w.write_str("<div class=\"item-spacer\"></div>"); } } if !required.is_empty() && !provided.is_empty() { w.write_str("\n"); } for (pos, m) in provided.iter().enumerate() { render_assoc_item(w, m, AssocItemLink::Anchor(None), ItemType::Trait, cx); match *m.kind { clean::MethodItem(ref inner, _) if !inner.generics.where_predicates.is_empty() => { w.write_str(",\n { ... }\n"); } _ => { w.write_str(" { ... }\n"); } } if pos < provided.len() - 1 { w.write_str("<div class=\"item-spacer\"></div>"); } } w.write_str("}"); } w.write_str("</pre>") }); // Trait documentation document(w, cx, it, None); fn write_small_section_header(w: &mut Buffer, id: &str, title: &str, extra_content: &str) { write!( w, "<h2 id=\"{0}\" class=\"small-section-header\">\ {1}<a href=\"#{0}\" class=\"anchor\"></a>\ </h2>{2}", id, title, extra_content ) } fn write_loading_content(w: &mut Buffer, extra_content: &str) { write!(w, "{}<span class=\"loading-content\">Loading content...</span>", extra_content) } fn trait_item(w: &mut Buffer, cx: &Context<'_>, m: &clean::Item, t: &clean::Item) { let name = m.name.as_ref().unwrap(); info!("Documenting {} on {:?}", name, t.name); let item_type = m.type_(); let id = cx.derive_id(format!("{}.{}", item_type, name)); write!(w, "<h3 id=\"{id}\" class=\"method\"><code>", id = id,); render_assoc_item(w, m, AssocItemLink::Anchor(Some(&id)), ItemType::Impl, cx); w.write_str("</code>"); render_stability_since(w, m, t, cx.tcx()); write_srclink(cx, m, w); w.write_str("</h3>"); document(w, cx, m, Some(t)); } if !types.is_empty() { write_small_section_header( w, "associated-types", "Associated Types", "<div class=\"methods\">", ); for t in types { trait_item(w, cx, t, it); } write_loading_content(w, "</div>"); } if !consts.is_empty() { write_small_section_header( w, "associated-const", "Associated Constants", "<div class=\"methods\">", ); for t in consts { trait_item(w, cx, t, it); } write_loading_content(w, "</div>"); } // Output the documentation for each function individually if !required.is_empty() { write_small_section_header( w, "required-methods", "Required methods", "<div class=\"methods\">", ); for m in required { trait_item(w, cx, m, it); } write_loading_content(w, "</div>"); } if !provided.is_empty() { write_small_section_header( w, "provided-methods", "Provided methods", "<div class=\"methods\">", ); for m in provided { trait_item(w, cx, m, it); } write_loading_content(w, "</div>"); } // If there are methods directly on this trait object, render them here. render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All); if let Some(implementors) = cx.cache.implementors.get(&it.def_id) { // The DefId is for the first Type found with that name. The bool is // if any Types with the same name but different DefId have been found. let mut implementor_dups: FxHashMap<Symbol, (DefId, bool)> = FxHashMap::default(); for implementor in implementors { match implementor.inner_impl().for_ { clean::ResolvedPath { ref path, did, is_generic: false, .. } | clean::BorrowedRef { type_: box clean::ResolvedPath { ref path, did, is_generic: false, .. }, .. } => { let &mut (prev_did, ref mut has_duplicates) = implementor_dups.entry(path.last()).or_insert((did, false)); if prev_did != did { *has_duplicates = true; } } _ => {} } } let (local, foreign) = implementors.iter().partition::<Vec<_>, _>(|i| { i.inner_impl() .for_ .def_id_full(cx.cache()) .map_or(true, |d| cx.cache.paths.contains_key(&d)) }); let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) = local.iter().partition(|i| i.inner_impl().synthetic); synthetic.sort_by(|a, b| compare_impl(a, b, cx.cache())); concrete.sort_by(|a, b| compare_impl(a, b, cx.cache())); if !foreign.is_empty() { write_small_section_header(w, "foreign-impls", "Implementations on Foreign Types", ""); for implementor in foreign { let assoc_link = AssocItemLink::GotoSource( implementor.impl_item.def_id, &implementor.inner_impl().provided_trait_methods, ); render_impl( w, cx, &implementor, it, assoc_link, RenderMode::Normal, implementor.impl_item.stable_since(cx.tcx()).as_deref(), implementor.impl_item.const_stable_since(cx.tcx()).as_deref(), false, None, true, false, &[], ); } write_loading_content(w, ""); } write_small_section_header( w, "implementors", "Implementors", "<div class=\"item-list\" id=\"implementors-list\">", ); for implementor in concrete { render_implementor(cx, implementor, it, w, &implementor_dups, &[]); } write_loading_content(w, "</div>"); if t.is_auto { write_small_section_header( w, "synthetic-implementors", "Auto implementors", "<div class=\"item-list\" id=\"synthetic-implementors-list\">", ); for implementor in synthetic { render_implementor( cx, implementor, it, w, &implementor_dups, &collect_paths_for_type(implementor.inner_impl().for_.clone(), &cx.cache), ); } write_loading_content(w, "</div>"); } } else { // even without any implementations to write in, we still want the heading and list, so the // implementors javascript file pulled in below has somewhere to write the impls into write_small_section_header( w, "implementors", "Implementors", "<div class=\"item-list\" id=\"implementors-list\">", ); write_loading_content(w, "</div>"); if t.is_auto { write_small_section_header( w, "synthetic-implementors", "Auto implementors", "<div class=\"item-list\" id=\"synthetic-implementors-list\">", ); write_loading_content(w, "</div>"); } } write!( w, "<script type=\"text/javascript\" \ src=\"{root_path}/implementors/{path}/{ty}.{name}.js\" async>\ </script>", root_path = vec![".."; cx.current.len()].join("/"), path = if it.def_id.is_local() { cx.current.join("/") } else { let (ref path, _) = cx.cache.external_paths[&it.def_id]; path[..path.len() - 1].join("/") }, ty = it.type_(), name = *it.name.as_ref().unwrap() ); } fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>, cache: &Cache) -> String { use crate::formats::item_type::ItemType::*; let name = it.name.as_ref().unwrap(); let ty = match it.type_() { Typedef | AssocType => AssocType, s => s, }; let anchor = format!("#{}.{}", ty, name); match link { AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id), AssocItemLink::Anchor(None) => anchor, AssocItemLink::GotoSource(did, _) => { href(did, cache).map(|p| format!("{}{}", p.0, anchor)).unwrap_or(anchor) } } } fn assoc_const( w: &mut Buffer, it: &clean::Item, ty: &clean::Type, _default: Option<&String>, link: AssocItemLink<'_>, extra: &str, cx: &Context<'_>, ) { write!( w, "{}{}const <a href=\"{}\" class=\"constant\"><b>{}</b></a>: {}", extra, it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()), naive_assoc_href(it, link, cx.cache()), it.name.as_ref().unwrap(), ty.print(cx.cache()) ); } fn assoc_type( w: &mut Buffer, it: &clean::Item, bounds: &[clean::GenericBound], default: Option<&clean::Type>, link: AssocItemLink<'_>, extra: &str, cache: &Cache, ) { write!( w, "{}type <a href=\"{}\" class=\"type\">{}</a>", extra, naive_assoc_href(it, link, cache), it.name.as_ref().unwrap() ); if !bounds.is_empty() { write!(w, ": {}", print_generic_bounds(bounds, cache)) } if let Some(default) = default { write!(w, " = {}", default.print(cache)) } } fn render_stability_since_raw( w: &mut Buffer, ver: Option<&str>, const_ver: Option<&str>, containing_ver: Option<&str>, containing_const_ver: Option<&str>, ) { let ver = ver.filter(|inner| !inner.is_empty()); let const_ver = const_ver.filter(|inner| !inner.is_empty()); match (ver, const_ver) { (Some(v), Some(cv)) if const_ver != containing_const_ver => { write!( w, "<span class=\"since\" title=\"Stable since Rust version {0}, const since {1}\">{0} (const: {1})</span>", v, cv ); } (Some(v), _) if ver != containing_ver => { write!( w, "<span class=\"since\" title=\"Stable since Rust version {0}\">{0}</span>", v ); } _ => {} } } fn render_stability_since( w: &mut Buffer, item: &clean::Item, containing_item: &clean::Item, tcx: TyCtxt<'_>, ) { render_stability_since_raw( w, item.stable_since(tcx).as_deref(), item.const_stable_since(tcx).as_deref(), containing_item.stable_since(tcx).as_deref(), containing_item.const_stable_since(tcx).as_deref(), ) } fn render_assoc_item( w: &mut Buffer, item: &clean::Item, link: AssocItemLink<'_>, parent: ItemType, cx: &Context<'_>, ) { fn method( w: &mut Buffer, meth: &clean::Item, header: hir::FnHeader, g: &clean::Generics, d: &clean::FnDecl, link: AssocItemLink<'_>, parent: ItemType, cx: &Context<'_>, ) { let name = meth.name.as_ref().unwrap(); let anchor = format!("#{}.{}", meth.type_(), name); let href = match link { AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id), AssocItemLink::Anchor(None) => anchor, AssocItemLink::GotoSource(did, provided_methods) => { // We're creating a link from an impl-item to the corresponding // trait-item and need to map the anchored type accordingly. let ty = if provided_methods.contains(&name) { ItemType::Method } else { ItemType::TyMethod }; href(did, cx.cache()).map(|p| format!("{}#{}.{}", p.0, ty, name)).unwrap_or(anchor) } }; let mut header_len = format!( "{}{}{}{}{}{:#}fn {}{:#}", meth.visibility.print_with_space(cx.tcx(), meth.def_id, cx.cache()), header.constness.print_with_space(), header.asyncness.print_with_space(), header.unsafety.print_with_space(), print_default_space(meth.is_default()), print_abi_with_space(header.abi), name, g.print(cx.cache()) ) .len(); let (indent, end_newline) = if parent == ItemType::Trait { header_len += 4; (4, false) } else { (0, true) }; render_attributes(w, meth, false); write!( w, "{}{}{}{}{}{}{}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\ {generics}{decl}{spotlight}{where_clause}", if parent == ItemType::Trait { " " } else { "" }, meth.visibility.print_with_space(cx.tcx(), meth.def_id, cx.cache()), header.constness.print_with_space(), header.asyncness.print_with_space(), header.unsafety.print_with_space(), print_default_space(meth.is_default()), print_abi_with_space(header.abi), href = href, name = name, generics = g.print(cx.cache()), decl = Function { decl: d, header_len, indent, asyncness: header.asyncness } .print(cx.cache()), spotlight = spotlight_decl(&d, cx.cache()), where_clause = WhereClause { gens: g, indent, end_newline }.print(cx.cache()) ) } match *item.kind { clean::StrippedItem(..) => {} clean::TyMethodItem(ref m) => { method(w, item, m.header, &m.generics, &m.decl, link, parent, cx) } clean::MethodItem(ref m, _) => { method(w, item, m.header, &m.generics, &m.decl, link, parent, cx) } clean::AssocConstItem(ref ty, ref default) => assoc_const( w, item, ty, default.as_ref(), link, if parent == ItemType::Trait { " " } else { "" }, cx, ), clean::AssocTypeItem(ref bounds, ref default) => assoc_type( w, item, bounds, default.as_ref(), link, if parent == ItemType::Trait { " " } else { "" }, cx.cache(), ), _ => panic!("render_assoc_item called on non-associated-item"), } } fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Struct) { wrap_into_docblock(w, |w| { w.write_str("<pre class=\"rust struct\">"); render_attributes(w, it, true); render_struct(w, it, Some(&s.generics), s.struct_type, &s.fields, "", true, cx); w.write_str("</pre>") }); document(w, cx, it, None); let mut fields = s .fields .iter() .filter_map(|f| match *f.kind { clean::StructFieldItem(ref ty) => Some((f, ty)), _ => None, }) .peekable(); if let CtorKind::Fictive = s.struct_type { if fields.peek().is_some() { write!( w, "<h2 id=\"fields\" class=\"fields small-section-header\"> Fields{}<a href=\"#fields\" class=\"anchor\"></a></h2>", document_non_exhaustive_header(it) ); document_non_exhaustive(w, it); for (field, ty) in fields { let id = cx.derive_id(format!( "{}.{}", ItemType::StructField, field.name.as_ref().unwrap() )); write!( w, "<span id=\"{id}\" class=\"{item_type} small-section-header\">\ <a href=\"#{id}\" class=\"anchor field\"></a>\ <code>{name}: {ty}</code>\ </span>", item_type = ItemType::StructField, id = id, name = field.name.as_ref().unwrap(), ty = ty.print(cx.cache()) ); document(w, cx, field, Some(it)); } } } render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All) } fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Union) { wrap_into_docblock(w, |w| { w.write_str("<pre class=\"rust union\">"); render_attributes(w, it, true); render_union(w, it, Some(&s.generics), &s.fields, "", true, cx); w.write_str("</pre>") }); document(w, cx, it, None); let mut fields = s .fields .iter() .filter_map(|f| match *f.kind { clean::StructFieldItem(ref ty) => Some((f, ty)), _ => None, }) .peekable(); if fields.peek().is_some() { write!( w, "<h2 id=\"fields\" class=\"fields small-section-header\"> Fields<a href=\"#fields\" class=\"anchor\"></a></h2>" ); for (field, ty) in fields { let name = field.name.as_ref().expect("union field name"); let id = format!("{}.{}", ItemType::StructField, name); write!( w, "<span id=\"{id}\" class=\"{shortty} small-section-header\">\ <a href=\"#{id}\" class=\"anchor field\"></a>\ <code>{name}: {ty}</code>\ </span>", id = id, name = name, shortty = ItemType::StructField, ty = ty.print(cx.cache()) ); if let Some(stability_class) = field.stability_class(cx.tcx()) { write!(w, "<span class=\"stab {stab}\"></span>", stab = stability_class); } document(w, cx, field, Some(it)); } } render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All) } fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum) { wrap_into_docblock(w, |w| { w.write_str("<pre class=\"rust enum\">"); render_attributes(w, it, true); write!( w, "{}enum {}{}{}", it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()), it.name.as_ref().unwrap(), e.generics.print(cx.cache()), WhereClause { gens: &e.generics, indent: 0, end_newline: true }.print(cx.cache()) ); if e.variants.is_empty() && !e.variants_stripped { w.write_str(" {}"); } else { w.write_str(" {\n"); for v in &e.variants { w.write_str(" "); let name = v.name.as_ref().unwrap(); match *v.kind { clean::VariantItem(ref var) => match var { clean::Variant::CLike => write!(w, "{}", name), clean::Variant::Tuple(ref tys) => { write!(w, "{}(", name); for (i, ty) in tys.iter().enumerate() { if i > 0 { w.write_str(",&nbsp;") } write!(w, "{}", ty.print(cx.cache())); } w.write_str(")"); } clean::Variant::Struct(ref s) => { render_struct(w, v, None, s.struct_type, &s.fields, " ", false, cx); } }, _ => unreachable!(), } w.write_str(",\n"); } if e.variants_stripped { w.write_str(" // some variants omitted\n"); } w.write_str("}"); } w.write_str("</pre>") }); document(w, cx, it, None); if !e.variants.is_empty() { write!( w, "<h2 id=\"variants\" class=\"variants small-section-header\"> Variants{}<a href=\"#variants\" class=\"anchor\"></a></h2>\n", document_non_exhaustive_header(it) ); document_non_exhaustive(w, it); for variant in &e.variants { let id = cx.derive_id(format!("{}.{}", ItemType::Variant, variant.name.as_ref().unwrap())); write!( w, "<div id=\"{id}\" class=\"variant small-section-header\">\ <a href=\"#{id}\" class=\"anchor field\"></a>\ <code>{name}", id = id, name = variant.name.as_ref().unwrap() ); if let clean::VariantItem(clean::Variant::Tuple(ref tys)) = *variant.kind { w.write_str("("); for (i, ty) in tys.iter().enumerate() { if i > 0 { w.write_str(",&nbsp;"); } write!(w, "{}", ty.print(cx.cache())); } w.write_str(")"); } w.write_str("</code></div>"); document(w, cx, variant, Some(it)); document_non_exhaustive(w, variant); use crate::clean::Variant; if let clean::VariantItem(Variant::Struct(ref s)) = *variant.kind { let variant_id = cx.derive_id(format!( "{}.{}.fields", ItemType::Variant, variant.name.as_ref().unwrap() )); write!(w, "<div class=\"autohide sub-variant\" id=\"{id}\">", id = variant_id); write!( w, "<h3>Fields of <b>{name}</b></h3><div>", name = variant.name.as_ref().unwrap() ); for field in &s.fields { use crate::clean::StructFieldItem; if let StructFieldItem(ref ty) = *field.kind { let id = cx.derive_id(format!( "variant.{}.field.{}", variant.name.as_ref().unwrap(), field.name.as_ref().unwrap() )); write!( w, "<span id=\"{id}\" class=\"variant small-section-header\">\ <a href=\"#{id}\" class=\"anchor field\"></a>\ <code>{f}:&nbsp;{t}</code>\ </span>", id = id, f = field.name.as_ref().unwrap(), t = ty.print(cx.cache()) ); document(w, cx, field, Some(variant)); } } w.write_str("</div></div>"); } render_stability_since(w, variant, it, cx.tcx()); } } render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All) } const ALLOWED_ATTRIBUTES: &[Symbol] = &[ sym::export_name, sym::lang, sym::link_section, sym::must_use, sym::no_mangle, sym::repr, sym::non_exhaustive, ]; // The `top` parameter is used when generating the item declaration to ensure it doesn't have a // left padding. For example: // // #[foo] <----- "top" attribute // struct Foo { // #[bar] <---- not "top" attribute // bar: usize, // } fn render_attributes(w: &mut Buffer, it: &clean::Item, top: bool) { let attrs = it .attrs .other_attrs .iter() .filter_map(|attr| { if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) { Some(pprust::attribute_to_string(&attr)) } else { None } }) .join("\n"); if !attrs.is_empty() { write!( w, "<span class=\"docblock attributes{}\">{}</span>", if top { " top-attr" } else { "" }, &attrs ); } } fn render_struct( w: &mut Buffer, it: &clean::Item, g: Option<&clean::Generics>, ty: CtorKind, fields: &[clean::Item], tab: &str, structhead: bool, cx: &Context<'_>, ) { write!( w, "{}{}{}", it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()), if structhead { "struct " } else { "" }, it.name.as_ref().unwrap() ); if let Some(g) = g { write!(w, "{}", g.print(cx.cache())) } match ty { CtorKind::Fictive => { if let Some(g) = g { write!( w, "{}", WhereClause { gens: g, indent: 0, end_newline: true }.print(cx.cache()) ) } let mut has_visible_fields = false; w.write_str(" {"); for field in fields { if let clean::StructFieldItem(ref ty) = *field.kind { write!( w, "\n{} {}{}: {},", tab, field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()), field.name.as_ref().unwrap(), ty.print(cx.cache()) ); has_visible_fields = true; } } if has_visible_fields { if it.has_stripped_fields().unwrap() { write!(w, "\n{} // some fields omitted", tab); } write!(w, "\n{}", tab); } else if it.has_stripped_fields().unwrap() { // If there are no visible fields we can just display // `{ /* fields omitted */ }` to save space. write!(w, " /* fields omitted */ "); } w.write_str("}"); } CtorKind::Fn => { w.write_str("("); for (i, field) in fields.iter().enumerate() { if i > 0 { w.write_str(", "); } match *field.kind { clean::StrippedItem(box clean::StructFieldItem(..)) => write!(w, "_"), clean::StructFieldItem(ref ty) => { write!( w, "{}{}", field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()), ty.print(cx.cache()) ) } _ => unreachable!(), } } w.write_str(")"); if let Some(g) = g { write!( w, "{}", WhereClause { gens: g, indent: 0, end_newline: false }.print(cx.cache()) ) } w.write_str(";"); } CtorKind::Const => { // Needed for PhantomData. if let Some(g) = g { write!( w, "{}", WhereClause { gens: g, indent: 0, end_newline: false }.print(cx.cache()) ) } w.write_str(";"); } } } fn render_union( w: &mut Buffer, it: &clean::Item, g: Option<&clean::Generics>, fields: &[clean::Item], tab: &str, structhead: bool, cx: &Context<'_>, ) { write!( w, "{}{}{}", it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()), if structhead { "union " } else { "" }, it.name.as_ref().unwrap() ); if let Some(g) = g { write!(w, "{}", g.print(cx.cache())); write!(w, "{}", WhereClause { gens: g, indent: 0, end_newline: true }.print(cx.cache())); } write!(w, " {{\n{}", tab); for field in fields { if let clean::StructFieldItem(ref ty) = *field.kind { write!( w, " {}{}: {},\n{}", field.visibility.print_with_space(cx.tcx(), field.def_id, cx.cache()), field.name.as_ref().unwrap(), ty.print(cx.cache()), tab ); } } if it.has_stripped_fields().unwrap() { write!(w, " // some fields omitted\n{}", tab); } w.write_str("}"); } #[derive(Copy, Clone)] enum AssocItemLink<'a> { Anchor(Option<&'a str>), GotoSource(DefId, &'a FxHashSet<Symbol>), } impl<'a> AssocItemLink<'a> { fn anchor(&self, id: &'a str) -> Self { match *self { AssocItemLink::Anchor(_) => AssocItemLink::Anchor(Some(&id)), ref other => *other, } } } fn render_assoc_items( w: &mut Buffer, cx: &Context<'_>, containing_item: &clean::Item, it: DefId, what: AssocItemRender<'_>, ) { info!("Documenting associated items of {:?}", containing_item.name); let v = match cx.cache.impls.get(&it) { Some(v) => v, None => return, }; let (non_trait, traits): (Vec<_>, _) = v.iter().partition(|i| i.inner_impl().trait_.is_none()); if !non_trait.is_empty() { let render_mode = match what { AssocItemRender::All => { w.write_str( "<h2 id=\"implementations\" class=\"small-section-header\">\ Implementations<a href=\"#implementations\" class=\"anchor\"></a>\ </h2>", ); RenderMode::Normal } AssocItemRender::DerefFor { trait_, type_, deref_mut_ } => { let id = cx.derive_id(small_url_encode(format!( "deref-methods-{:#}", type_.print(cx.cache()) ))); debug!("Adding {} to deref id map", type_.print(cx.cache())); cx.deref_id_map .borrow_mut() .insert(type_.def_id_full(cx.cache()).unwrap(), id.clone()); write!( w, "<h2 id=\"{id}\" class=\"small-section-header\">\ Methods from {trait_}&lt;Target = {type_}&gt;\ <a href=\"#{id}\" class=\"anchor\"></a>\ </h2>", id = id, trait_ = trait_.print(cx.cache()), type_ = type_.print(cx.cache()), ); RenderMode::ForDeref { mut_: deref_mut_ } } }; for i in &non_trait { render_impl( w, cx, i, containing_item, AssocItemLink::Anchor(None), render_mode, containing_item.stable_since(cx.tcx()).as_deref(), containing_item.const_stable_since(cx.tcx()).as_deref(), true, None, false, true, &[], ); } } if !traits.is_empty() { let deref_impl = traits .iter() .find(|t| t.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_trait_did); if let Some(impl_) = deref_impl { let has_deref_mut = traits.iter().any(|t| { t.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_mut_trait_did }); render_deref_methods(w, cx, impl_, containing_item, has_deref_mut); } // If we were already one level into rendering deref methods, we don't want to render // anything after recursing into any further deref methods above. if let AssocItemRender::DerefFor { .. } = what { return; } let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) = traits.iter().partition(|t| t.inner_impl().synthetic); let (blanket_impl, concrete): (Vec<&&Impl>, _) = concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some()); let mut impls = Buffer::empty_from(&w); render_impls(cx, &mut impls, &concrete, containing_item); let impls = impls.into_inner(); if !impls.is_empty() { write!( w, "<h2 id=\"trait-implementations\" class=\"small-section-header\">\ Trait Implementations<a href=\"#trait-implementations\" class=\"anchor\"></a>\ </h2>\ <div id=\"trait-implementations-list\">{}</div>", impls ); } if !synthetic.is_empty() { w.write_str( "<h2 id=\"synthetic-implementations\" class=\"small-section-header\">\ Auto Trait Implementations\ <a href=\"#synthetic-implementations\" class=\"anchor\"></a>\ </h2>\ <div id=\"synthetic-implementations-list\">", ); render_impls(cx, w, &synthetic, containing_item); w.write_str("</div>"); } if !blanket_impl.is_empty() { w.write_str( "<h2 id=\"blanket-implementations\" class=\"small-section-header\">\ Blanket Implementations\ <a href=\"#blanket-implementations\" class=\"anchor\"></a>\ </h2>\ <div id=\"blanket-implementations-list\">", ); render_impls(cx, w, &blanket_impl, containing_item); w.write_str("</div>"); } } } fn render_deref_methods( w: &mut Buffer, cx: &Context<'_>, impl_: &Impl, container_item: &clean::Item, deref_mut: bool, ) { let deref_type = impl_.inner_impl().trait_.as_ref().unwrap(); let (target, real_target) = impl_ .inner_impl() .items .iter() .find_map(|item| match *item.kind { clean::TypedefItem(ref t, true) => Some(match *t { clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_), _ => (&t.type_, &t.type_), }), _ => None, }) .expect("Expected associated type binding"); debug!("Render deref methods for {:#?}, target {:#?}", impl_.inner_impl().for_, target); let what = AssocItemRender::DerefFor { trait_: deref_type, type_: real_target, deref_mut_: deref_mut }; if let Some(did) = target.def_id_full(cx.cache()) { if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) { // `impl Deref<Target = S> for S` if did == type_did { // Avoid infinite cycles return; } } render_assoc_items(w, cx, container_item, did, what); } else { if let Some(prim) = target.primitive_type() { if let Some(&did) = cx.cache.primitive_locations.get(&prim) { render_assoc_items(w, cx, container_item, did, what); } } } } fn should_render_item(item: &clean::Item, deref_mut_: bool, cache: &Cache) -> bool { let self_type_opt = match *item.kind { clean::MethodItem(ref method, _) => method.decl.self_type(), clean::TyMethodItem(ref method) => method.decl.self_type(), _ => None, }; if let Some(self_ty) = self_type_opt { let (by_mut_ref, by_box, by_value) = match self_ty { SelfTy::SelfBorrowed(_, mutability) | SelfTy::SelfExplicit(clean::BorrowedRef { mutability, .. }) => { (mutability == Mutability::Mut, false, false) } SelfTy::SelfExplicit(clean::ResolvedPath { did, .. }) => { (false, Some(did) == cache.owned_box_did, false) } SelfTy::SelfValue => (false, false, true), _ => (false, false, false), }; (deref_mut_ || !by_mut_ref) && !by_box && !by_value } else { false } } fn spotlight_decl(decl: &clean::FnDecl, cache: &Cache) -> String { let mut out = Buffer::html(); let mut trait_ = String::new(); if let Some(did) = decl.output.def_id_full(cache) { if let Some(impls) = cache.impls.get(&did) { for i in impls { let impl_ = i.inner_impl(); if impl_.trait_.def_id_full(cache).map_or(false, |d| cache.traits[&d].is_spotlight) { if out.is_empty() { write!( &mut out, "<h3 class=\"notable\">Notable traits for {}</h3>\ <code class=\"content\">", impl_.for_.print(cache) ); trait_.push_str(&impl_.for_.print(cache).to_string()); } //use the "where" class here to make it small write!( &mut out, "<span class=\"where fmt-newline\">{}</span>", impl_.print(cache, false) ); let t_did = impl_.trait_.def_id_full(cache).unwrap(); for it in &impl_.items { if let clean::TypedefItem(ref tydef, _) = *it.kind { out.push_str("<span class=\"where fmt-newline\"> "); assoc_type( &mut out, it, &[], Some(&tydef.type_), AssocItemLink::GotoSource(t_did, &FxHashSet::default()), "", cache, ); out.push_str(";</span>"); } } } } } } if !out.is_empty() { out.insert_str( 0, "<span class=\"notable-traits\"><span class=\"notable-traits-tooltip\">ⓘ\ <div class=\"notable-traits-tooltiptext\"><span class=\"docblock\">", ); out.push_str("</code></span></div></span></span>"); } out.into_inner() } fn render_impl( w: &mut Buffer, cx: &Context<'_>, i: &Impl, parent: &clean::Item, link: AssocItemLink<'_>, render_mode: RenderMode, outer_version: Option<&str>, outer_const_version: Option<&str>, show_def_docs: bool, use_absolute: Option<bool>, is_on_foreign_type: bool, show_default_items: bool, // This argument is used to reference same type with different paths to avoid duplication // in documentation pages for trait with automatic implementations like "Send" and "Sync". aliases: &[String], ) { let traits = &cx.cache.traits; let trait_ = i.trait_did_full(cx.cache()).map(|did| &traits[&did]); if render_mode == RenderMode::Normal { let id = cx.derive_id(match i.inner_impl().trait_ { Some(ref t) => { if is_on_foreign_type { get_id_for_impl_on_foreign_type(&i.inner_impl().for_, t, cx.cache()) } else { format!("impl-{}", small_url_encode(format!("{:#}", t.print(cx.cache())))) } } None => "impl".to_string(), }); let aliases = if aliases.is_empty() { String::new() } else { format!(" aliases=\"{}\"", aliases.join(",")) }; if let Some(use_absolute) = use_absolute { write!(w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">", id, aliases); write!(w, "{}", i.inner_impl().print(cx.cache(), use_absolute)); if show_def_docs { for it in &i.inner_impl().items { if let clean::TypedefItem(ref tydef, _) = *it.kind { w.write_str("<span class=\"where fmt-newline\"> "); assoc_type( w, it, &[], Some(&tydef.type_), AssocItemLink::Anchor(None), "", cx.cache(), ); w.write_str(";</span>"); } } } w.write_str("</code>"); } else { write!( w, "<h3 id=\"{}\" class=\"impl\"{}><code class=\"in-band\">{}</code>", id, aliases, i.inner_impl().print(cx.cache(), false) ); } write!(w, "<a href=\"#{}\" class=\"anchor\"></a>", id); render_stability_since_raw( w, i.impl_item.stable_since(cx.tcx()).as_deref(), i.impl_item.const_stable_since(cx.tcx()).as_deref(), outer_version, outer_const_version, ); write_srclink(cx, &i.impl_item, w); w.write_str("</h3>"); if trait_.is_some() { if let Some(portability) = portability(&i.impl_item, Some(parent)) { write!(w, "<div class=\"item-info\">{}</div>", portability); } } if let Some(ref dox) = cx.shared.maybe_collapsed_doc_value(&i.impl_item) { let mut ids = cx.id_map.borrow_mut(); write!( w, "<div class=\"docblock\">{}</div>", Markdown( &*dox, &i.impl_item.links(&cx.cache), &mut ids, cx.shared.codes, cx.shared.edition, &cx.shared.playground ) .into_string() ); } } fn doc_impl_item( w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, parent: &clean::Item, link: AssocItemLink<'_>, render_mode: RenderMode, is_default_item: bool, outer_version: Option<&str>, outer_const_version: Option<&str>, trait_: Option<&clean::Trait>, show_def_docs: bool, ) { let item_type = item.type_(); let name = item.name.as_ref().unwrap(); let render_method_item = match render_mode { RenderMode::Normal => true, RenderMode::ForDeref { mut_: deref_mut_ } => { should_render_item(&item, deref_mut_, &cx.cache) } }; let (is_hidden, extra_class) = if (trait_.is_none() || item.doc_value().is_some() || item.kind.is_type_alias()) && !is_default_item { (false, "") } else { (true, " hidden") }; match *item.kind { clean::MethodItem(..) | clean::TyMethodItem(_) => { // Only render when the method is not static or we allow static methods if render_method_item { let id = cx.derive_id(format!("{}.{}", item_type, name)); write!(w, "<h4 id=\"{}\" class=\"{}{}\">", id, item_type, extra_class); w.write_str("<code>"); render_assoc_item(w, item, link.anchor(&id), ItemType::Impl, cx); w.write_str("</code>"); render_stability_since_raw( w, item.stable_since(cx.tcx()).as_deref(), item.const_stable_since(cx.tcx()).as_deref(), outer_version, outer_const_version, ); write_srclink(cx, item, w); w.write_str("</h4>"); } } clean::TypedefItem(ref tydef, _) => { let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name)); write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class); assoc_type( w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "", cx.cache(), ); w.write_str("</code></h4>"); } clean::AssocConstItem(ref ty, ref default) => { let id = cx.derive_id(format!("{}.{}", item_type, name)); write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class); assoc_const(w, item, ty, default.as_ref(), link.anchor(&id), "", cx); w.write_str("</code>"); render_stability_since_raw( w, item.stable_since(cx.tcx()).as_deref(), item.const_stable_since(cx.tcx()).as_deref(), outer_version, outer_const_version, ); write_srclink(cx, item, w); w.write_str("</h4>"); } clean::AssocTypeItem(ref bounds, ref default) => { let id = cx.derive_id(format!("{}.{}", item_type, name)); write!(w, "<h4 id=\"{}\" class=\"{}{}\"><code>", id, item_type, extra_class); assoc_type(w, item, bounds, default.as_ref(), link.anchor(&id), "", cx.cache()); w.write_str("</code></h4>"); } clean::StrippedItem(..) => return, _ => panic!("can't make docs for trait item with name {:?}", item.name), } if render_method_item { if !is_default_item { if let Some(t) = trait_ { // The trait item may have been stripped so we might not // find any documentation or stability for it. if let Some(it) = t.items.iter().find(|i| i.name == item.name) { // We need the stability of the item from the trait // because impls can't have a stability. if item.doc_value().is_some() { document_item_info(w, cx, it, is_hidden, Some(parent)); document_full(w, item, cx, "", is_hidden); } else { // In case the item isn't documented, // provide short documentation from the trait. document_short( w, it, cx, link, "", is_hidden, Some(parent), show_def_docs, ); } } } else { document_item_info(w, cx, item, is_hidden, Some(parent)); if show_def_docs { document_full(w, item, cx, "", is_hidden); } } } else { document_short(w, item, cx, link, "", is_hidden, Some(parent), show_def_docs); } } } w.write_str("<div class=\"impl-items\">"); for trait_item in &i.inner_impl().items { doc_impl_item( w, cx, trait_item, if trait_.is_some() { &i.impl_item } else { parent }, link, render_mode, false, outer_version, outer_const_version, trait_, show_def_docs, ); } fn render_default_items( w: &mut Buffer, cx: &Context<'_>, t: &clean::Trait, i: &clean::Impl, parent: &clean::Item, render_mode: RenderMode, outer_version: Option<&str>, outer_const_version: Option<&str>, show_def_docs: bool, ) { for trait_item in &t.items { let n = trait_item.name; if i.items.iter().any(|m| m.name == n) { continue; } let did = i.trait_.as_ref().unwrap().def_id_full(cx.cache()).unwrap(); let assoc_link = AssocItemLink::GotoSource(did, &i.provided_trait_methods); doc_impl_item( w, cx, trait_item, parent, assoc_link, render_mode, true, outer_version, outer_const_version, None, show_def_docs, ); } } // If we've implemented a trait, then also emit documentation for all // default items which weren't overridden in the implementation block. // We don't emit documentation for default items if they appear in the // Implementations on Foreign Types or Implementors sections. if show_default_items { if let Some(t) = trait_ { render_default_items( w, cx, t, &i.inner_impl(), &i.impl_item, render_mode, outer_version, outer_const_version, show_def_docs, ); } } w.write_str("</div>"); } fn item_opaque_ty(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::OpaqueTy) { w.write_str("<pre class=\"rust opaque\">"); render_attributes(w, it, false); write!( w, "type {}{}{where_clause} = impl {bounds};</pre>", it.name.as_ref().unwrap(), t.generics.print(cx.cache()), where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()), bounds = bounds(&t.bounds, false, cx.cache()) ); document(w, cx, it, None); // Render any items associated directly to this alias, as otherwise they // won't be visible anywhere in the docs. It would be nice to also show // associated items from the aliased type (see discussion in #32077), but // we need #14072 to make sense of the generics. render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All) } fn item_trait_alias(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::TraitAlias) { w.write_str("<pre class=\"rust trait-alias\">"); render_attributes(w, it, false); write!( w, "trait {}{}{} = {};</pre>", it.name.as_ref().unwrap(), t.generics.print(cx.cache()), WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()), bounds(&t.bounds, true, cx.cache()) ); document(w, cx, it, None); // Render any items associated directly to this alias, as otherwise they // won't be visible anywhere in the docs. It would be nice to also show // associated items from the aliased type (see discussion in #32077), but // we need #14072 to make sense of the generics. render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All) } fn item_typedef(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Typedef) { w.write_str("<pre class=\"rust typedef\">"); render_attributes(w, it, false); write!( w, "type {}{}{where_clause} = {type_};</pre>", it.name.as_ref().unwrap(), t.generics.print(cx.cache()), where_clause = WhereClause { gens: &t.generics, indent: 0, end_newline: true }.print(cx.cache()), type_ = t.type_.print(cx.cache()) ); document(w, cx, it, None); // Render any items associated directly to this alias, as otherwise they // won't be visible anywhere in the docs. It would be nice to also show // associated items from the aliased type (see discussion in #32077), but // we need #14072 to make sense of the generics. render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All) } fn item_foreign_type(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) { w.write_str("<pre class=\"rust foreigntype\">extern {\n"); render_attributes(w, it, false); write!( w, " {}type {};\n}}</pre>", it.visibility.print_with_space(cx.tcx(), it.def_id, cx.cache()), it.name.as_ref().unwrap(), ); document(w, cx, it, None); render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All) } fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) { let parentlen = cx.current.len() - if it.is_mod() { 1 } else { 0 }; if it.is_struct() || it.is_trait() || it.is_primitive() || it.is_union() || it.is_enum() || it.is_mod() || it.is_typedef() { write!( buffer, "<p class=\"location\">{}{}</p>", match *it.kind { clean::StructItem(..) => "Struct ", clean::TraitItem(..) => "Trait ", clean::PrimitiveItem(..) => "Primitive Type ", clean::UnionItem(..) => "Union ", clean::EnumItem(..) => "Enum ", clean::TypedefItem(..) => "Type Definition ", clean::ForeignTypeItem => "Foreign Type ", clean::ModuleItem(..) => if it.is_crate() { "Crate " } else { "Module " }, _ => "", }, it.name.as_ref().unwrap() ); } if it.is_crate() { if let Some(ref version) = cx.cache.crate_version { write!( buffer, "<div class=\"block version\">\ <p>Version {}</p>\ </div>", Escape(version) ); } } buffer.write_str("<div class=\"sidebar-elems\">"); if it.is_crate() { write!( buffer, "<a id=\"all-types\" href=\"all.html\"><p>See all {}'s items</p></a>", it.name.as_ref().expect("crates always have a name") ); } match *it.kind { clean::StructItem(ref s) => sidebar_struct(cx, buffer, it, s), clean::TraitItem(ref t) => sidebar_trait(cx, buffer, it, t), clean::PrimitiveItem(_) => sidebar_primitive(cx, buffer, it), clean::UnionItem(ref u) => sidebar_union(cx, buffer, it, u), clean::EnumItem(ref e) => sidebar_enum(cx, buffer, it, e), clean::TypedefItem(_, _) => sidebar_typedef(cx, buffer, it), clean::ModuleItem(ref m) => sidebar_module(buffer, &m.items), clean::ForeignTypeItem => sidebar_foreign_type(cx, buffer, it), _ => (), } // The sidebar is designed to display sibling functions, modules and // other miscellaneous information. since there are lots of sibling // items (and that causes quadratic growth in large modules), // we refactor common parts into a shared JavaScript file per module. // still, we don't move everything into JS because we want to preserve // as much HTML as possible in order to allow non-JS-enabled browsers // to navigate the documentation (though slightly inefficiently). buffer.write_str("<p class=\"location\">"); for (i, name) in cx.current.iter().take(parentlen).enumerate() { if i > 0 { buffer.write_str("::<wbr>"); } write!( buffer, "<a href=\"{}index.html\">{}</a>", &cx.root_path()[..(cx.current.len() - i - 1) * 3], *name ); } buffer.write_str("</p>"); // Sidebar refers to the enclosing module, not this module. let relpath = if it.is_mod() { "../" } else { "" }; write!( buffer, "<div id=\"sidebar-vars\" data-name=\"{name}\" data-ty=\"{ty}\" data-relpath=\"{path}\">\ </div>", name = it.name.unwrap_or(kw::Empty), ty = it.type_(), path = relpath ); if parentlen == 0 { // There is no sidebar-items.js beyond the crate root path // FIXME maybe dynamic crate loading can be merged here } else { write!(buffer, "<script defer src=\"{path}sidebar-items.js\"></script>", path = relpath); } // Closes sidebar-elems div. buffer.write_str("</div>"); } fn get_next_url(used_links: &mut FxHashSet<String>, url: String) -> String { if used_links.insert(url.clone()) { return url; } let mut add = 1; while !used_links.insert(format!("{}-{}", url, add)) { add += 1; } format!("{}-{}", url, add) } fn get_methods( i: &clean::Impl, for_deref: bool, used_links: &mut FxHashSet<String>, deref_mut: bool, cache: &Cache, ) -> Vec<String> { i.items .iter() .filter_map(|item| match item.name { Some(ref name) if !name.is_empty() && item.is_method() => { if !for_deref || should_render_item(item, deref_mut, cache) { Some(format!( "<a href=\"#{}\">{}</a>", get_next_url(used_links, format!("method.{}", name)), name )) } else { None } } _ => None, }) .collect::<Vec<_>>() } // The point is to url encode any potential character from a type with genericity. fn small_url_encode(s: String) -> String { let mut st = String::new(); let mut last_match = 0; for (idx, c) in s.char_indices() { let escaped = match c { '<' => "%3C", '>' => "%3E", ' ' => "%20", '?' => "%3F", '\'' => "%27", '&' => "%26", ',' => "%2C", ':' => "%3A", ';' => "%3B", '[' => "%5B", ']' => "%5D", '"' => "%22", _ => continue, }; st += &s[last_match..idx]; st += escaped; // NOTE: we only expect single byte characters here - which is fine as long as we // only match single byte characters last_match = idx + 1; } if last_match != 0 { st += &s[last_match..]; st } else { s } } fn sidebar_assoc_items(cx: &Context<'_>, out: &mut Buffer, it: &clean::Item) { if let Some(v) = cx.cache.impls.get(&it.def_id) { let mut used_links = FxHashSet::default(); { let used_links_bor = &mut used_links; let mut ret = v .iter() .filter(|i| i.inner_impl().trait_.is_none()) .flat_map(move |i| { get_methods(i.inner_impl(), false, used_links_bor, false, &cx.cache) }) .collect::<Vec<_>>(); if !ret.is_empty() { // We want links' order to be reproducible so we don't use unstable sort. ret.sort(); out.push_str( "<a class=\"sidebar-title\" href=\"#implementations\">Methods</a>\ <div class=\"sidebar-links\">", ); for line in ret { out.push_str(&line); } out.push_str("</div>"); } } if v.iter().any(|i| i.inner_impl().trait_.is_some()) { if let Some(impl_) = v .iter() .filter(|i| i.inner_impl().trait_.is_some()) .find(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == cx.cache.deref_trait_did) { sidebar_deref_methods(cx, out, impl_, v); } let format_impls = |impls: Vec<&Impl>| { let mut links = FxHashSet::default(); let mut ret = impls .iter() .filter_map(|it| { if let Some(ref i) = it.inner_impl().trait_ { let i_display = format!("{:#}", i.print(cx.cache())); let out = Escape(&i_display); let encoded = small_url_encode(format!("{:#}", i.print(cx.cache()))); let generated = format!( "<a href=\"#impl-{}\">{}{}</a>", encoded, if it.inner_impl().negative_polarity { "!" } else { "" }, out ); if links.insert(generated.clone()) { Some(generated) } else { None } } else { None } }) .collect::<Vec<String>>(); ret.sort(); ret }; let write_sidebar_links = |out: &mut Buffer, links: Vec<String>| { out.push_str("<div class=\"sidebar-links\">"); for link in links { out.push_str(&link); } out.push_str("</div>"); }; let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) = v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic); let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete .into_iter() .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some()); let concrete_format = format_impls(concrete); let synthetic_format = format_impls(synthetic); let blanket_format = format_impls(blanket_impl); if !concrete_format.is_empty() { out.push_str( "<a class=\"sidebar-title\" href=\"#trait-implementations\">\ Trait Implementations</a>", ); write_sidebar_links(out, concrete_format); } if !synthetic_format.is_empty() { out.push_str( "<a class=\"sidebar-title\" href=\"#synthetic-implementations\">\ Auto Trait Implementations</a>", ); write_sidebar_links(out, synthetic_format); } if !blanket_format.is_empty() { out.push_str( "<a class=\"sidebar-title\" href=\"#blanket-implementations\">\ Blanket Implementations</a>", ); write_sidebar_links(out, blanket_format); } } } } fn sidebar_deref_methods(cx: &Context<'_>, out: &mut Buffer, impl_: &Impl, v: &Vec<Impl>) { let c = cx.cache(); debug!("found Deref: {:?}", impl_); if let Some((target, real_target)) = impl_.inner_impl().items.iter().find_map(|item| match *item.kind { clean::TypedefItem(ref t, true) => Some(match *t { clean::Typedef { item_type: Some(ref type_), .. } => (type_, &t.type_), _ => (&t.type_, &t.type_), }), _ => None, }) { debug!("found target, real_target: {:?} {:?}", target, real_target); if let Some(did) = target.def_id_full(cx.cache()) { if let Some(type_did) = impl_.inner_impl().for_.def_id_full(cx.cache()) { // `impl Deref<Target = S> for S` if did == type_did { // Avoid infinite cycles return; } } } let deref_mut = v .iter() .filter(|i| i.inner_impl().trait_.is_some()) .any(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_mut_trait_did); let inner_impl = target .def_id_full(cx.cache()) .or_else(|| { target.primitive_type().and_then(|prim| c.primitive_locations.get(&prim).cloned()) }) .and_then(|did| c.impls.get(&did)); if let Some(impls) = inner_impl { debug!("found inner_impl: {:?}", impls); let mut used_links = FxHashSet::default(); let mut ret = impls .iter() .filter(|i| i.inner_impl().trait_.is_none()) .flat_map(|i| get_methods(i.inner_impl(), true, &mut used_links, deref_mut, c)) .collect::<Vec<_>>(); if !ret.is_empty() { let deref_id_map = cx.deref_id_map.borrow(); let id = deref_id_map .get(&real_target.def_id_full(cx.cache()).unwrap()) .expect("Deref section without derived id"); write!( out, "<a class=\"sidebar-title\" href=\"#{}\">Methods from {}&lt;Target={}&gt;</a>", id, Escape(&format!("{:#}", impl_.inner_impl().trait_.as_ref().unwrap().print(c))), Escape(&format!("{:#}", real_target.print(c))), ); // We want links' order to be reproducible so we don't use unstable sort. ret.sort(); out.push_str("<div class=\"sidebar-links\">"); for link in ret { out.push_str(&link); } out.push_str("</div>"); } } // Recurse into any further impls that might exist for `target` if let Some(target_did) = target.def_id_full(cx.cache()) { if let Some(target_impls) = c.impls.get(&target_did) { if let Some(target_deref_impl) = target_impls .iter() .filter(|i| i.inner_impl().trait_.is_some()) .find(|i| i.inner_impl().trait_.def_id_full(cx.cache()) == c.deref_trait_did) { sidebar_deref_methods(cx, out, target_deref_impl, target_impls); } } } } } fn sidebar_struct(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, s: &clean::Struct) { let mut sidebar = Buffer::new(); let fields = get_struct_fields_name(&s.fields); if !fields.is_empty() { if let CtorKind::Fictive = s.struct_type { sidebar.push_str( "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\ <div class=\"sidebar-links\">", ); for field in fields { sidebar.push_str(&field); } sidebar.push_str("</div>"); } } sidebar_assoc_items(cx, &mut sidebar, it); if !sidebar.is_empty() { write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner()); } } fn get_id_for_impl_on_foreign_type( for_: &clean::Type, trait_: &clean::Type, cache: &Cache, ) -> String { small_url_encode(format!("impl-{:#}-for-{:#}", trait_.print(cache), for_.print(cache))) } fn extract_for_impl_name(item: &clean::Item, cache: &Cache) -> Option<(String, String)> { match *item.kind { clean::ItemKind::ImplItem(ref i) => { if let Some(ref trait_) = i.trait_ { Some(( format!("{:#}", i.for_.print(cache)), get_id_for_impl_on_foreign_type(&i.for_, trait_, cache), )) } else { None } } _ => None, } } fn sidebar_trait(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, t: &clean::Trait) { buf.write_str("<div class=\"block items\">"); fn print_sidebar_section( out: &mut Buffer, items: &[clean::Item], before: &str, filter: impl Fn(&clean::Item) -> bool, write: impl Fn(&mut Buffer, &Symbol), after: &str, ) { let mut items = items .iter() .filter_map(|m| match m.name { Some(ref name) if filter(m) => Some(name), _ => None, }) .collect::<Vec<_>>(); if !items.is_empty() { items.sort(); out.push_str(before); for item in items.into_iter() { write(out, item); } out.push_str(after); } } print_sidebar_section( buf, &t.items, "<a class=\"sidebar-title\" href=\"#associated-types\">\ Associated Types</a><div class=\"sidebar-links\">", |m| m.is_associated_type(), |out, sym| write!(out, "<a href=\"#associatedtype.{0}\">{0}</a>", sym), "</div>", ); print_sidebar_section( buf, &t.items, "<a class=\"sidebar-title\" href=\"#associated-const\">\ Associated Constants</a><div class=\"sidebar-links\">", |m| m.is_associated_const(), |out, sym| write!(out, "<a href=\"#associatedconstant.{0}\">{0}</a>", sym), "</div>", ); print_sidebar_section( buf, &t.items, "<a class=\"sidebar-title\" href=\"#required-methods\">\ Required Methods</a><div class=\"sidebar-links\">", |m| m.is_ty_method(), |out, sym| write!(out, "<a href=\"#tymethod.{0}\">{0}</a>", sym), "</div>", ); print_sidebar_section( buf, &t.items, "<a class=\"sidebar-title\" href=\"#provided-methods\">\ Provided Methods</a><div class=\"sidebar-links\">", |m| m.is_method(), |out, sym| write!(out, "<a href=\"#method.{0}\">{0}</a>", sym), "</div>", ); if let Some(implementors) = cx.cache.implementors.get(&it.def_id) { let mut res = implementors .iter() .filter(|i| { i.inner_impl() .for_ .def_id_full(cx.cache()) .map_or(false, |d| !cx.cache.paths.contains_key(&d)) }) .filter_map(|i| extract_for_impl_name(&i.impl_item, cx.cache())) .collect::<Vec<_>>(); if !res.is_empty() { res.sort(); buf.push_str( "<a class=\"sidebar-title\" href=\"#foreign-impls\">\ Implementations on Foreign Types</a>\ <div class=\"sidebar-links\">", ); for (name, id) in res.into_iter() { write!(buf, "<a href=\"#{}\">{}</a>", id, Escape(&name)); } buf.push_str("</div>"); } } sidebar_assoc_items(cx, buf, it); buf.push_str("<a class=\"sidebar-title\" href=\"#implementors\">Implementors</a>"); if t.is_auto { buf.push_str( "<a class=\"sidebar-title\" \ href=\"#synthetic-implementors\">Auto Implementors</a>", ); } buf.push_str("</div>") } fn sidebar_primitive(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) { let mut sidebar = Buffer::new(); sidebar_assoc_items(cx, &mut sidebar, it); if !sidebar.is_empty() { write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner()); } } fn sidebar_typedef(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) { let mut sidebar = Buffer::new(); sidebar_assoc_items(cx, &mut sidebar, it); if !sidebar.is_empty() { write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner()); } } fn get_struct_fields_name(fields: &[clean::Item]) -> Vec<String> { let mut fields = fields .iter() .filter(|f| matches!(*f.kind, clean::StructFieldItem(..))) .filter_map(|f| { f.name.map(|name| format!("<a href=\"#structfield.{name}\">{name}</a>", name = name)) }) .collect::<Vec<_>>(); fields.sort(); fields } fn sidebar_union(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, u: &clean::Union) { let mut sidebar = Buffer::new(); let fields = get_struct_fields_name(&u.fields); if !fields.is_empty() { sidebar.push_str( "<a class=\"sidebar-title\" href=\"#fields\">Fields</a>\ <div class=\"sidebar-links\">", ); for field in fields { sidebar.push_str(&field); } sidebar.push_str("</div>"); } sidebar_assoc_items(cx, &mut sidebar, it); if !sidebar.is_empty() { write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner()); } } fn sidebar_enum(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item, e: &clean::Enum) { let mut sidebar = Buffer::new(); let mut variants = e .variants .iter() .filter_map(|v| match v.name { Some(ref name) => Some(format!("<a href=\"#variant.{name}\">{name}</a>", name = name)), _ => None, }) .collect::<Vec<_>>(); if !variants.is_empty() { variants.sort_unstable(); sidebar.push_str(&format!( "<a class=\"sidebar-title\" href=\"#variants\">Variants</a>\ <div class=\"sidebar-links\">{}</div>", variants.join(""), )); } sidebar_assoc_items(cx, &mut sidebar, it); if !sidebar.is_empty() { write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner()); } } fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) { match *ty { ItemType::ExternCrate | ItemType::Import => ("reexports", "Re-exports"), ItemType::Module => ("modules", "Modules"), ItemType::Struct => ("structs", "Structs"), ItemType::Union => ("unions", "Unions"), ItemType::Enum => ("enums", "Enums"), ItemType::Function => ("functions", "Functions"), ItemType::Typedef => ("types", "Type Definitions"), ItemType::Static => ("statics", "Statics"), ItemType::Constant => ("constants", "Constants"), ItemType::Trait => ("traits", "Traits"), ItemType::Impl => ("impls", "Implementations"), ItemType::TyMethod => ("tymethods", "Type Methods"), ItemType::Method => ("methods", "Methods"), ItemType::StructField => ("fields", "Struct Fields"), ItemType::Variant => ("variants", "Variants"), ItemType::Macro => ("macros", "Macros"), ItemType::Primitive => ("primitives", "Primitive Types"), ItemType::AssocType => ("associated-types", "Associated Types"), ItemType::AssocConst => ("associated-consts", "Associated Constants"), ItemType::ForeignType => ("foreign-types", "Foreign Types"), ItemType::Keyword => ("keywords", "Keywords"), ItemType::OpaqueTy => ("opaque-types", "Opaque Types"), ItemType::ProcAttribute => ("attributes", "Attribute Macros"), ItemType::ProcDerive => ("derives", "Derive Macros"), ItemType::TraitAlias => ("trait-aliases", "Trait aliases"), } } fn sidebar_module(buf: &mut Buffer, items: &[clean::Item]) { let mut sidebar = String::new(); if items.iter().any(|it| { it.type_() == ItemType::ExternCrate || (it.type_() == ItemType::Import && !it.is_stripped()) }) { sidebar.push_str("<li><a href=\"#reexports\">Re-exports</a></li>"); } // ordering taken from item_module, reorder, where it prioritized elements in a certain order // to print its headings for &myty in &[ ItemType::Primitive, ItemType::Module, ItemType::Macro, ItemType::Struct, ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait, ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl, ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant, ItemType::AssocType, ItemType::AssocConst, ItemType::ForeignType, ItemType::Keyword, ] { if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) { let (short, name) = item_ty_to_strs(&myty); sidebar.push_str(&format!( "<li><a href=\"#{id}\">{name}</a></li>", id = short, name = name )); } } if !sidebar.is_empty() { write!(buf, "<div class=\"block items\"><ul>{}</ul></div>", sidebar); } } fn sidebar_foreign_type(cx: &Context<'_>, buf: &mut Buffer, it: &clean::Item) { let mut sidebar = Buffer::new(); sidebar_assoc_items(cx, &mut sidebar, it); if !sidebar.is_empty() { write!(buf, "<div class=\"block items\">{}</div>", sidebar.into_inner()); } } fn item_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) { wrap_into_docblock(w, |w| { highlight::render_with_highlighting( &t.source, w, Some("macro"), None, None, it.source.span().edition(), ); }); document(w, cx, it, None) } fn item_proc_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, m: &clean::ProcMacro) { let name = it.name.as_ref().expect("proc-macros always have names"); match m.kind { MacroKind::Bang => { w.push_str("<pre class=\"rust macro\">"); write!(w, "{}!() {{ /* proc-macro */ }}", name); w.push_str("</pre>"); } MacroKind::Attr => { w.push_str("<pre class=\"rust attr\">"); write!(w, "#[{}]", name); w.push_str("</pre>"); } MacroKind::Derive => { w.push_str("<pre class=\"rust derive\">"); write!(w, "#[derive({})]", name); if !m.helpers.is_empty() { w.push_str("\n{\n"); w.push_str(" // Attributes available to this derive:\n"); for attr in &m.helpers { writeln!(w, " #[{}]", attr); } w.push_str("}\n"); } w.push_str("</pre>"); } } document(w, cx, it, None) } fn item_primitive(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) { document(w, cx, it, None); render_assoc_items(w, cx, it, it.def_id, AssocItemRender::All) } fn item_keyword(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item) { document(w, cx, it, None) } crate const BASIC_KEYWORDS: &str = "rust, rustlang, rust-lang"; fn make_item_keywords(it: &clean::Item) -> String { format!("{}, {}", BASIC_KEYWORDS, it.name.as_ref().unwrap()) } /// Returns a list of all paths used in the type. /// This is used to help deduplicate imported impls /// for reexported types. If any of the contained /// types are re-exported, we don't use the corresponding /// entry from the js file, as inlining will have already /// picked up the impl fn collect_paths_for_type(first_ty: clean::Type, cache: &Cache) -> Vec<String> { let mut out = Vec::new(); let mut visited = FxHashSet::default(); let mut work = VecDeque::new(); work.push_back(first_ty); while let Some(ty) = work.pop_front() { if !visited.insert(ty.clone()) { continue; } match ty { clean::Type::ResolvedPath { did, .. } => { let get_extern = || cache.external_paths.get(&did).map(|s| s.0.clone()); let fqp = cache.exact_paths.get(&did).cloned().or_else(get_extern); if let Some(path) = fqp { out.push(path.join("::")); } } clean::Type::Tuple(tys) => { work.extend(tys.into_iter()); } clean::Type::Slice(ty) => { work.push_back(*ty); } clean::Type::Array(ty, _) => { work.push_back(*ty); } clean::Type::RawPointer(_, ty) => { work.push_back(*ty); } clean::Type::BorrowedRef { type_, .. } => { work.push_back(*type_); } clean::Type::QPath { self_type, trait_, .. } => { work.push_back(*self_type); work.push_back(*trait_); } _ => {} } } out }
35.83252
121
0.506222
c151cb17cd49653c026f6950fbed00c0352be2a6
566
//! Utility functions shared among various unit tests. use crate::*; use std::env; use std::path; mod audio; mod conf; mod filesystem; mod graphics; mod mesh; mod text; /// Make a basic `Context` with sane defaults. pub fn make_context() -> (Context, event::EventsLoop) { let mut cb = ContextBuilder::new("ggez_unit_tests", "ggez"); if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") { let mut path = path::PathBuf::from(manifest_dir); path.push("resources"); cb = cb.add_resource_path(path); } cb.build().unwrap() }
23.583333
64
0.660777
5044130c6866add94f22a836eb05ddae87cc3cd4
295
/// protobuf crate version pub const VERSION: &'static str = "2.25.2"; /// This symbol is used by codegen #[doc(hidden)] pub const VERSION_IDENT: &'static str = "VERSION_2_25_2"; /// This symbol can be referenced to assert that proper version of crate is used pub const VERSION_2_25_2: () = ();
36.875
80
0.715254
bbe86fb0ba6aaf84a1ce4a1e7af183e43e22b956
14,311
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. extern crate lazy_static; use std::{ convert::{Into, TryFrom, TryInto}, num::{FpCategory, Wrapping}, }; mod float { use std::num::FpCategory; #[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] pub struct F64([u8; 8]); impl F64 { pub fn to_f64(&self) -> f64 { (*self).into() } pub fn classify(&self) -> FpCategory { self.to_f64().classify() } } impl From<f64> for F64 { fn from(f: f64) -> Self { F64(f.to_be_bytes()) } } impl Into<f64> for F64 { fn into(self) -> f64 { f64::from_be_bytes(self.0) } } } /// We introduce a type for Hack/PHP values, mimicking what happens at runtime. /// Currently this is used for constant folding. By defining a special type, we /// ensure independence from usage: for example, it can be used for optimization /// on ASTs, or on bytecode, or (in future) on a compiler intermediate language. /// HHVM takes a similar approach: see runtime/base/typed-value.h #[derive(Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)] pub enum TypedValue { /// Used for fields that are initialized in the 86pinit method Uninit, /// Hack/PHP integers are 64-bit Int(i64), Bool(bool), /// Both Hack/PHP and Caml floats are IEEE754 64-bit Float(float::F64), String(String), LazyClass(String), Null, // Classic PHP arrays with explicit (key,value) entries HhasAdata(String), // Hack arrays: vectors, keysets, and dictionaries Vec(Vec<TypedValue>), Keyset(Vec<TypedValue>), Dict(Vec<(TypedValue, TypedValue)>), } mod string_ops { pub fn bitwise_not(s: &str) -> String { let s = s.as_bytes(); let len = s.len(); let mut res = vec![0; len]; for i in 0..len { // keep only last byte res[i] = (!s[i]) & 0xFF; } // The "~" operator in Hack will create invalid utf-8 strings unsafe { String::from_utf8_unchecked(res) } } } /// Cast to a boolean: the (bool) operator in PHP impl From<TypedValue> for bool { fn from(x: TypedValue) -> bool { match x { TypedValue::Uninit => false, // Should not happen TypedValue::Bool(b) => b, TypedValue::Null => false, TypedValue::String(s) => s != "" && s != "0", TypedValue::LazyClass(_) => true, TypedValue::Int(i) => i != 0, TypedValue::Float(f) => f.to_f64() != 0.0, // Empty collections cast to false if empty, otherwise true TypedValue::Vec(v) => !v.is_empty(), TypedValue::Keyset(v) => !v.is_empty(), TypedValue::Dict(v) => !v.is_empty(), // Non-empty collections cast to true TypedValue::HhasAdata(_) => true, } } } pub type CastError = (); /// Cast to an integer: the (int) operator in PHP. Return Err if we can't /// or won't produce the correct value impl TryFrom<TypedValue> for i64 { type Error = CastError; fn try_from(x: TypedValue) -> Result<i64, Self::Error> { match x { TypedValue::Uninit => Err(()), // Should not happen // Unreachable - the only calliste of to_int is cast_to_arraykey, which never // calls it with String TypedValue::String(_) => Err(()), // not worth it TypedValue::LazyClass(_) => Err(()), // not worth it TypedValue::Int(i) => Ok(i), TypedValue::Float(f) => match f.classify() { FpCategory::Nan | FpCategory::Infinite => { if f.to_f64() == std::f64::INFINITY { Ok(0) } else { Ok(std::i64::MIN) } } _ => panic!("TODO"), }, v => Ok(if v.into() { 1 } else { 0 }), } } } /// Cast to a float: the (float) operator in PHP. Return Err if we can't /// or won't produce the correct value impl TryFrom<TypedValue> for f64 { type Error = CastError; fn try_from(v: TypedValue) -> Result<f64, Self::Error> { match v { TypedValue::Uninit => Err(()), // Should not happen TypedValue::String(_) => Err(()), // not worth it TypedValue::LazyClass(_) => Err(()), // not worth it TypedValue::Int(i) => Ok(i as f64), TypedValue::Float(f) => Ok(f.into()), _ => Ok(if v.into() { 1.0 } else { 0.0 }), } } } /// Cast to a string: the (string) operator in PHP. Return Err if we can't /// or won't produce the correct value *) impl TryFrom<TypedValue> for String { type Error = CastError; fn try_from(x: TypedValue) -> Result<String, Self::Error> { match x { TypedValue::Uninit => Err(()), // Should not happen TypedValue::Bool(false) => Ok("".into()), TypedValue::Bool(true) => Ok("1".into()), TypedValue::Null => Ok("".into()), TypedValue::Int(i) => Ok(i.to_string()), TypedValue::String(s) => Ok(s), TypedValue::LazyClass(s) => Ok(s), _ => Err(()), } } } impl TypedValue { // Integer operations. For now, we don't attempt to implement the // overflow-to-float semantics fn add_int(i1: i64, i2: i64) -> Option<TypedValue> { Some(Self::Int((Wrapping(i1) + Wrapping(i2)).0)) } pub fn neg(&self) -> Option<TypedValue> { match self { Self::Int(i) => Some(Self::Int((-Wrapping(*i)).0)), Self::Float(i) => Some(Self::float(0.0 - i.to_f64())), _ => None, } } fn sub_int(i1: i64, i2: i64) -> Option<TypedValue> { Some(Self::Int((Wrapping(i1) - Wrapping(i2)).0)) } // Arithmetic. For now, only on pure integer or float operands pub fn sub(&self, v2: &TypedValue) -> Option<TypedValue> { match (self, v2) { (Self::Int(i1), Self::Int(i2)) => Self::sub_int(*i1, *i2), (Self::Float(f1), Self::Float(f2)) => Some(Self::float(f1.to_f64() - f2.to_f64())), _ => None, } } fn mul_int(i1: i64, i2: i64) -> Option<TypedValue> { Some(Self::Int((Wrapping(i1) * Wrapping(i2)).0)) } // Arithmetic. For now, only on pure integer or float operands pub fn mul(&self, other: &TypedValue) -> Option<TypedValue> { match (self, other) { (Self::Int(i1), Self::Int(i2)) => Self::mul_int(*i1, *i2), (Self::Float(i1), Self::Float(i2)) => Some(Self::float(i1.to_f64() * i2.to_f64())), (Self::Int(i1), Self::Float(i2)) => Some(Self::float(*i1 as f64 * i2.to_f64())), (Self::Float(i1), Self::Int(i2)) => Some(Self::float(i1.to_f64() * *i2 as f64)), _ => None, } } // Arithmetic. For now, only on pure integer or float operands pub fn div(&self, v2: &TypedValue) -> Option<TypedValue> { match (self, v2) { (Self::Int(i1), Self::Int(i2)) if *i2 != 0 => { if i1 % i2 == 0 { Some(Self::Int(i1 / i2)) } else { Some(Self::float(*i1 as f64 / *i2 as f64)) } } (Self::Float(f1), Self::Float(f2)) if f2.to_f64() != 0.0 => { Some(Self::float(f1.to_f64() / f2.to_f64())) } (Self::Int(i1), Self::Float(f2)) if f2.to_f64() != 0.0 => { Some(Self::float(*i1 as f64 / f2.to_f64())) } (Self::Float(f1), Self::Int(i2)) if *i2 != 0 => { Some(Self::float(f1.to_f64() / *i2 as f64)) } _ => None, } } // Arithmetic. For now, only on pure integer or float operands pub fn add(&self, other: &TypedValue) -> Option<TypedValue> { match (self, other) { (Self::Float(i1), Self::Float(i2)) => Some(Self::float(i1.to_f64() + i2.to_f64())), (Self::Int(i1), Self::Int(i2)) => Self::add_int(*i1, *i2), (Self::Int(i1), Self::Float(i2)) => Some(Self::float(*i1 as f64 + i2.to_f64())), (Self::Float(i1), Self::Int(i2)) => Some(Self::float(i1.to_f64() + *i2 as f64)), _ => None, } } pub fn shift_left(&self, v2: &TypedValue) -> Option<TypedValue> { match (self, v2) { (Self::Int(i1), Self::Int(i2)) => { if *i2 < 0 { None } else { i32::try_from(*i2) .ok() .map(|i2| Self::Int(i1 << (i2 % 64) as u32)) } } _ => None, } } // Arithmetic. For now, only on pure integer operands pub fn bitwise_or(&self, other: &TypedValue) -> Option<TypedValue> { match (self, other) { (Self::Int(i1), Self::Int(i2)) => Some(Self::Int(i1 | i2)), _ => None, } } // String concatenation pub fn concat(self, v2: TypedValue) -> Option<TypedValue> { fn safe_to_cast(t: &TypedValue) -> bool { matches!( t, TypedValue::Int(_) | TypedValue::String(_) | TypedValue::LazyClass(_) ) } if !safe_to_cast(&self) || !safe_to_cast(&v2) { return None; } let s1: Option<String> = self.try_into().ok(); let s2: Option<String> = v2.try_into().ok(); match (s1, s2) { (Some(l), Some(r)) => Some(Self::String(l + &r)), _ => None, } } // Bitwise operations. pub fn bitwise_not(&self) -> Option<TypedValue> { match self { Self::Int(i) => Some(Self::Int(!i)), Self::String(s) => Some(Self::String(string_ops::bitwise_not(s))), _ => None, } } pub fn not(self) -> Option<TypedValue> { let b: bool = self.into(); Some(Self::Bool(!b)) } pub fn cast_to_string(self) -> Option<TypedValue> { self.try_into().ok().map(|x| Self::String(x)) } pub fn cast_to_int(self) -> Option<TypedValue> { self.try_into().ok().map(|x| Self::Int(x)) } pub fn cast_to_bool(self) -> Option<TypedValue> { Some(Self::Bool(self.into())) } pub fn cast_to_float(self) -> Option<TypedValue> { self.try_into().ok().map(|x| Self::float(x)) } pub fn cast_to_arraykey(self) -> Option<TypedValue> { match self { TypedValue::String(s) => Some(Self::String(s)), TypedValue::Null => Some(Self::String("".into())), TypedValue::Uninit | TypedValue::Vec(_) | TypedValue::Keyset(_) | TypedValue::Dict(_) => None, _ => Self::cast_to_int(self), } } pub fn string(s: impl Into<String>) -> TypedValue { Self::String(s.into()) } pub fn float(f: f64) -> Self { Self::Float(f.into()) } } #[cfg(test)] mod typed_value_tests { use super::TypedValue; use std::convert::TryInto; #[test] fn non_numeric_string_to_int() { let res: Option<i64> = TypedValue::String("foo".to_string()).try_into().ok(); assert!(res.is_none()); } #[test] fn nan_to_int() { let res: i64 = TypedValue::float(std::f64::NAN).try_into().unwrap(); assert_eq!(res, std::i64::MIN); } #[test] fn inf_to_int() { let res: i64 = TypedValue::float(std::f64::INFINITY).try_into().unwrap(); assert_eq!(res, 0); } #[test] fn neg_inf_to_int() { let res: i64 = TypedValue::float(std::f64::NEG_INFINITY) .try_into() .unwrap(); assert_eq!(res, std::i64::MIN); } #[test] fn false_to_int() { let res: i64 = TypedValue::Bool(false).try_into().unwrap(); assert_eq!(res, 0); } #[test] fn true_to_int() { let res: i64 = TypedValue::Bool(true).try_into().unwrap(); assert_eq!(res, 1); } #[test] fn non_numeric_string_to_float() { let res: Option<f64> = TypedValue::String("foo".to_string()).try_into().ok(); assert!(res.is_none()); } #[test] fn int_wrapping_add() { let res = TypedValue::Int(0x7FFFFFFFFFFFFFFF) .add(&TypedValue::Int(1)) .unwrap(); assert_eq!(res, TypedValue::Int(-9223372036854775808)); } #[test] fn int_wrapping_neg() { let res = TypedValue::Int(1 << 63).neg().unwrap(); assert_eq!(res, TypedValue::Int(-9223372036854775808)); } #[test] fn int_wrapping_sub() { let res = TypedValue::Int(1 << 63).sub(&TypedValue::Int(1)).unwrap(); assert_eq!(res, TypedValue::Int(9223372036854775807)); } #[test] fn int_wrapping_mul() { let res = TypedValue::Int(0x80000001) .mul(&TypedValue::Int(-0xffffffff)) .unwrap(); assert_eq!(res, TypedValue::Int(9223372034707292161)); } #[test] fn negative_shift_left() { let res = TypedValue::Int(3).shift_left(&TypedValue::Int(-1)); assert_eq!(res, None); } #[test] fn big_shift_left() { let res = TypedValue::Int(1).shift_left(&TypedValue::Int(70)).unwrap(); assert_eq!(res, TypedValue::Int(64)); } #[test] fn eq() { assert_eq!(TypedValue::Bool(true), TypedValue::Bool(true)); assert_ne!(TypedValue::Int(2), TypedValue::Int(3)); assert_eq!( TypedValue::String("foo".to_string()), TypedValue::String("foo".to_string()) ); assert_eq!( TypedValue::float(std::f64::NAN), TypedValue::float(std::f64::NAN) ); } #[test] fn overflowing_shift_left() { let res = TypedValue::Int(1).shift_left(&TypedValue::Int(0xffffffffffff)); assert_eq!(res, None); } /* #[test] fn eq() { assert_eq!(TypedValue::Bool(true), TypedValue::Bool(true)); } */ }
31.873051
95
0.520579
62b1254287724aedacab6f5a7642124dbfd2bcdb
15,349
use crate::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE}; use crate::hir; use rustc_ast as ast; use rustc_ast::NodeId; use rustc_macros::HashStable_Generic; use rustc_span::hygiene::MacroKind; use std::array::IntoIter; use std::fmt::Debug; /// Encodes if a `DefKind::Ctor` is the constructor of an enum variant or a struct. #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)] #[derive(HashStable_Generic)] pub enum CtorOf { /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit struct. Struct, /// This `DefKind::Ctor` is a synthesized constructor of a tuple or unit variant. Variant, } #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)] #[derive(HashStable_Generic)] pub enum CtorKind { /// Constructor function automatically created by a tuple struct/variant. Fn, /// Constructor constant automatically created by a unit struct/variant. Const, /// Unusable name in value namespace created by a struct variant. Fictive, } #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)] #[derive(HashStable_Generic)] pub enum NonMacroAttrKind { /// Single-segment attribute defined by the language (`#[inline]`) Builtin, /// Multi-segment custom attribute living in a "tool module" (`#[rustfmt::skip]`). Tool, /// Single-segment custom attribute registered by a derive macro (`#[serde(default)]`). DeriveHelper, /// Single-segment custom attribute registered with `#[register_attr]`. Registered, } #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)] #[derive(HashStable_Generic)] pub enum DefKind { // Type namespace Mod, /// Refers to the struct itself, `DefKind::Ctor` refers to its constructor if it exists. Struct, Union, Enum, /// Refers to the variant itself, `DefKind::Ctor` refers to its constructor if it exists. Variant, Trait, /// `type Foo = Bar;` TyAlias, ForeignTy, TraitAlias, AssocTy, TyParam, // Value namespace Fn, Const, ConstParam, Static, /// Refers to the struct or enum variant's constructor. Ctor(CtorOf, CtorKind), AssocFn, AssocConst, // Macro namespace Macro(MacroKind), // Not namespaced (or they are, but we don't treat them so) ExternCrate, Use, ForeignMod, AnonConst, OpaqueTy, Field, LifetimeParam, GlobalAsm, Impl, Closure, Generator, } impl DefKind { pub fn descr(self, def_id: DefId) -> &'static str { match self { DefKind::Fn => "function", DefKind::Mod if def_id.index == CRATE_DEF_INDEX && def_id.krate != LOCAL_CRATE => { "crate" } DefKind::Mod => "module", DefKind::Static => "static", DefKind::Enum => "enum", DefKind::Variant => "variant", DefKind::Ctor(CtorOf::Variant, CtorKind::Fn) => "tuple variant", DefKind::Ctor(CtorOf::Variant, CtorKind::Const) => "unit variant", DefKind::Ctor(CtorOf::Variant, CtorKind::Fictive) => "struct variant", DefKind::Struct => "struct", DefKind::Ctor(CtorOf::Struct, CtorKind::Fn) => "tuple struct", DefKind::Ctor(CtorOf::Struct, CtorKind::Const) => "unit struct", DefKind::Ctor(CtorOf::Struct, CtorKind::Fictive) => { panic!("impossible struct constructor") } DefKind::OpaqueTy => "opaque type", DefKind::TyAlias => "type alias", DefKind::TraitAlias => "trait alias", DefKind::AssocTy => "associated type", DefKind::Union => "union", DefKind::Trait => "trait", DefKind::ForeignTy => "foreign type", DefKind::AssocFn => "associated function", DefKind::Const => "constant", DefKind::AssocConst => "associated constant", DefKind::TyParam => "type parameter", DefKind::ConstParam => "const parameter", DefKind::Macro(macro_kind) => macro_kind.descr(), DefKind::LifetimeParam => "lifetime parameter", DefKind::Use => "import", DefKind::ForeignMod => "foreign module", DefKind::AnonConst => "constant expression", DefKind::Field => "field", DefKind::Impl => "implementation", DefKind::Closure => "closure", DefKind::Generator => "generator", DefKind::ExternCrate => "extern crate", DefKind::GlobalAsm => "global assembly block", } } /// Gets an English article for the definition. pub fn article(&self) -> &'static str { match *self { DefKind::AssocTy | DefKind::AssocConst | DefKind::AssocFn | DefKind::Enum | DefKind::OpaqueTy | DefKind::Impl | DefKind::Use | DefKind::ExternCrate => "an", DefKind::Macro(macro_kind) => macro_kind.article(), _ => "a", } } pub fn ns(&self) -> Option<Namespace> { match self { DefKind::Mod | DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::Variant | DefKind::Trait | DefKind::OpaqueTy | DefKind::TyAlias | DefKind::ForeignTy | DefKind::TraitAlias | DefKind::AssocTy | DefKind::TyParam => Some(Namespace::TypeNS), DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static | DefKind::Ctor(..) | DefKind::AssocFn | DefKind::AssocConst => Some(Namespace::ValueNS), DefKind::Macro(..) => Some(Namespace::MacroNS), // Not namespaced. DefKind::AnonConst | DefKind::Field | DefKind::LifetimeParam | DefKind::ExternCrate | DefKind::Closure | DefKind::Generator | DefKind::Use | DefKind::ForeignMod | DefKind::GlobalAsm | DefKind::Impl => None, } } } /// The resolution of a path or export. #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)] #[derive(HashStable_Generic)] pub enum Res<Id = hir::HirId> { Def(DefKind, DefId), // Type namespace PrimTy(hir::PrimTy), /// `Self`, with both an optional trait and impl `DefId`. /// /// HACK(min_const_generics): impl self types also have an optional requirement to not mention /// any generic parameters to allow the following with `min_const_generics`: /// ```rust /// impl Foo { fn test() -> [u8; std::mem::size_of::<Self>()] {} } /// ``` /// /// FIXME(lazy_normalization_consts): Remove this bodge once this feature is stable. SelfTy(Option<DefId> /* trait */, Option<(DefId, bool)> /* impl */), ToolMod, // e.g., `rustfmt` in `#[rustfmt::skip]` // Value namespace SelfCtor(DefId /* impl */), // `DefId` refers to the impl Local(Id), // Macro namespace NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]` // All namespaces Err, } /// The result of resolving a path before lowering to HIR, /// with "module" segments resolved and associated item /// segments deferred to type checking. /// `base_res` is the resolution of the resolved part of the /// path, `unresolved_segments` is the number of unresolved /// segments. /// /// ```text /// module::Type::AssocX::AssocY::MethodOrAssocType /// ^~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /// base_res unresolved_segments = 3 /// /// <T as Trait>::AssocX::AssocY::MethodOrAssocType /// ^~~~~~~~~~~~~~ ^~~~~~~~~~~~~~~~~~~~~~~~~ /// base_res unresolved_segments = 2 /// ``` #[derive(Copy, Clone, Debug)] pub struct PartialRes { base_res: Res<NodeId>, unresolved_segments: usize, } impl PartialRes { #[inline] pub fn new(base_res: Res<NodeId>) -> Self { PartialRes { base_res, unresolved_segments: 0 } } #[inline] pub fn with_unresolved_segments(base_res: Res<NodeId>, mut unresolved_segments: usize) -> Self { if base_res == Res::Err { unresolved_segments = 0 } PartialRes { base_res, unresolved_segments } } #[inline] pub fn base_res(&self) -> Res<NodeId> { self.base_res } #[inline] pub fn unresolved_segments(&self) -> usize { self.unresolved_segments } } /// Different kinds of symbols don't influence each other. /// /// Therefore, they have a separate universe (namespace). #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub enum Namespace { TypeNS, ValueNS, MacroNS, } impl Namespace { pub fn descr(self) -> &'static str { match self { Self::TypeNS => "type", Self::ValueNS => "value", Self::MacroNS => "macro", } } } /// Just a helper ‒ separate structure for each namespace. #[derive(Copy, Clone, Default, Debug)] pub struct PerNS<T> { pub value_ns: T, pub type_ns: T, pub macro_ns: T, } impl<T> PerNS<T> { pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> PerNS<U> { PerNS { value_ns: f(self.value_ns), type_ns: f(self.type_ns), macro_ns: f(self.macro_ns) } } pub fn into_iter(self) -> IntoIter<T, 3> { IntoIter::new([self.value_ns, self.type_ns, self.macro_ns]) } pub fn iter(&self) -> IntoIter<&T, 3> { IntoIter::new([&self.value_ns, &self.type_ns, &self.macro_ns]) } } impl<T> ::std::ops::Index<Namespace> for PerNS<T> { type Output = T; fn index(&self, ns: Namespace) -> &T { match ns { Namespace::ValueNS => &self.value_ns, Namespace::TypeNS => &self.type_ns, Namespace::MacroNS => &self.macro_ns, } } } impl<T> ::std::ops::IndexMut<Namespace> for PerNS<T> { fn index_mut(&mut self, ns: Namespace) -> &mut T { match ns { Namespace::ValueNS => &mut self.value_ns, Namespace::TypeNS => &mut self.type_ns, Namespace::MacroNS => &mut self.macro_ns, } } } impl<T> PerNS<Option<T>> { /// Returns `true` if all the items in this collection are `None`. pub fn is_empty(&self) -> bool { self.type_ns.is_none() && self.value_ns.is_none() && self.macro_ns.is_none() } /// Returns an iterator over the items which are `Some`. pub fn present_items(self) -> impl Iterator<Item = T> { IntoIter::new([self.type_ns, self.value_ns, self.macro_ns]).filter_map(|it| it) } } impl CtorKind { pub fn from_ast(vdata: &ast::VariantData) -> CtorKind { match *vdata { ast::VariantData::Tuple(..) => CtorKind::Fn, ast::VariantData::Unit(..) => CtorKind::Const, ast::VariantData::Struct(..) => CtorKind::Fictive, } } pub fn from_hir(vdata: &hir::VariantData<'_>) -> CtorKind { match *vdata { hir::VariantData::Tuple(..) => CtorKind::Fn, hir::VariantData::Unit(..) => CtorKind::Const, hir::VariantData::Struct(..) => CtorKind::Fictive, } } } impl NonMacroAttrKind { pub fn descr(self) -> &'static str { match self { NonMacroAttrKind::Builtin => "built-in attribute", NonMacroAttrKind::Tool => "tool attribute", NonMacroAttrKind::DeriveHelper => "derive helper attribute", NonMacroAttrKind::Registered => "explicitly registered attribute", } } pub fn article(self) -> &'static str { match self { NonMacroAttrKind::Registered => "an", _ => "a", } } /// Users of some attributes cannot mark them as used, so they are considered always used. pub fn is_used(self) -> bool { match self { NonMacroAttrKind::Tool | NonMacroAttrKind::DeriveHelper => true, NonMacroAttrKind::Builtin | NonMacroAttrKind::Registered => false, } } } impl<Id> Res<Id> { /// Return the `DefId` of this `Def` if it has an ID, else panic. pub fn def_id(&self) -> DefId where Id: Debug, { self.opt_def_id() .unwrap_or_else(|| panic!("attempted .def_id() on invalid res: {:?}", self)) } /// Return `Some(..)` with the `DefId` of this `Res` if it has a ID, else `None`. pub fn opt_def_id(&self) -> Option<DefId> { match *self { Res::Def(_, id) => Some(id), Res::Local(..) | Res::PrimTy(..) | Res::SelfTy(..) | Res::SelfCtor(..) | Res::ToolMod | Res::NonMacroAttr(..) | Res::Err => None, } } /// Return the `DefId` of this `Res` if it represents a module. pub fn mod_def_id(&self) -> Option<DefId> { match *self { Res::Def(DefKind::Mod, id) => Some(id), _ => None, } } /// A human readable name for the res kind ("function", "module", etc.). pub fn descr(&self) -> &'static str { match *self { Res::Def(kind, def_id) => kind.descr(def_id), Res::SelfCtor(..) => "self constructor", Res::PrimTy(..) => "builtin type", Res::Local(..) => "local variable", Res::SelfTy(..) => "self type", Res::ToolMod => "tool module", Res::NonMacroAttr(attr_kind) => attr_kind.descr(), Res::Err => "unresolved item", } } /// Gets an English article for the `Res`. pub fn article(&self) -> &'static str { match *self { Res::Def(kind, _) => kind.article(), Res::NonMacroAttr(kind) => kind.article(), Res::Err => "an", _ => "a", } } pub fn map_id<R>(self, mut map: impl FnMut(Id) -> R) -> Res<R> { match self { Res::Def(kind, id) => Res::Def(kind, id), Res::SelfCtor(id) => Res::SelfCtor(id), Res::PrimTy(id) => Res::PrimTy(id), Res::Local(id) => Res::Local(map(id)), Res::SelfTy(a, b) => Res::SelfTy(a, b), Res::ToolMod => Res::ToolMod, Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind), Res::Err => Res::Err, } } pub fn macro_kind(self) -> Option<MacroKind> { match self { Res::Def(DefKind::Macro(kind), _) => Some(kind), Res::NonMacroAttr(..) => Some(MacroKind::Attr), _ => None, } } /// Returns `None` if this is `Res::Err` pub fn ns(&self) -> Option<Namespace> { match self { Res::Def(kind, ..) => kind.ns(), Res::PrimTy(..) | Res::SelfTy(..) | Res::ToolMod => Some(Namespace::TypeNS), Res::SelfCtor(..) | Res::Local(..) => Some(Namespace::ValueNS), Res::NonMacroAttr(..) => Some(Namespace::MacroNS), Res::Err => None, } } /// Always returns `true` if `self` is `Res::Err` pub fn matches_ns(&self, ns: Namespace) -> bool { self.ns().map_or(true, |actual_ns| actual_ns == ns) } }
31.582305
100
0.558147
ebd4c1b9d4c2d76c9dda0bebd849b11ea844358d
907
#[doc = r" Value read from the register"] pub struct R { bits: u32, } impl super::DIEP2_TXFSTS { #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } } #[doc = r" Value of the field"] pub struct SPCAVAILR { bits: u16, } impl SPCAVAILR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u16 { self.bits } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:15 - TxFIFO Space Available"] #[inline] pub fn spcavail(&self) -> SPCAVAILR { let bits = { const MASK: u16 = 0xffff; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u16 }; SPCAVAILR { bits } } }
21.595238
56
0.509372
01f730f47781ce5a6dd2ff40301cc86cccebd19b
3,251
// Copyright 2021 - Nym Technologies SA <[email protected]> // SPDX-License-Identifier: Apache-2.0 use crate::nymd::cosmwasm_client::types::ContractCodeId; use cosmrs::tendermint::block; use cosmrs::{bip32, rpc, tx, AccountId}; use std::io; use thiserror::Error; #[derive(Debug, Error)] pub enum NymdError { #[error("No contract address is available to perform the call")] NoContractAddressAvailable, #[error("There was an issue with bip32 - {0}")] Bip32Error(#[from] bip32::Error), #[error("There was an issue with bip32 - {0}")] Bip39Error(#[from] bip39::Error), #[error("Failed to derive account address")] AccountDerivationError, #[error("Address {0} was not found in the wallet")] SigningAccountNotFound(AccountId), #[error("Failed to sign raw transaction")] SigningFailure, #[error("{0} is not a valid tx hash")] InvalidTxHash(String), #[error("There was an issue with a tendermint RPC request - {0}")] TendermintError(#[from] rpc::Error), #[error("There was an issue when attempting to serialize data")] SerializationError(String), #[error("There was an issue when attempting to deserialize data")] DeserializationError(String), #[error("There was an issue when attempting to encode our protobuf data - {0}")] ProtobufEncodingError(#[from] prost::EncodeError), #[error("There was an issue when attempting to decode our protobuf data - {0}")] ProtobufDecodingError(#[from] prost::DecodeError), #[error("Account {0} does not exist on the chain")] NonExistentAccountError(AccountId), #[error("There was an issue with the serialization/deserialization - {0}")] SerdeJsonError(#[from] serde_json::Error), #[error("Account {0} is not a valid account address")] MalformedAccountAddress(String), #[error("Account {0} has an invalid associated public key")] InvalidPublicKey(AccountId), #[error("Queried contract (code_id: {0}) did not have any code information attached")] NoCodeInformation(ContractCodeId), #[error("Queried contract (address: {0}) did not have any contract information attached")] NoContractInformation(AccountId), #[error("Contract contains invalid operations in its history")] InvalidContractHistoryOperation, #[error("Block has an invalid height (either negative or larger than i64::MAX")] InvalidHeight, #[error("Failed to compress provided wasm code - {0}")] WasmCompressionError(io::Error), #[error("Logs returned from the validator were malformed")] MalformedLogString, #[error( "Error when broadcasting tx {hash} at height {height}. Error occurred during CheckTx phase. Code: {code}; Raw log: {raw_log}" )] BroadcastTxErrorCheckTx { hash: tx::Hash, height: block::Height, code: u32, raw_log: String, }, #[error( "Error when broadcasting tx {hash} at height {height}. Error occurred during DeliverTx phase. Code: {code}; Raw log: {raw_log}" )] BroadcastTxErrorDeliverTx { hash: tx::Hash, height: block::Height, code: u32, raw_log: String, }, #[error("The provided gas price is malformed")] MalformedGasPrice, }
32.188119
131
0.677638
87a056acef215d6fdfa526aaf1376c0676a520f3
892
use rustc_serialize::json; use std::ops::Deref; use rustc_serialize::{Encoder, Encodable}; pub static DELETE_KEY : &'static str = "$$delete"; //pub static UPDATE_KEY : &'static str = "$$delete"; #[derive(Clone, Debug)] pub enum Entry{ Insert(json::Json), Delete(json::Json), Update(json::Json) } //impl Deref for Entry { //type Target = json::Json; //fn deref<'a>(&'a self) -> &'a json::Json { //match self { //&Entry::Insert(ref x) => { x } //&Entry::Delete(ref x) => { x } //&Entry::Update(ref x) => { x } //} //} //} impl Encodable for Entry { fn encode<S : Encoder>(&self, s : &mut S) -> Result<(), S::Error> { match self { &Entry::Insert(ref x) => {x.encode(s)} &Entry::Delete(ref x) => {x.encode(s)} &Entry::Update(ref x) => {x.encode(s)} } } }
24.777778
71
0.513453
ef3114ff394eb75baa9e5bddb70fed1a85ec6c01
960
// 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. // run-pass #![allow(unused)] fn foo<F>(f: F) where F: FnOnce() { } fn main() { // Test that this closure is inferred to `FnOnce` // because it moves from `y.as<Option::Some>.0`: let x = Some(vec![1, 2, 3]); foo(|| { match x { Some(y) => { } None => { } } }); // Test that this closure is inferred to `FnOnce` // because it moves from `y.0`: let y = (vec![1, 2, 3], 0); foo(|| { let x = y.0; }); }
25.945946
68
0.59375
91df928002a1b71b487a76808722bf6e22a4aa9c
40,905
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt::{self, Display, Formatter}; use std::io; use std::sync::mpsc::{self, Sender}; use std::sync::Arc; use std::thread::{Builder, JoinHandle}; use std::time::{Duration, Instant}; use futures::Future; use tokio_core::reactor::Handle; use tokio_timer::Delay; use engine::rocks::util::*; use engine::rocks::DB; use engine_rocks::RocksEngine; use fs2; use kvproto::metapb; use kvproto::pdpb; use kvproto::raft_cmdpb::{AdminCmdType, AdminRequest, RaftCmdRequest, SplitRequest}; use kvproto::raft_serverpb::RaftMessage; use prometheus::local::LocalHistogram; use raft::eraftpb::ConfChangeType; use crate::config::ConfigHandler; use crate::raftstore::coprocessor::{get_region_approximate_keys, get_region_approximate_size}; use crate::raftstore::store::cmd_resp::new_error; use crate::raftstore::store::util::is_epoch_stale; use crate::raftstore::store::util::KeysInfoFormatter; use crate::raftstore::store::Callback; use crate::raftstore::store::StoreInfo; use crate::raftstore::store::{CasualMessage, PeerMsg, RaftCommand, RaftRouter}; use crate::storage::FlowStatistics; use pd_client::metrics::*; use pd_client::{Error, PdClient, RegionStat}; use tikv_util::collections::HashMap; use tikv_util::metrics::ThreadInfoStatistics; use tikv_util::time::UnixSecs; use tikv_util::worker::{FutureRunnable as Runnable, FutureScheduler as Scheduler, Stopped}; type RecordPairVec = Vec<pdpb::RecordPair>; /// Uses an asynchronous thread to tell PD something. pub enum Task { AskSplit { region: metapb::Region, split_key: Vec<u8>, peer: metapb::Peer, // If true, right Region derives origin region_id. right_derive: bool, callback: Callback<RocksEngine>, }, AskBatchSplit { region: metapb::Region, split_keys: Vec<Vec<u8>>, peer: metapb::Peer, // If true, right Region derives origin region_id. right_derive: bool, callback: Callback<RocksEngine>, }, Heartbeat { term: u64, region: metapb::Region, peer: metapb::Peer, down_peers: Vec<pdpb::PeerStats>, pending_peers: Vec<metapb::Peer>, written_bytes: u64, written_keys: u64, approximate_size: Option<u64>, approximate_keys: Option<u64>, }, StoreHeartbeat { stats: pdpb::StoreStats, store_info: StoreInfo, }, ReportBatchSplit { regions: Vec<metapb::Region>, }, ValidatePeer { region: metapb::Region, peer: metapb::Peer, merge_source: Option<u64>, }, ReadStats { read_stats: HashMap<u64, FlowStatistics>, }, DestroyPeer { region_id: u64, }, StoreInfos { cpu_usages: RecordPairVec, read_io_rates: RecordPairVec, write_io_rates: RecordPairVec, }, RefreshConfig, } pub struct StoreStat { pub engine_total_bytes_read: u64, pub engine_total_keys_read: u64, pub engine_last_total_bytes_read: u64, pub engine_last_total_keys_read: u64, pub last_report_ts: UnixSecs, pub region_bytes_read: LocalHistogram, pub region_keys_read: LocalHistogram, pub region_bytes_written: LocalHistogram, pub region_keys_written: LocalHistogram, pub store_cpu_usages: RecordPairVec, pub store_read_io_rates: RecordPairVec, pub store_write_io_rates: RecordPairVec, } impl Default for StoreStat { fn default() -> StoreStat { StoreStat { region_bytes_read: REGION_READ_BYTES_HISTOGRAM.local(), region_keys_read: REGION_READ_KEYS_HISTOGRAM.local(), region_bytes_written: REGION_WRITTEN_BYTES_HISTOGRAM.local(), region_keys_written: REGION_WRITTEN_KEYS_HISTOGRAM.local(), last_report_ts: UnixSecs::zero(), engine_total_bytes_read: 0, engine_total_keys_read: 0, engine_last_total_bytes_read: 0, engine_last_total_keys_read: 0, store_cpu_usages: RecordPairVec::default(), store_read_io_rates: RecordPairVec::default(), store_write_io_rates: RecordPairVec::default(), } } } #[derive(Default)] pub struct PeerStat { pub read_bytes: u64, pub read_keys: u64, pub last_read_bytes: u64, pub last_read_keys: u64, pub last_written_bytes: u64, pub last_written_keys: u64, pub last_report_ts: UnixSecs, } impl Display for Task { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match *self { Task::AskSplit { ref region, ref split_key, .. } => write!( f, "ask split region {} with key {}", region.get_id(), hex::encode_upper(&split_key), ), Task::AskBatchSplit { ref region, ref split_keys, .. } => write!( f, "ask split region {} with {}", region.get_id(), KeysInfoFormatter(split_keys.iter()) ), Task::Heartbeat { ref region, ref peer, .. } => write!( f, "heartbeat for region {:?}, leader {}", region, peer.get_id() ), Task::StoreHeartbeat { ref stats, .. } => { write!(f, "store heartbeat stats: {:?}", stats) } Task::ReportBatchSplit { ref regions } => write!(f, "report split {:?}", regions), Task::ValidatePeer { ref region, ref peer, ref merge_source, } => write!( f, "validate peer {:?} with region {:?}, merge_source {:?}", peer, region, merge_source ), Task::ReadStats { ref read_stats } => { write!(f, "get the read statistics {:?}", read_stats) } Task::DestroyPeer { ref region_id } => { write!(f, "destroy peer of region {}", region_id) } Task::StoreInfos { ref cpu_usages, ref read_io_rates, ref write_io_rates, } => write!( f, "get store's informations: cpu_usages {:?}, read_io_rates {:?}, write_io_rates {:?}", cpu_usages, read_io_rates, write_io_rates, ), Task::RefreshConfig => write!(f, "refresh config"), } } } #[inline] fn convert_record_pairs(m: HashMap<String, u64>) -> RecordPairVec { m.into_iter() .map(|(k, v)| { let mut pair = pdpb::RecordPair::default(); pair.set_key(k); pair.set_value(v); pair }) .collect() } struct StatsMonitor { scheduler: Scheduler<Task>, handle: Option<JoinHandle<()>>, sender: Option<Sender<bool>>, interval: Duration, } impl StatsMonitor { pub fn new(interval: Duration, scheduler: Scheduler<Task>) -> Self { StatsMonitor { scheduler, handle: None, sender: None, interval, } } pub fn start(&mut self) -> Result<(), io::Error> { let (tx, rx) = mpsc::channel(); let interval = self.interval; let scheduler = self.scheduler.clone(); self.sender = Some(tx); let h = Builder::new() .name(thd_name!("stats-monitor")) .spawn(move || { let mut thread_stats = ThreadInfoStatistics::new(); while let Err(mpsc::RecvTimeoutError::Timeout) = rx.recv_timeout(interval) { thread_stats.record(); let cpu_usages = convert_record_pairs(thread_stats.get_cpu_usages()); let read_io_rates = convert_record_pairs(thread_stats.get_read_io_rates()); let write_io_rates = convert_record_pairs(thread_stats.get_write_io_rates()); let task = Task::StoreInfos { cpu_usages, read_io_rates, write_io_rates, }; if let Err(e) = scheduler.schedule(task) { error!( "failed to send store infos to pd worker"; "err" => ?e, ); } } })?; self.handle = Some(h); Ok(()) } pub fn stop(&mut self) { let h = self.handle.take(); if h.is_none() { return; } drop(self.sender.take().unwrap()); if let Err(e) = h.unwrap().join() { error!("join stats collector failed"; "err" => ?e); return; } } } pub struct Runner<T: PdClient> { store_id: u64, pd_client: Arc<T>, config_handler: ConfigHandler, router: RaftRouter, db: Arc<DB>, region_peers: HashMap<u64, PeerStat>, store_stat: StoreStat, is_hb_receiver_scheduled: bool, // Records the boot time. start_ts: UnixSecs, // use for Runner inner handle function to send Task to itself // actually it is the sender connected to Runner's Worker which // calls Runner's run() on Task received. scheduler: Scheduler<Task>, stats_monitor: StatsMonitor, } impl<T: PdClient> Runner<T> { const INTERVAL_DIVISOR: u32 = 2; pub fn new( store_id: u64, pd_client: Arc<T>, config_handler: ConfigHandler, router: RaftRouter, db: Arc<DB>, scheduler: Scheduler<Task>, store_heartbeat_interval: u64, ) -> Runner<T> { let interval = Duration::from_secs(store_heartbeat_interval) / Self::INTERVAL_DIVISOR; let mut stats_monitor = StatsMonitor::new(interval, scheduler.clone()); if let Err(e) = stats_monitor.start() { error!("failed to start stats collector, error = {:?}", e); } Runner { store_id, pd_client, config_handler, router, db, is_hb_receiver_scheduled: false, region_peers: HashMap::default(), store_stat: StoreStat::default(), start_ts: UnixSecs::now(), scheduler, stats_monitor, } } fn handle_ask_split( &self, handle: &Handle, mut region: metapb::Region, split_key: Vec<u8>, peer: metapb::Peer, right_derive: bool, callback: Callback<RocksEngine>, ) { let router = self.router.clone(); let f = self.pd_client.ask_split(region.clone()).then(move |resp| { match resp { Ok(mut resp) => { info!( "try to split region"; "region_id" => region.get_id(), "new_region_id" => resp.get_new_region_id(), "region" => ?region ); let req = new_split_region_request( split_key, resp.get_new_region_id(), resp.take_new_peer_ids(), right_derive, ); let region_id = region.get_id(); let epoch = region.take_region_epoch(); send_admin_request(&router, region_id, epoch, peer, req, callback) } Err(e) => { debug!("failed to ask split"; "region_id" => region.get_id(), "err" => ?e); } } Ok(()) }); handle.spawn(f) } fn handle_ask_batch_split( &self, handle: &Handle, mut region: metapb::Region, mut split_keys: Vec<Vec<u8>>, peer: metapb::Peer, right_derive: bool, callback: Callback<RocksEngine>, ) { let router = self.router.clone(); let scheduler = self.scheduler.clone(); let f = self .pd_client .ask_batch_split(region.clone(), split_keys.len()) .then(move |resp| { match resp { Ok(mut resp) => { info!( "try to batch split region"; "region_id" => region.get_id(), "new_region_ids" => ?resp.get_ids(), "region" => ?region, ); let req = new_batch_split_region_request( split_keys, resp.take_ids().into(), right_derive, ); let region_id = region.get_id(); let epoch = region.take_region_epoch(); send_admin_request(&router, region_id, epoch, peer, req, callback) } // When rolling update, there might be some old version tikvs that don't support batch split in cluster. // In this situation, PD version check would refuse `ask_batch_split`. // But if update time is long, it may cause large Regions, so call `ask_split` instead. Err(Error::Incompatible) => { let (region_id, peer_id) = (region.id, peer.id); info!( "ask_batch_split is incompatible, use ask_split instead"; "region_id" => region_id ); let task = Task::AskSplit { region, split_key: split_keys.pop().unwrap(), peer, right_derive, callback, }; if let Err(Stopped(t)) = scheduler.schedule(task) { error!( "failed to notify pd to split: Stopped"; "region_id" => region_id, "peer_id" => peer_id ); match t { Task::AskSplit { callback, .. } => { callback.invoke_with_response(new_error(box_err!( "failed to split: Stopped" ))); } _ => unreachable!(), } } } Err(e) => { debug!( "ask batch split failed"; "region_id" => region.get_id(), "err" => ?e, ); } } Ok(()) }); handle.spawn(f) } fn handle_heartbeat( &self, handle: &Handle, term: u64, region: metapb::Region, peer: metapb::Peer, region_stat: RegionStat, ) { self.store_stat .region_bytes_written .observe(region_stat.written_bytes as f64); self.store_stat .region_keys_written .observe(region_stat.written_keys as f64); self.store_stat .region_bytes_read .observe(region_stat.read_bytes as f64); self.store_stat .region_keys_read .observe(region_stat.read_keys as f64); let f = self .pd_client .region_heartbeat(term, region.clone(), peer.clone(), region_stat) .map_err(move |e| { debug!( "failed to send heartbeat"; "region_id" => region.get_id(), "err" => ?e ); }); handle.spawn(f); } fn handle_store_heartbeat( &mut self, handle: &Handle, mut stats: pdpb::StoreStats, store_info: StoreInfo, ) { let disk_stats = match fs2::statvfs(store_info.engine.path()) { Err(e) => { error!( "get disk stat for rocksdb failed"; "engine_path" => store_info.engine.path(), "err" => ?e ); return; } Ok(stats) => stats, }; let disk_cap = disk_stats.total_space(); let capacity = if store_info.capacity == 0 || disk_cap < store_info.capacity { disk_cap } else { store_info.capacity }; stats.set_capacity(capacity); // already include size of snapshot files let used_size = stats.get_used_size() + get_engine_used_size(Arc::clone(&store_info.engine)); stats.set_used_size(used_size); let mut available = if capacity > used_size { capacity - used_size } else { warn!("no available space"); 0 }; // We only care about rocksdb SST file size, so we should check disk available here. if available > disk_stats.free_space() { available = disk_stats.free_space(); } stats.set_available(available); stats.set_bytes_read( self.store_stat.engine_total_bytes_read - self.store_stat.engine_last_total_bytes_read, ); stats.set_keys_read( self.store_stat.engine_total_keys_read - self.store_stat.engine_last_total_keys_read, ); stats.set_cpu_usages(self.store_stat.store_cpu_usages.clone().into()); stats.set_read_io_rates(self.store_stat.store_read_io_rates.clone().into()); stats.set_write_io_rates(self.store_stat.store_write_io_rates.clone().into()); let mut interval = pdpb::TimeInterval::default(); interval.set_start_timestamp(self.store_stat.last_report_ts.into_inner()); stats.set_interval(interval); self.store_stat.engine_last_total_bytes_read = self.store_stat.engine_total_bytes_read; self.store_stat.engine_last_total_keys_read = self.store_stat.engine_total_keys_read; self.store_stat.last_report_ts = UnixSecs::now(); self.store_stat.region_bytes_written.flush(); self.store_stat.region_keys_written.flush(); self.store_stat.region_bytes_read.flush(); self.store_stat.region_keys_read.flush(); STORE_SIZE_GAUGE_VEC .with_label_values(&["capacity"]) .set(capacity as i64); STORE_SIZE_GAUGE_VEC .with_label_values(&["available"]) .set(available as i64); let f = self.pd_client.store_heartbeat(stats).map_err(|e| { error!("store heartbeat failed"; "err" => ?e); }); handle.spawn(f); } fn handle_report_batch_split(&self, handle: &Handle, regions: Vec<metapb::Region>) { let f = self.pd_client.report_batch_split(regions).map_err(|e| { debug!("report split failed"; "err" => ?e); }); handle.spawn(f); } fn handle_validate_peer( &self, handle: &Handle, local_region: metapb::Region, peer: metapb::Peer, merge_source: Option<u64>, ) { let router = self.router.clone(); let f = self .pd_client .get_region_by_id(local_region.get_id()) .then(move |resp| { match resp { Ok(Some(pd_region)) => { if is_epoch_stale( pd_region.get_region_epoch(), local_region.get_region_epoch(), ) { // The local Region epoch is fresher than Region epoch in PD // This means the Region info in PD is not updated to the latest even // after `max_leader_missing_duration`. Something is wrong in the system. // Just add a log here for this situation. info!( "local region epoch is greater the \ region epoch in PD ignore validate peer"; "region_id" => local_region.get_id(), "peer_id" => peer.get_id(), "local_region_epoch" => ?local_region.get_region_epoch(), "pd_region_epoch" => ?pd_region.get_region_epoch() ); PD_VALIDATE_PEER_COUNTER_VEC .with_label_values(&["region epoch error"]) .inc(); return Ok(()); } if pd_region .get_peers() .iter() .all(|p| p.get_id() != peer.get_id()) { // Peer is not a member of this Region anymore. Probably it's removed out. // Send it a raft massage to destroy it since it's obsolete. info!( "peer is not a valid member of region, to be \ destroyed soon"; "region_id" => local_region.get_id(), "peer_id" => peer.get_id(), "pd_region" => ?pd_region ); PD_VALIDATE_PEER_COUNTER_VEC .with_label_values(&["peer stale"]) .inc(); if let Some(source) = merge_source { send_merge_fail(&router, source, peer); } else { send_destroy_peer_message(&router, local_region, peer, pd_region); } return Ok(()); } info!( "peer is still valid a member of region"; "region_id" => local_region.get_id(), "peer_id" => peer.get_id(), "pd_region" => ?pd_region ); PD_VALIDATE_PEER_COUNTER_VEC .with_label_values(&["peer valid"]) .inc(); } Ok(None) => { // splitted Region has not yet reported to PD. // TODO: handle merge } Err(e) => { error!("get region failed"; "err" => ?e); } } Ok(()) }); handle.spawn(f); } fn schedule_heartbeat_receiver(&mut self, handle: &Handle) { let router = self.router.clone(); let store_id = self.store_id; let f = self .pd_client .handle_region_heartbeat_response(self.store_id, move |mut resp| { let region_id = resp.get_region_id(); let epoch = resp.take_region_epoch(); let peer = resp.take_target_peer(); if resp.has_change_peer() { PD_HEARTBEAT_COUNTER_VEC .with_label_values(&["change peer"]) .inc(); let mut change_peer = resp.take_change_peer(); info!( "try to change peer"; "region_id" => region_id, "change_type" => ?change_peer.get_change_type(), "peer" => ?change_peer.get_peer() ); let req = new_change_peer_request( change_peer.get_change_type(), change_peer.take_peer(), ); send_admin_request(&router, region_id, epoch, peer, req, Callback::None); } else if resp.has_transfer_leader() { PD_HEARTBEAT_COUNTER_VEC .with_label_values(&["transfer leader"]) .inc(); let mut transfer_leader = resp.take_transfer_leader(); info!( "try to transfer leader"; "region_id" => region_id, "from_peer" => ?peer, "to_peer" => ?transfer_leader.get_peer() ); let req = new_transfer_leader_request(transfer_leader.take_peer()); send_admin_request(&router, region_id, epoch, peer, req, Callback::None); } else if resp.has_split_region() { PD_HEARTBEAT_COUNTER_VEC .with_label_values(&["split region"]) .inc(); let mut split_region = resp.take_split_region(); info!("try to split"; "region_id" => region_id, "region_epoch" => ?epoch); let msg = if split_region.get_policy() == pdpb::CheckPolicy::Usekey { CasualMessage::SplitRegion{ region_epoch: epoch, split_keys: split_region.take_keys().into(), callback: Callback::None, } } else { CasualMessage::HalfSplitRegion { region_epoch: epoch, policy: split_region.get_policy(), } }; if let Err(e) = router.send(region_id, PeerMsg::CasualMessage(msg)) { error!("send halfsplit request failed"; "region_id" => region_id, "err" => ?e); } } else if resp.has_merge() { PD_HEARTBEAT_COUNTER_VEC.with_label_values(&["merge"]).inc(); let merge = resp.take_merge(); info!("try to merge"; "region_id" => region_id, "merge" => ?merge); let req = new_merge_request(merge); send_admin_request(&router, region_id, epoch, peer, req, Callback::None) } else { PD_HEARTBEAT_COUNTER_VEC.with_label_values(&["noop"]).inc(); } }) .map_err(|e| panic!("unexpected error: {:?}", e)) .map(move |_| { info!( "region heartbeat response handler exit"; "store_id" => store_id, ) }); handle.spawn(f); self.is_hb_receiver_scheduled = true; } fn handle_read_stats(&mut self, read_stats: HashMap<u64, FlowStatistics>) { for (region_id, stats) in read_stats { let peer_stat = self .region_peers .entry(region_id) .or_insert_with(PeerStat::default); peer_stat.read_bytes += stats.read_bytes as u64; peer_stat.read_keys += stats.read_keys as u64; self.store_stat.engine_total_bytes_read += stats.read_bytes as u64; self.store_stat.engine_total_keys_read += stats.read_keys as u64; } } fn handle_destroy_peer(&mut self, region_id: u64) { match self.region_peers.remove(&region_id) { None => {} Some(_) => info!("remove peer statistic record in pd"; "region_id" => region_id), } } fn handle_store_infos( &mut self, cpu_usages: RecordPairVec, read_io_rates: RecordPairVec, write_io_rates: RecordPairVec, ) { self.store_stat.store_cpu_usages = cpu_usages; self.store_stat.store_read_io_rates = read_io_rates; self.store_stat.store_write_io_rates = write_io_rates; } fn handle_refresh_config(&mut self, handle: &Handle) { let config_handler = &mut self.config_handler; info!( "refresh config"; "component id" => config_handler.get_id(), "version" => ?config_handler.get_version() ); if let Err(e) = config_handler.refresh_config(self.pd_client.clone()) { error!( "failed to refresh config"; "component id" => config_handler.get_id(), "version" => ?config_handler.get_version(), "err" => ?e ) } let scheduler = self.scheduler.clone(); let when = Instant::now() + config_handler.get_refresh_interval(); let f = Delay::new(when) .map_err(|e| warn!("timeout timer delay errored"; "err" => ?e)) .then(move |_| { if let Err(e) = scheduler.schedule(Task::RefreshConfig) { error!("failed to schedule refresh config task"; "err" => ?e) } Ok(()) }); handle.spawn(f); } } impl<T: PdClient> Runnable<Task> for Runner<T> { fn run(&mut self, task: Task, handle: &Handle) { debug!("executing task"; "task" => %task); if !self.is_hb_receiver_scheduled { self.schedule_heartbeat_receiver(handle); } match task { Task::AskSplit { region, split_key, peer, right_derive, callback, } => self.handle_ask_split(handle, region, split_key, peer, right_derive, callback), Task::AskBatchSplit { region, split_keys, peer, right_derive, callback, } => self.handle_ask_batch_split( handle, region, split_keys, peer, right_derive, callback, ), Task::Heartbeat { term, region, peer, down_peers, pending_peers, written_bytes, written_keys, approximate_size, approximate_keys, } => { let approximate_size = approximate_size.unwrap_or_else(|| { get_region_approximate_size(&self.db, &region).unwrap_or_default() }); let approximate_keys = approximate_keys.unwrap_or_else(|| { get_region_approximate_keys(&self.db, &region).unwrap_or_default() }); let ( read_bytes_delta, read_keys_delta, written_bytes_delta, written_keys_delta, last_report_ts, ) = { let peer_stat = self .region_peers .entry(region.get_id()) .or_insert_with(PeerStat::default); let read_bytes_delta = peer_stat.read_bytes - peer_stat.last_read_bytes; let read_keys_delta = peer_stat.read_keys - peer_stat.last_read_keys; let written_bytes_delta = written_bytes - peer_stat.last_written_bytes; let written_keys_delta = written_keys - peer_stat.last_written_keys; let mut last_report_ts = peer_stat.last_report_ts; peer_stat.last_written_bytes = written_bytes; peer_stat.last_written_keys = written_keys; peer_stat.last_read_bytes = peer_stat.read_bytes; peer_stat.last_read_keys = peer_stat.read_keys; peer_stat.last_report_ts = UnixSecs::now(); if last_report_ts.is_zero() { last_report_ts = self.start_ts; } ( read_bytes_delta, read_keys_delta, written_bytes_delta, written_keys_delta, last_report_ts, ) }; self.handle_heartbeat( handle, term, region, peer, RegionStat { down_peers, pending_peers, written_bytes: written_bytes_delta, written_keys: written_keys_delta, read_bytes: read_bytes_delta, read_keys: read_keys_delta, approximate_size, approximate_keys, last_report_ts, }, ) } Task::StoreHeartbeat { stats, store_info } => { self.handle_store_heartbeat(handle, stats, store_info) } Task::ReportBatchSplit { regions } => self.handle_report_batch_split(handle, regions), Task::ValidatePeer { region, peer, merge_source, } => self.handle_validate_peer(handle, region, peer, merge_source), Task::ReadStats { read_stats } => self.handle_read_stats(read_stats), Task::DestroyPeer { region_id } => self.handle_destroy_peer(region_id), Task::StoreInfos { cpu_usages, read_io_rates, write_io_rates, } => self.handle_store_infos(cpu_usages, read_io_rates, write_io_rates), Task::RefreshConfig => self.handle_refresh_config(handle), }; } fn shutdown(&mut self) { self.stats_monitor.stop(); } } fn new_change_peer_request(change_type: ConfChangeType, peer: metapb::Peer) -> AdminRequest { let mut req = AdminRequest::default(); req.set_cmd_type(AdminCmdType::ChangePeer); req.mut_change_peer().set_change_type(change_type); req.mut_change_peer().set_peer(peer); req } fn new_split_region_request( split_key: Vec<u8>, new_region_id: u64, peer_ids: Vec<u64>, right_derive: bool, ) -> AdminRequest { let mut req = AdminRequest::default(); req.set_cmd_type(AdminCmdType::Split); req.mut_split().set_split_key(split_key); req.mut_split().set_new_region_id(new_region_id); req.mut_split().set_new_peer_ids(peer_ids); req.mut_split().set_right_derive(right_derive); req } fn new_batch_split_region_request( split_keys: Vec<Vec<u8>>, ids: Vec<pdpb::SplitId>, right_derive: bool, ) -> AdminRequest { let mut req = AdminRequest::default(); req.set_cmd_type(AdminCmdType::BatchSplit); req.mut_splits().set_right_derive(right_derive); let mut requests = Vec::with_capacity(ids.len()); for (mut id, key) in ids.into_iter().zip(split_keys) { let mut split = SplitRequest::default(); split.set_split_key(key); split.set_new_region_id(id.get_new_region_id()); split.set_new_peer_ids(id.take_new_peer_ids()); requests.push(split); } req.mut_splits().set_requests(requests.into()); req } fn new_transfer_leader_request(peer: metapb::Peer) -> AdminRequest { let mut req = AdminRequest::default(); req.set_cmd_type(AdminCmdType::TransferLeader); req.mut_transfer_leader().set_peer(peer); req } fn new_merge_request(merge: pdpb::Merge) -> AdminRequest { let mut req = AdminRequest::default(); req.set_cmd_type(AdminCmdType::PrepareMerge); req.mut_prepare_merge() .set_target(merge.get_target().to_owned()); req } fn send_admin_request( router: &RaftRouter, region_id: u64, epoch: metapb::RegionEpoch, peer: metapb::Peer, request: AdminRequest, callback: Callback<RocksEngine>, ) { let cmd_type = request.get_cmd_type(); let mut req = RaftCmdRequest::default(); req.mut_header().set_region_id(region_id); req.mut_header().set_region_epoch(epoch); req.mut_header().set_peer(peer); req.set_admin_request(request); if let Err(e) = router.send_raft_command(RaftCommand::new(req, callback)) { error!( "send request failed"; "region_id" => region_id, "cmd_type" => ?cmd_type, "err" => ?e, ); } } /// Sends merge fail message to gc merge source. fn send_merge_fail(router: &RaftRouter, source_region_id: u64, target: metapb::Peer) { let target_id = target.get_id(); if let Err(e) = router.send( source_region_id, PeerMsg::CasualMessage(CasualMessage::MergeResult { target, stale: true, }), ) { error!( "source region report merge failed"; "region_id" => source_region_id, "targe_region_id" => target_id, "err" => ?e, ); } } /// Sends a raft message to destroy the specified stale Peer fn send_destroy_peer_message( router: &RaftRouter, local_region: metapb::Region, peer: metapb::Peer, pd_region: metapb::Region, ) { let mut message = RaftMessage::default(); message.set_region_id(local_region.get_id()); message.set_from_peer(peer.clone()); message.set_to_peer(peer.clone()); message.set_region_epoch(pd_region.get_region_epoch().clone()); message.set_is_tombstone(true); if let Err(e) = router.send_raft_message(message) { error!( "send gc peer request failed"; "region_id" => local_region.get_id(), "err" => ?e ) } } #[cfg(not(target_os = "macos"))] #[cfg(test)] mod tests { use std::sync::Mutex; use std::time::Instant; use tikv_util::worker::FutureWorker; use super::*; struct RunnerTest { store_stat: Arc<Mutex<StoreStat>>, stats_monitor: StatsMonitor, } impl RunnerTest { fn new( interval: u64, scheduler: Scheduler<Task>, store_stat: Arc<Mutex<StoreStat>>, ) -> RunnerTest { let mut stats_monitor = StatsMonitor::new(Duration::from_secs(interval), scheduler.clone()); if let Err(e) = stats_monitor.start() { error!("failed to start stats collector, error = {:?}", e); } RunnerTest { store_stat, stats_monitor, } } fn handle_store_infos( &mut self, cpu_usages: RecordPairVec, read_io_rates: RecordPairVec, write_io_rates: RecordPairVec, ) { let mut store_stat = self.store_stat.lock().unwrap(); store_stat.store_cpu_usages = cpu_usages; store_stat.store_read_io_rates = read_io_rates; store_stat.store_write_io_rates = write_io_rates; } } impl Runnable<Task> for RunnerTest { fn run(&mut self, task: Task, _handle: &Handle) { if let Task::StoreInfos { cpu_usages, read_io_rates, write_io_rates, } = task { self.handle_store_infos(cpu_usages, read_io_rates, write_io_rates) }; } fn shutdown(&mut self) { self.stats_monitor.stop(); } } fn sum_record_pairs(pairs: &[pdpb::RecordPair]) -> u64 { let mut sum = 0; for record in pairs.iter() { sum += record.get_value(); } sum } #[test] fn test_collect_stats() { let mut pd_worker = FutureWorker::new("test-pd-worker"); let store_stat = Arc::new(Mutex::new(StoreStat::default())); let runner = RunnerTest::new(1, pd_worker.scheduler(), Arc::clone(&store_stat)); pd_worker.start(runner).unwrap(); let start = Instant::now(); loop { if (Instant::now() - start).as_secs() > 2 { break; } } let total_cpu_usages = sum_record_pairs(&store_stat.lock().unwrap().store_cpu_usages); assert!(total_cpu_usages > 90); pd_worker.stop(); } }
35.787402
124
0.510402
48e2da083f6e0d7997a2e806101a57efe5d01bfc
13,269
// Copyright 2020, The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use std::{iter, sync::Arc}; use log::*; use tari_shutdown::ShutdownSignal; use tokio::{ io::{AsyncRead, AsyncWrite}, sync::{broadcast, mpsc}, }; use super::{CommsBuilderError, CommsShutdown}; use crate::{ connection_manager::{ ConnectionManager, ConnectionManagerEvent, ConnectionManagerRequest, ConnectionManagerRequester, ListenerInfo, }, connectivity::{ConnectivityEventRx, ConnectivityManager, ConnectivityRequest, ConnectivityRequester}, multiaddr::Multiaddr, noise::NoiseConfig, peer_manager::{NodeIdentity, PeerManager}, protocol::{ ProtocolExtension, ProtocolExtensionContext, ProtocolExtensions, ProtocolId, ProtocolNotificationTx, Protocols, }, tor, transports::Transport, CommsBuilder, Substream, }; const LOG_TARGET: &str = "comms::node"; /// Contains the built comms services pub struct UnspawnedCommsNode { pub(super) node_identity: Arc<NodeIdentity>, pub(super) builder: CommsBuilder, pub(super) connection_manager_request_rx: mpsc::Receiver<ConnectionManagerRequest>, pub(super) connection_manager_requester: ConnectionManagerRequester, pub(super) connectivity_requester: ConnectivityRequester, pub(super) connectivity_rx: mpsc::Receiver<ConnectivityRequest>, pub(super) peer_manager: Arc<PeerManager>, pub(super) protocol_extensions: ProtocolExtensions, pub(super) protocols: Protocols<Substream>, pub(super) shutdown_signal: ShutdownSignal, } impl UnspawnedCommsNode { /// Add an RPC server/router in this instance of Tari comms. /// /// ```compile_fail /// # use tari_comms::CommsBuilder; /// # use tari_comms::protocol::rpc::RpcServer; /// let server = RpcServer::new().add_service(MyService).add_service(AnotherService); /// CommsBuilder::new().add_rpc_service(server).build(); /// ``` #[cfg(feature = "rpc")] pub fn add_rpc_server<T: ProtocolExtension + 'static>(mut self, rpc: T) -> Self { // Rpc router is treated the same as any other `ProtocolExtension` however this method may make it clearer for // users that this is the correct way to add the RPC server self.protocol_extensions.add(rpc); self } /// Adds [ProtocolExtensions](crate::protocol::ProtocolExtensions) to this node. pub fn add_protocol_extensions(mut self, extensions: ProtocolExtensions) -> Self { self.protocol_extensions.extend(extensions); self } /// Adds an implementation of [ProtocolExtension](crate::protocol::ProtocolExtension) to this node. /// This is used to add custom protocols to Tari comms. pub fn add_protocol_extension<T: ProtocolExtension + 'static>(mut self, extension: T) -> Self { self.protocol_extensions.add(extension); self } /// Registers custom ProtocolIds and mpsc notifier. A [ProtocolNotification](crate::protocol::ProtocolNotification) /// will be sent on that channel whenever a remote peer requests to speak the given protocols. pub fn add_protocol<I: AsRef<[ProtocolId]>>( mut self, protocol: I, notifier: &ProtocolNotificationTx<Substream>, ) -> Self { self.protocols.add(protocol, notifier); self } /// Set the listener address. This is an alias to `CommsBuilder::with_listener_address`. pub fn with_listener_address(mut self, listener_address: Multiaddr) -> Self { self.builder = self.builder.with_listener_address(listener_address); self } /// Set the tor hidden service controller to associate with this comms instance pub fn with_hidden_service_controller(mut self, hidden_service_ctl: tor::HiddenServiceController) -> Self { self.builder.hidden_service_ctl = Some(hidden_service_ctl); self } /// Spawn a new node using the specified [Transport](crate::transports::Transport). pub async fn spawn_with_transport<TTransport>(self, transport: TTransport) -> Result<CommsNode, CommsBuilderError> where TTransport: Transport + Unpin + Send + Sync + Clone + 'static, TTransport::Output: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static, { let UnspawnedCommsNode { builder, connection_manager_request_rx, mut connection_manager_requester, connectivity_requester, connectivity_rx, node_identity, shutdown_signal, peer_manager, protocol_extensions, protocols, } = self; let CommsBuilder { dial_backoff, hidden_service_ctl, connection_manager_config, connectivity_config, .. } = builder; //---------------------------------- Connectivity Manager --------------------------------------------// let connectivity_manager = ConnectivityManager { config: connectivity_config, request_rx: connectivity_rx, event_tx: connectivity_requester.get_event_publisher(), connection_manager: connection_manager_requester.clone(), node_identity: node_identity.clone(), peer_manager: peer_manager.clone(), shutdown_signal: shutdown_signal.clone(), }; let mut ext_context = ProtocolExtensionContext::new( connectivity_requester.clone(), peer_manager.clone(), shutdown_signal.clone(), ); debug!( target: LOG_TARGET, "Installing {} protocol extension(s)", protocol_extensions.len() ); protocol_extensions.install_all(&mut ext_context)?; //---------------------------------- Connection Manager --------------------------------------------// let noise_config = NoiseConfig::new(node_identity.clone()); let mut connection_manager = ConnectionManager::new( connection_manager_config, transport, noise_config, dial_backoff, connection_manager_request_rx, node_identity.clone(), peer_manager.clone(), connection_manager_requester.get_event_publisher(), shutdown_signal.clone(), ); ext_context.register_complete_signal(connection_manager.complete_signal()); connection_manager.add_protocols(ext_context.take_protocols().expect("Protocols already taken")); connection_manager.add_protocols(protocols); //---------------------------------- Spawn Actors --------------------------------------------// connectivity_manager.spawn(); connection_manager.spawn(); debug!(target: LOG_TARGET, "Hello from comms!"); info!( target: LOG_TARGET, "Your node's public key is '{}'", node_identity.public_key() ); info!( target: LOG_TARGET, "Your node's network ID is '{}'", node_identity.node_id() ); let listening_info = connection_manager_requester.wait_until_listening().await?; let mut hidden_service = None; if let Some(mut ctl) = hidden_service_ctl { ctl.set_proxied_addr(listening_info.bind_address()); let hs = ctl.create_hidden_service().await?; let onion_addr = hs.get_onion_address(); if node_identity.public_address() != onion_addr { node_identity.set_public_address(onion_addr); } hidden_service = Some(hs); } info!( target: LOG_TARGET, "Your node's public address is '{}'", node_identity.public_address() ); Ok(CommsNode { shutdown_signal, connection_manager_requester, connectivity_requester, listening_info, node_identity, peer_manager, hidden_service, complete_signals: ext_context.drain_complete_signals(), }) } /// Return a cloned atomic reference of the PeerManager pub fn peer_manager(&self) -> Arc<PeerManager> { Arc::clone(&self.peer_manager) } /// Return a cloned atomic reference of the NodeIdentity pub fn node_identity(&self) -> Arc<NodeIdentity> { Arc::clone(&self.node_identity) } /// Return an owned copy of a ConnectivityRequester. This is the async interface to the ConnectivityManager pub fn connectivity(&self) -> ConnectivityRequester { self.connectivity_requester.clone() } /// Returns an owned copy`ShutdownSignal` pub fn shutdown_signal(&self) -> ShutdownSignal { self.shutdown_signal.clone() } } /// CommsNode is a handle to a comms node. /// /// It allows communication with the internals of tari_comms. #[derive(Clone)] pub struct CommsNode { /// The `ShutdownSignal` for this node. Use `wait_until_shutdown` to asynchronously block until the /// shutdown signal is triggered. shutdown_signal: ShutdownSignal, /// Requester object for the ConnectionManager connection_manager_requester: ConnectionManagerRequester, /// Requester for the ConnectivityManager connectivity_requester: ConnectivityRequester, /// Node identity for this node node_identity: Arc<NodeIdentity>, /// Shared PeerManager instance peer_manager: Arc<PeerManager>, /// The bind addresses of the listener(s) listening_info: ListenerInfo, /// `Some` if the comms node is configured to run via a hidden service, otherwise `None` hidden_service: Option<tor::HiddenService>, /// The 'reciprocal' shutdown signals for each comms service complete_signals: Vec<ShutdownSignal>, } impl CommsNode { /// Get a subscription to `ConnectionManagerEvent`s pub fn subscribe_connection_manager_events(&self) -> broadcast::Receiver<Arc<ConnectionManagerEvent>> { self.connection_manager_requester.get_event_subscription() } /// Get a subscription to `ConnectivityEvent`s pub fn subscribe_connectivity_events(&self) -> ConnectivityEventRx { self.connectivity_requester.get_event_subscription() } /// Return a cloned atomic reference of the PeerManager pub fn peer_manager(&self) -> Arc<PeerManager> { Arc::clone(&self.peer_manager) } /// Return a cloned atomic reference of the NodeIdentity pub fn node_identity(&self) -> Arc<NodeIdentity> { Arc::clone(&self.node_identity) } /// Return a reference to the NodeIdentity pub fn node_identity_ref(&self) -> &NodeIdentity { &self.node_identity } /// Return the Ip/Tcp address that this node is listening on pub fn listening_address(&self) -> &Multiaddr { self.listening_info.bind_address() } /// Return the Ip/Tcp address that this node is listening on pub fn hidden_service(&self) -> Option<&tor::HiddenService> { self.hidden_service.as_ref() } /// Return a handle that is used to call the connectivity service. pub fn connectivity(&self) -> ConnectivityRequester { self.connectivity_requester.clone() } /// Returns a new `ShutdownSignal` pub fn shutdown_signal(&self) -> ShutdownSignal { self.shutdown_signal.clone() } /// Wait for comms to shutdown once the shutdown signal is triggered and for comms services to shut down. /// The object is consumed to ensure that no handles/channels are kept after shutdown pub fn wait_until_shutdown(self) -> CommsShutdown { CommsShutdown::new(iter::once(self.shutdown_signal).chain(self.complete_signals)) } }
38.912023
119
0.664029
f9952c0dc540d9a8acbec97facdcdbf4dbcdfe4b
4,027
extern crate polyhorn_yoga as yoga; use yoga::{ Align, Direction, FlexDirection, Justify, Node, Overflow, PositionType, StyleUnit, Wrap, }; #[test] fn test_assert_default_values() { let root = Node::new(); assert_eq!(root.get_child_count(), 0); assert!(root.get_child(1).is_null()); assert_eq!(Direction::Inherit, root.get_style_direction()); assert_eq!(FlexDirection::Column, root.get_flex_direction()); assert_eq!(Justify::FlexStart, root.get_justify_content()); assert_eq!(Align::FlexStart, root.get_align_content()); assert_eq!(Align::Stretch, root.get_align_items()); assert_eq!(Align::Auto, root.get_align_self()); assert_eq!(PositionType::Static, root.get_position_type()); assert_eq!(Wrap::NoWrap, root.get_flex_wrap()); assert_eq!(Overflow::Visible, root.get_overflow()); assert_eq!(0.0, root.get_flex_grow()); assert_eq!(0.0, root.get_flex_shrink()); assert_eq!(StyleUnit::Auto, root.get_flex_basis()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_position_left()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_position_top()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_position_right()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_position_bottom()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_position_start()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_position_end()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_margin_left()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_margin_top()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_margin_right()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_margin_bottom()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_margin_start()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_margin_end()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_padding_left()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_padding_top()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_padding_right()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_padding_bottom()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_padding_start()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_padding_end()); assert!(root.get_style_border_left().is_nan()); assert!(root.get_style_border_top().is_nan()); assert!(root.get_style_border_right().is_nan()); assert!(root.get_style_border_bottom().is_nan()); assert!(root.get_style_border_start().is_nan()); assert!(root.get_style_border_end().is_nan()); assert_eq!(StyleUnit::Auto, root.get_style_width()); assert_eq!(StyleUnit::Auto, root.get_style_height()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_min_width()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_min_height()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_max_width()); assert_eq!(StyleUnit::UndefinedValue, root.get_style_max_height()); assert_eq!(0.0, root.get_layout_left()); assert_eq!(0.0, root.get_layout_right()); assert_eq!(0.0, root.get_layout_top()); assert_eq!(0.0, root.get_layout_bottom()); assert_eq!(0.0, root.get_layout_margin_left()); assert_eq!(0.0, root.get_layout_margin_right()); assert_eq!(0.0, root.get_layout_margin_top()); assert_eq!(0.0, root.get_layout_margin_bottom()); assert_eq!(0.0, root.get_layout_padding_left()); assert_eq!(0.0, root.get_layout_padding_right()); assert_eq!(0.0, root.get_layout_padding_top()); assert_eq!(0.0, root.get_layout_padding_bottom()); assert_eq!(0.0, root.get_layout_border_left()); assert_eq!(0.0, root.get_layout_border_right()); assert_eq!(0.0, root.get_layout_border_top()); assert_eq!(0.0, root.get_layout_border_bottom()); assert!(root.get_layout_width().is_nan()); assert!(root.get_layout_height().is_nan()); assert_eq!(Direction::Inherit, root.get_layout_direction()); } #[test] fn test_assert_webdefault_values() { // TODO - unimplemented for now assert!(true); } #[test] fn test_assert_webdefault_values_reset() { // TODO - unimplemented for now assert!(true); }
41.091837
89
0.772039
d7d4d8b2413ced9f18cf17a04a6b9a7f41f285f3
2,145
mod sphere; pub use sphere::*; mod plane; pub use plane::*; mod triangle; pub use triangle::*; mod bound; pub use bound::*; mod point_light; pub use point_light::*; use crate::types::*; // A trait for types that can be in Objects. pub trait Surface { // Takes in a ray and performs an intersection test // on itself. If the ray intersects the object, // returns the distance to the intersection point. fn intersect(&self, ray: Ray) -> Option<f32>; // Takes in a point (assumed to be on the object's surface) // and returns the normal vector off of that point. fn normal(&self, point: Point3f) -> Unit3f; // Takes in a point (assumed to be on the object's surface) // and returns the texture information on that point. fn get_texture(&self, point: Point3f) -> Texture; // Creates a bounding sphere around the object. fn bound(&self) -> Bound; } pub struct Object { pub surface: Box<dyn Surface>, bound: Bound } impl Object { // Creates a new object with the default bounding sphere. pub fn new(surface: impl 'static + Surface) -> Self { let bound = surface.bound(); Object { surface: Box::new(surface), bound } } pub fn intersect(&self, ray: Ray) -> Option<f32> { if self.bound.is_intersected(ray) { self.surface.intersect(ray) } else { None } } pub fn normal(&self, point: Point3f) -> Unit3f { self.surface.normal(point) } pub fn get_texture(&self, point: Point3f) -> Texture { self.surface.get_texture(point) } } pub trait Light { // Determine if the light is able to illuminate the point. fn check_shadow(&self, point: Point3f, objects: &Vec<Object>) -> bool; // Compute color on a point. fn get_color(&self, point: Point3f) -> Color; // Compute intensity on a point. fn intensity(&self, point: Point3f) -> f32; // Return the direction from the point to the light source. fn direction(&self, point: Point3f) -> Unit3f; } pub struct Scene { pub objects: Vec<Object>, pub lights: Vec<Box<dyn Light>>, pub background: Color }
28.986486
92
0.641492
089562566e4282139557845c18e1a2f242b2f8ab
3,343
use common::Result; use packets::icmp::v6::{Icmpv6, Icmpv6Packet, Icmpv6Payload, Icmpv6Type, Icmpv6Types}; use packets::ip::v6::Ipv6Packet; use packets::{buffer, Fixed, Packet}; use std::fmt; /* From https://tools.ietf.org/html/rfc4443#section-4.1 Echo Request Message 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Code | Checksum | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Identifier | Sequence Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Data ... +-+-+-+-+- Identifier An identifier to aid in matching Echo Replies to this Echo Request. May be zero. Sequence Number A sequence number to aid in matching Echo Replies to this Echo Request. May be zero. Data Zero or more octets of arbitrary data. */ /// Echo request message #[derive(Default, Debug)] #[repr(C, packed)] pub struct EchoRequest { identifier: u16, seq_no: u16, } impl Icmpv6Payload for EchoRequest { fn msg_type() -> Icmpv6Type { Icmpv6Types::EchoRequest } } impl<E: Ipv6Packet> Icmpv6<E, EchoRequest> { #[inline] pub fn identifier(&self) -> u16 { u16::from_be(self.payload().identifier) } #[inline] pub fn set_identifier(&mut self, identifier: u16) { self.payload_mut().identifier = u16::to_be(identifier); } #[inline] pub fn seq_no(&self) -> u16 { u16::from_be(self.payload().seq_no) } #[inline] pub fn set_seq_no(&mut self, seq_no: u16) { self.payload_mut().seq_no = u16::to_be(seq_no); } /// Returns the offset where the data field in the message body starts #[inline] fn data_offset(&self) -> usize { self.payload_offset() + EchoRequest::size() } /// Returns the length of the data field in the message body #[inline] fn data_len(&self) -> usize { self.payload_len() - EchoRequest::size() } #[inline] pub fn data(&self) -> &[u8] { if let Ok(data) = buffer::read_slice(self.mbuf(), self.data_offset(), self.data_len()) { unsafe { &(*data) } } else { unreachable!() } } #[inline] pub fn set_data(&mut self, data: &[u8]) -> Result<()> { buffer::realloc( self.mbuf(), self.data_offset(), data.len() as isize - self.data_len() as isize, )?; buffer::write_slice(self.mbuf(), self.data_offset(), data)?; Ok(()) } } impl<E: Ipv6Packet> fmt::Display for Icmpv6<E, EchoRequest> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "type: {}, code: {}, checksum: 0x{:04x}, identifier: {}, seq_no: {}", self.msg_type(), self.code(), self.checksum(), self.identifier(), self.seq_no(), ) } } #[cfg(test)] mod tests { use super::*; #[test] fn size_of_echo_request() { assert_eq!(4, EchoRequest::size()); } }
27.628099
96
0.498953
7636557708c38bd3f1bd0b9aaa02264e741c822e
2,471
use crate::core::Method; use crate::core::{ValueType, OHLCV}; use crate::prelude::Candle; use std::borrow::BorrowMut; /// Implements some methods for sequence manipulations. pub trait Sequence<T>: AsRef<[T]> { /// Validates the sequence. fn validate(&self) -> bool; /// Applies [`Method`](crate::core::Method) on the slice in-place. fn apply<'a, M>(&'a mut self, mut method: M) where M: Method<'a, Input = T, Output = T> + BorrowMut<M> + 'a, Self: AsMut<[T]>, T: Copy, { self.as_mut().iter_mut().for_each(|x| *x = method.next(*x)); } /// Calls [`Method`](crate::core::Method) over the slice and returns `Vec` of result values. fn call<'a, M>(&self, method: M) -> Vec<M::Output> where M: Method<'a, Input = T> + BorrowMut<M> + 'a; /// Returns a reference to the first value in the sequence or `None` if it's empty. fn get_initial_value(&self) -> Option<&T> { self.as_ref().first() } /// Converts timeframe of the series fn collapse_timeframe(&self, size: usize, continuous: bool) -> Vec<Candle> where T: OHLCV, { fn fold<T: OHLCV>(folded: Candle, next: &T) -> Candle { Candle { high: folded.high.max(next.high()), low: folded.low.min(next.low()), close: next.close(), volume: folded.volume + next.volume(), ..folded } } fn window<T: OHLCV>(window: &[T]) -> Candle { let first = window.first().unwrap(); let initial = Candle { open: first.open(), high: first.high(), low: first.low(), close: first.close(), volume: first.volume(), }; window.iter().skip(1).fold(initial, fold) } self.as_ref() .windows(size) .step_by(if continuous { 1 } else { size }) .map(window) .collect() } } impl<Q: AsRef<[ValueType]>> Sequence<ValueType> for Q { fn validate(&self) -> bool { self.as_ref().iter().copied().all(ValueType::is_finite) } fn call<'a, M>(&self, mut method: M) -> Vec<M::Output> where M: Method<'a, Input = ValueType> + BorrowMut<M> + 'a, { let method = method.borrow_mut(); let inputs = self.as_ref(); inputs.iter().map(|&x| method.next(x)).collect() } } impl<T: OHLCV + Clone, Q: AsRef<[T]>> Sequence<T> for Q { fn validate(&self) -> bool { self.as_ref().iter().all(OHLCV::validate) } fn call<'a, M>(&self, mut method: M) -> Vec<M::Output> where M: Method<'a, Input = T> + BorrowMut<M> + 'a, { let method = method.borrow_mut(); let input = self.as_ref(); input.iter().cloned().map(|x| method.next(x)).collect() } }
25.214286
93
0.614326
380ee005d0302232f834732149ce55b2529c5432
6,621
use crate::theory::contraint_db::Enabler; use crate::theory::{Timepoint, W}; use aries_core::{BoundValueAdd, Lit, VarBound}; /// A unique identifier for an edge in the STN. /// An edge and its negation share the same `base_id` but differ by the `is_negated` property. /// /// For instance, valid edge ids: /// - `a - b <= 10` /// - base_id: 3 /// - negated: false /// - `a - b > 10` # negation of the previous one /// - base_id: 3 # same /// - negated: true # inverse /// - `a - b <= 20` # unrelated /// - base_id: 4 /// - negated: false #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)] pub struct EdgeId(u32); impl EdgeId { #[inline] pub fn new(base_id: u32, negated: bool) -> EdgeId { if negated { EdgeId((base_id << 1) + 1) } else { EdgeId(base_id << 1) } } #[inline] pub fn base_id(&self) -> u32 { self.0 >> 1 } #[inline] pub fn is_negated(&self) -> bool { self.0 & 0x1 == 1 } /// Id of the forward (from source to target) view of this edge pub(in crate::theory) fn forward(self) -> PropagatorId { PropagatorId::forward(self) } /// Id of the backward view (from target to source) of this edge pub(in crate::theory) fn backward(self) -> PropagatorId { PropagatorId::backward(self) } } impl std::ops::Not for EdgeId { type Output = Self; #[inline] fn not(self) -> Self::Output { EdgeId(self.0 ^ 0x1) } } impl From<EdgeId> for u32 { fn from(e: EdgeId) -> Self { e.0 } } impl From<u32> for EdgeId { fn from(id: u32) -> Self { EdgeId(id) } } impl From<EdgeId> for usize { fn from(e: EdgeId) -> Self { e.0 as usize } } impl From<usize> for EdgeId { fn from(id: usize) -> Self { EdgeId(id as u32) } } /// An edge in the STN, representing the constraint `target - source <= weight` /// An edge can be either in canonical form or in negated form. /// Given to edges (tgt - src <= w) and (tgt -src > w) one will be in canonical form and /// the other in negated form. #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)] pub struct Edge { pub source: Timepoint, pub target: Timepoint, pub weight: W, } impl Edge { pub fn new(source: Timepoint, target: Timepoint, weight: W) -> Edge { Edge { source, target, weight } } pub fn is_negated(&self) -> bool { !self.is_canonical() } pub fn is_canonical(&self) -> bool { self.source < self.target || self.source == self.target && self.weight >= 0 } // not(b - a <= 6) // = b - a > 6 // = a -b < -6 // = a - b <= -7 // // not(a - b <= -7) // = a - b > -7 // = b - a < 7 // = b - a <= 6 pub fn negated(&self) -> Self { Edge { source: self.target, target: self.source, weight: -self.weight - 1, } } } /// A `Propagator` represents the fact that an update on the `source` bound /// should be reflected on the `target` bound. /// /// From a classical STN edge `source -- weight --> target` there will be two `Propagator`s: /// - ub(source) = X implies ub(target) <= X + weight /// - lb(target) = X implies lb(source) >= X - weight #[derive(Clone, Debug)] pub(crate) struct Propagator { pub source: VarBound, pub target: VarBound, pub weight: BoundValueAdd, /// Non-empty if the constraint active (participates in propagation) /// If the enabler is Lit::TRUE, then the constraint can be assumed to be always active pub enabler: Option<Enabler>, /// A set of potential enablers for this constraint. /// The edge becomes active once one of its enablers becomes true pub enablers: Vec<Enabler>, } impl Propagator { /// source <= X => target <= X + weight pub fn forward(edge: Edge) -> Propagator { Propagator { source: VarBound::ub(edge.source), target: VarBound::ub(edge.target), weight: BoundValueAdd::on_ub(edge.weight), enabler: None, enablers: vec![], } } /// target >= X => source >= X - weight pub fn backward(edge: Edge) -> Propagator { Propagator { source: VarBound::lb(edge.target), target: VarBound::lb(edge.source), weight: BoundValueAdd::on_lb(-edge.weight), enabler: None, enablers: vec![], } } pub fn as_edge(&self) -> Edge { if self.source.is_ub() { debug_assert!(self.target.is_ub()); Edge { source: self.source.variable(), target: self.target.variable(), weight: self.weight.as_ub_add(), } } else { debug_assert!(self.target.is_lb()); Edge { source: self.target.variable(), target: self.source.variable(), weight: -self.weight.as_lb_add(), } } } } /// Represents an edge together with a particular propagation direction: /// - forward (source to target) /// - backward (target to source) #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)] pub(crate) struct PropagatorId(u32); impl PropagatorId { /// Forward view of the given edge pub fn forward(e: EdgeId) -> Self { PropagatorId(u32::from(e) << 1) } /// Backward view of the given edge pub fn backward(e: EdgeId) -> Self { PropagatorId((u32::from(e) << 1) + 1) } #[allow(unused)] pub fn is_forward(self) -> bool { (u32::from(self) & 0x1) == 0 } /// The edge underlying this projection pub fn edge(self) -> EdgeId { EdgeId::from(self.0 >> 1) } } impl From<PropagatorId> for usize { fn from(e: PropagatorId) -> Self { e.0 as usize } } impl From<usize> for PropagatorId { fn from(u: usize) -> Self { PropagatorId(u as u32) } } impl From<PropagatorId> for u32 { fn from(e: PropagatorId) -> Self { e.0 } } impl From<u32> for PropagatorId { fn from(u: u32) -> Self { PropagatorId(u) } } #[derive(Copy, Clone, Debug)] pub struct PropagatorTarget { pub target: VarBound, pub weight: BoundValueAdd, /// Literal that is true if and only if the edge must be present in the network. /// Note that handling of optional variables might allow and edge to propagate even it is not known /// to be present yet. pub presence: Lit, }
27.473029
103
0.561849
710fa232f816ffd3355fb06b9f013bc91ad9f1a5
1,295
use std::path::PathBuf; use anyhow::{Context, Result}; use clap::Args; use tokio::sync::broadcast; use crate::config::{ConfigOpts, ConfigOptsBuild, ConfigOptsServe, ConfigOptsWatch}; use crate::serve::ServeSystem; /// Build, watch & serve the Rust WASM app and all of its assets. #[derive(Args)] #[clap(name = "serve")] pub struct Serve { #[clap(flatten)] pub build: ConfigOptsBuild, #[clap(flatten)] pub watch: ConfigOptsWatch, #[clap(flatten)] pub serve: ConfigOptsServe, } impl Serve { #[tracing::instrument(level = "trace", skip(self, config))] pub async fn run(self, config: Option<PathBuf>) -> Result<()> { let (shutdown_tx, _) = broadcast::channel(1); let cfg = ConfigOpts::rtc_serve(self.build, self.watch, self.serve, config)?; let system = ServeSystem::new(cfg, shutdown_tx.clone()).await?; let system_handle = tokio::spawn(system.run()); let _res = tokio::signal::ctrl_c().await.context("error awaiting shutdown signal")?; tracing::debug!("received shutdown signal"); let _res = shutdown_tx.send(()); drop(shutdown_tx); // Ensure other components see the drop to avoid race conditions. system_handle.await.context("error awaiting system shutdown")??; Ok(()) } }
33.205128
92
0.658687
ac71a825739006ba0c27b810cb49e48a6ea6aa4e
24,037
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{ app::{MessageInternal, RenderOptions}, drawing::DisplayRotation, geometry::UintSize, input::ScenicInputHandler, message::Message, render::{ self, generic::{self, Backend}, ContextInner, }, view::{ strategies::base::{ViewStrategy, ViewStrategyPtr}, View, ViewAssistantContext, ViewAssistantPtr, ViewDetails, ViewKey, }, }; use anyhow::{Context, Error, Result}; use async_trait::async_trait; use fidl::endpoints::create_request_stream; use fidl_fuchsia_ui_gfx::{self as gfx}; use fidl_fuchsia_ui_input::SetHardKeyboardDeliveryCmd; use fidl_fuchsia_ui_views::{ViewRef, ViewRefControl, ViewToken}; use fuchsia_async::{self as fasync, OnSignals}; use fuchsia_component::client::connect_to_protocol; use fuchsia_framebuffer::{sysmem::BufferCollectionAllocator, FrameSet, FrameUsage, ImageId}; use fuchsia_scenic::{EntityNode, Image2, Material, Rectangle, SessionPtr, ShapeNode}; use fuchsia_trace::{self, duration, instant}; use fuchsia_zircon::{self as zx, Event, HandleBased, Signals, Time}; use futures::{channel::mpsc::UnboundedSender, TryStreamExt}; use std::collections::{BTreeMap, BTreeSet}; struct Plumber { pub size: UintSize, // TODO(fxbug.dev/77068): Remove this attribute. #[allow(dead_code)] pub buffer_count: usize, pub collection_id: u32, // TODO(fxbug.dev/77068): Remove this attribute. #[allow(dead_code)] pub first_image_id: u64, pub frame_set: FrameSet, pub image_indexes: BTreeMap<ImageId, u32>, pub images: BTreeMap<ImageId, Image2>, pub context: render::Context, } impl Plumber { async fn new( session: &SessionPtr, size: UintSize, pixel_format: fidl_fuchsia_sysmem::PixelFormatType, buffer_count: usize, collection_id: u32, first_image_id: u64, render_options: RenderOptions, ) -> Result<Plumber, Error> { let usage = if render_options.use_spinel { FrameUsage::Gpu } else { FrameUsage::Cpu }; let mut buffer_allocator = BufferCollectionAllocator::new( size.width, size.height, pixel_format, usage, buffer_count, )?; buffer_allocator.set_name(100, "CarnelianFramebuffer")?; let buffer_collection_token = buffer_allocator.duplicate_token().await?; session.lock().register_buffer_collection(collection_id, buffer_collection_token)?; let context_token = buffer_allocator.duplicate_token().await?; let context = render::Context { inner: if render_options.use_spinel { ContextInner::Spinel(generic::Spinel::new_context( context_token, size, DisplayRotation::Deg0, )) } else { ContextInner::Mold(generic::Mold::new_context( context_token, size, DisplayRotation::Deg0, )) }, }; let buffers = buffer_allocator.allocate_buffers(true).await.context("allocate_buffers")?; let mut image_ids = BTreeSet::new(); let mut image_indexes = BTreeMap::new(); let mut images = BTreeMap::new(); for index in 0..buffers.buffer_count as usize { let image_id = index + first_image_id as usize; image_ids.insert(image_id as u64); let uindex = index as u32; image_indexes.insert(image_id as u64, uindex); let image = Image2::new(session, size.width, size.height, collection_id, uindex); images.insert(image_id as u64, image); } let frame_set = FrameSet::new(image_ids); Ok(Plumber { size, buffer_count, collection_id, first_image_id, frame_set, image_indexes, images, context, }) } pub fn enter_retirement(&mut self, session: &SessionPtr) { session .lock() .deregister_buffer_collection(self.collection_id) .expect("deregister_buffer_collection"); } } const RENDER_BUFFER_COUNT: usize = 3; const DEFAULT_PRESENT_INTERVAL: i64 = (1_000_000_000.0 / 60.0) as i64; pub(crate) struct ScenicViewStrategy { #[allow(unused)] render_options: RenderOptions, #[allow(unused)] view: View, #[allow(unused)] root_node: EntityNode, session: SessionPtr, view_key: ViewKey, pending_present_count: usize, next_presentation_times: Vec<i64>, present_interval: i64, remaining_presents_in_flight_allowed: i64, render_timer_scheduled: bool, missed_frame: bool, app_sender: UnboundedSender<MessageInternal>, content_node: ShapeNode, content_material: Material, next_buffer_collection: u32, plumber: Option<Plumber>, retiring_plumbers: Vec<Plumber>, next_image_id: u64, input_handler: ScenicInputHandler, } impl ScenicViewStrategy { pub(crate) async fn new( key: ViewKey, session: &SessionPtr, render_options: RenderOptions, view_token: ViewToken, control_ref: ViewRefControl, view_ref: ViewRef, app_sender: UnboundedSender<MessageInternal>, ) -> Result<ViewStrategyPtr, Error> { let view_ref_key = fuchsia_scenic::duplicate_view_ref(&view_ref)?; let (view, root_node, content_material, content_node) = Self::create_scenic_resources(session, view_token, control_ref, view_ref); Self::request_hard_keys(session); Self::listen_for_session_events(session, &app_sender, key); Self::listen_for_key_events(view_ref_key, &app_sender, key)?; // This initial present is needed in order for session events to start flowing. Self::do_present(session, &app_sender, key, 0); let strat = ScenicViewStrategy { view, session: session.clone(), view_key: key, app_sender: app_sender.clone(), pending_present_count: 1, next_presentation_times: Vec::new(), present_interval: DEFAULT_PRESENT_INTERVAL, remaining_presents_in_flight_allowed: 3, render_timer_scheduled: false, missed_frame: false, root_node, render_options, content_node, content_material, plumber: None, retiring_plumbers: Vec::new(), next_buffer_collection: 1, next_image_id: 1, input_handler: ScenicInputHandler::new(), }; Ok(Box::new(strat)) } fn create_scenic_resources( session: &SessionPtr, view_token: ViewToken, control_ref: ViewRefControl, view_ref: ViewRef, ) -> (View, EntityNode, Material, ShapeNode) { let content_material = Material::new(session.clone()); let content_node = ShapeNode::new(session.clone()); content_node.set_material(&content_material); session.lock().flush(); let view = View::new3( session.clone(), view_token, control_ref, view_ref, Some(String::from("Carnelian View")), ); let root_node = EntityNode::new(session.clone()); root_node.add_child(&content_node); root_node.resource().set_event_mask(gfx::METRICS_EVENT_MASK); view.add_child(&root_node); (view, root_node, content_material, content_node) } fn request_hard_keys(session: &SessionPtr) { session.lock().enqueue(fidl_fuchsia_ui_scenic::Command::Input( fidl_fuchsia_ui_input::Command::SetHardKeyboardDelivery(SetHardKeyboardDeliveryCmd { delivery_request: true, }), )); } fn listen_for_session_events( session: &SessionPtr, app_sender: &UnboundedSender<MessageInternal>, key: ViewKey, ) { let event_sender = app_sender.clone(); let mut event_stream = session.lock().take_event_stream(); fasync::Task::local(async move { while let Some(event) = event_stream.try_next().await.expect("Failed to get next event") { match event { fidl_fuchsia_ui_scenic::SessionEvent::OnFramePresented { frame_presented_info, } => { event_sender .unbounded_send(MessageInternal::ScenicPresentDone( key, frame_presented_info, )) .expect("unbounded_send"); } } } }) .detach(); } fn listen_for_key_events( mut view_ref: ViewRef, app_sender: &UnboundedSender<MessageInternal>, key: ViewKey, ) -> Result<(), Error> { let keyboard = connect_to_protocol::<fidl_fuchsia_ui_input3::KeyboardMarker>() .context("Failed to connect to Keyboard service")?; let (listener_client_end, mut listener_stream) = create_request_stream::<fidl_fuchsia_ui_input3::KeyboardListenerMarker>()?; let event_sender = app_sender.clone(); fasync::Task::local(async move { keyboard.add_listener(&mut view_ref, listener_client_end).await.expect("add_listener"); while let Some(event) = listener_stream.try_next().await.expect("Failed to get next key event") { match event { fidl_fuchsia_ui_input3::KeyboardListenerRequest::OnKeyEvent { event, responder, .. } => { // Carnelian always considers key events handled. In the future, there // might be a use case that requires letting view assistants change // this behavior but none currently exists. responder .send(fidl_fuchsia_ui_input3::KeyEventStatus::Handled) .expect("send"); event_sender .unbounded_send(MessageInternal::ScenicKeyEvent(key, event)) .expect("unbounded_send"); } } } }) .detach(); Ok(()) } fn do_present( session: &SessionPtr, app_sender: &UnboundedSender<MessageInternal>, key: ViewKey, presentation_time: i64, ) { let present_sender = app_sender.clone(); let info_fut = session.lock().present2(presentation_time, 0); fasync::Task::local(async move { match info_fut.await { // TODO: figure out how to recover from this error Err(err) => eprintln!("Present Error: {}", err), Ok(info) => { present_sender .unbounded_send(MessageInternal::ScenicPresentSubmitted(key, info)) .expect("unbounded_send"); } } }) .detach(); } fn make_view_assistant_context( view_details: &ViewDetails, image_id: ImageId, image_index: u32, app_sender: UnboundedSender<MessageInternal>, ) -> ViewAssistantContext { ViewAssistantContext { key: view_details.key, size: view_details.logical_size, metrics: view_details.metrics, presentation_time: Time::get_monotonic(), messages: Vec::new(), buffer_count: None, image_id, image_index, frame_buffer: None, app_sender, mouse_cursor_position: None, } } async fn create_plumber(&mut self, size: UintSize) -> Result<(), Error> { let buffer_collection_id = self.next_buffer_collection; self.next_buffer_collection = self.next_buffer_collection.wrapping_add(1); let next_image_id = self.next_image_id; self.next_image_id = self.next_image_id.wrapping_add(RENDER_BUFFER_COUNT as u64); self.plumber = Some( Plumber::new( &self.session, size.to_u32(), fidl_fuchsia_sysmem::PixelFormatType::Bgra32, RENDER_BUFFER_COUNT, buffer_collection_id, next_image_id, self.render_options, ) .await .expect("VmoPlumber::new"), ); Ok(()) } fn next_presentation_time(&self) -> i64 { // TODO: https://bugs.fuchsia.dev/p/fuchsia/issues/detail?id=60306 let now = fasync::Time::now().into_nanos(); let legal_next = now + self.present_interval; let next = self.next_presentation_times.iter().find(|time| **time >= now).unwrap_or(&legal_next); *next } fn schedule_render_timer(&mut self, presentation_time: i64) { if !self.render_timer_scheduled { let timer = fasync::Timer::new(fuchsia_async::Time::from_nanos(presentation_time)); let timer_sender = self.app_sender.clone(); let key = self.view_key; fasync::Task::local(async move { timer.await; timer_sender.unbounded_send(MessageInternal::Render(key)).expect("unbounded_send"); }) .detach(); self.render_timer_scheduled = true; } } fn adjust_scenic_resources(&mut self, view_details: &ViewDetails) { let center_x = view_details.physical_size.width * 0.5; let center_y = view_details.physical_size.height * 0.5; self.content_node.set_translation(center_x, center_y, -0.1); let rectangle = Rectangle::new( self.session.clone(), view_details.physical_size.width as f32, view_details.physical_size.height as f32, ); self.content_node.set_shape(&rectangle); } fn render_to_image_from_plumber( &mut self, view_details: &ViewDetails, view_assistant: &mut ViewAssistantPtr, ) -> bool { let plumber = self.plumber.as_mut().expect("plumber"); if let Some(available) = plumber.frame_set.get_available_image() { duration!("gfx", "ScenicViewStrategy::render.render_to_image"); self.missed_frame = false; let available_index = plumber.image_indexes.get(&available).expect("index for image"); let image2 = plumber.images.get(&available).expect("image2"); self.content_material.set_texture_resource(Some(&image2)); let render_context = ScenicViewStrategy::make_view_assistant_context( view_details, available, *available_index, self.app_sender.clone(), ); let buffer_ready_event = Event::create().expect("Event.create"); view_assistant .render(&mut plumber.context, buffer_ready_event, &render_context) .unwrap_or_else(|e| panic!("Update error: {:?}", e)); plumber.frame_set.mark_prepared(available); let key = view_details.key; let collection_id = plumber.collection_id; let done_event = Event::create().expect("Event.create"); let local_done_event = done_event.duplicate_handle(zx::Rights::SAME_RIGHTS).expect("duplicate_handle"); self.session.lock().add_release_fence(done_event); let app_sender = self.app_sender.clone(); fasync::Task::local(async move { let signals = OnSignals::new(&local_done_event, Signals::EVENT_SIGNALED); signals.await.expect("to wait"); app_sender .unbounded_send(MessageInternal::ImageFreed(key, available, collection_id)) .expect("unbounded_send"); }) .detach(); // Image is guaranteed to be presented at this point. plumber.frame_set.mark_presented(available); true } else { self.missed_frame = true; false } } } #[async_trait(?Send)] impl ViewStrategy for ScenicViewStrategy { fn setup(&mut self, view_details: &ViewDetails, view_assistant: &mut ViewAssistantPtr) { let render_context = ScenicViewStrategy::make_view_assistant_context( view_details, 0, 0, self.app_sender.clone(), ); view_assistant.setup(&render_context).unwrap_or_else(|e| panic!("Setup error: {:?}", e)); } async fn render( &mut self, view_details: &ViewDetails, view_assistant: &mut ViewAssistantPtr, ) -> bool { duration!("gfx", "ScenicViewStrategy::render"); self.render_timer_scheduled = false; let size = view_details.logical_size.floor().to_u32(); if size.width > 0 && size.height > 0 { self.adjust_scenic_resources(view_details); if self.plumber.is_none() { duration!("gfx", "ScenicViewStrategy::render.create_plumber"); self.create_plumber(size).await.expect("create_plumber"); } else { let current_size = self.plumber.as_ref().expect("plumber").size; if current_size != size { duration!("gfx", "ScenicViewStrategy::render.create_plumber"); let retired_plumber = self.plumber.take().expect("plumber"); self.retiring_plumbers.push(retired_plumber); self.create_plumber(size).await.expect("create_plumber"); } } self.render_to_image_from_plumber(view_details, view_assistant) } else { true } } fn present(&mut self, _view_details: &ViewDetails) { duration!("gfx", "ScenicViewStrategy::present"); if self.remaining_presents_in_flight_allowed == 0 { instant!( "gfx", "ScenicViewStrategy::zero_remaining_presents_in_flight_allowed", fuchsia_trace::Scope::Process, "remaining_presents_in_flight_allowed" => format!("{:?}", self.remaining_presents_in_flight_allowed).as_str() ); } else if self.pending_present_count >= 3 { instant!( "gfx", "ScenicViewStrategy::too_many_presents", fuchsia_trace::Scope::Process, "pending_present_count" => format!("{:?}", self.pending_present_count).as_str() ); } else { let presentation_time = self.next_presentation_time(); Self::do_present(&self.session, &self.app_sender, self.view_key, presentation_time); // Advance presentation time. self.pending_present_count += 1; } } fn present_submitted( &mut self, _view_details: &ViewDetails, _view_assistant: &mut ViewAssistantPtr, info: fidl_fuchsia_scenic_scheduling::FuturePresentationTimes, ) { self.next_presentation_times = info .future_presentations .iter() .skip(1) // Skip the first one, as it is the time we are presenting to. .filter_map(|info| info.presentation_time) .collect(); let present_intervals = info.future_presentations.len().saturating_sub(1); if present_intervals > 0 { let times: Vec<_> = info .future_presentations .iter() .filter_map(|info| info.presentation_time) .collect(); let average_interval: i64 = times.as_slice().windows(2).map(|slice| slice[1] - slice[0]).sum::<i64>() / present_intervals as i64; self.present_interval = average_interval; } else { self.present_interval = DEFAULT_PRESENT_INTERVAL; } self.remaining_presents_in_flight_allowed = info.remaining_presents_in_flight_allowed; } fn present_done( &mut self, _view_details: &ViewDetails, _view_assistant: &mut ViewAssistantPtr, _info: fidl_fuchsia_scenic_scheduling::FramePresentedInfo, ) { assert_ne!(self.pending_present_count, 0); self.pending_present_count -= 1; } fn handle_focus( &mut self, view_details: &ViewDetails, view_assistant: &mut ViewAssistantPtr, focus: bool, ) { let mut render_context = ScenicViewStrategy::make_view_assistant_context( view_details, 0, 0, self.app_sender.clone(), ); view_assistant .handle_focus_event(&mut render_context, focus) .unwrap_or_else(|e| panic!("handle_focus error: {:?}", e)); } fn handle_scenic_input_event( &mut self, view_details: &ViewDetails, view_assistant: &mut ViewAssistantPtr, event: &fidl_fuchsia_ui_input::InputEvent, ) -> Vec<Message> { let events = self.input_handler.handle_scenic_input_event(&view_details.metrics, &event); let mut render_context = ScenicViewStrategy::make_view_assistant_context( view_details, 0, 0, self.app_sender.clone(), ); for input_event in events { view_assistant .handle_input_event(&mut render_context, &input_event) .unwrap_or_else(|e| eprintln!("handle_event: {:?}", e)); } render_context.messages } fn handle_scenic_key_event( &mut self, view_details: &ViewDetails, view_assistant: &mut ViewAssistantPtr, event: &fidl_fuchsia_ui_input3::KeyEvent, ) -> Vec<Message> { let events = self.input_handler.handle_scenic_key_event(&event); let mut render_context = ScenicViewStrategy::make_view_assistant_context( view_details, 0, 0, self.app_sender.clone(), ); for input_event in events { view_assistant .handle_input_event(&mut render_context, &input_event) .unwrap_or_else(|e| eprintln!("handle_event: {:?}", e)); } render_context.messages } fn image_freed(&mut self, image_id: u64, collection_id: u32) { instant!( "gfx", "ScenicViewStrategy::image_freed", fuchsia_trace::Scope::Process, "image_freed" => format!("{} in {}", image_id, collection_id).as_str() ); if self.missed_frame { self.render_requested(); } if let Some(plumber) = self.plumber.as_mut() { if plumber.collection_id == collection_id { plumber.frame_set.mark_done_presenting(image_id); return; } } for retired_plumber in &mut self.retiring_plumbers { if retired_plumber.collection_id == collection_id { retired_plumber.frame_set.mark_done_presenting(image_id); if retired_plumber.frame_set.no_images_in_use() { retired_plumber.enter_retirement(&self.session); } } } self.retiring_plumbers.retain(|plumber| !plumber.frame_set.no_images_in_use()); } fn render_requested(&mut self) { self.schedule_render_timer(self.next_presentation_time()); } }
36.866564
125
0.589591
5d244e77d7516aa2f2410d5e061fdc15db5bbe48
80,681
::bobbin_mcu::periph!( , Dma2d, _PERIPH, Dma2dPeriph, _OWNED, _REF_COUNT, 0x00000000, 0x00, 0x0c); #[doc="DMA2D controller"] #[derive(Clone, Copy, PartialEq, Eq)] pub struct Dma2dPeriph(pub usize); impl Dma2dPeriph { #[doc="Get the CR Register."] #[inline] pub fn cr_reg(&self) -> ::bobbin_mcu::register::Register<Cr> { ::bobbin_mcu::register::Register::new(self.0 as *mut Cr, 0x0) } #[doc="Get the *mut pointer for the CR register."] #[inline] pub fn cr_mut(&self) -> *mut Cr { self.cr_reg().ptr() } #[doc="Get the *const pointer for the CR register."] #[inline] pub fn cr_ptr(&self) -> *const Cr { self.cr_reg().ptr() } #[doc="Read the CR register."] #[inline] pub fn cr(&self) -> Cr { self.cr_reg().read() } #[doc="Write the CR register."] #[inline] pub fn write_cr(&self, value: Cr) -> &Self { self.cr_reg().write(value); self } #[doc="Set the CR register."] #[inline] pub fn set_cr<F: FnOnce(Cr) -> Cr>(&self, f: F) -> &Self { self.cr_reg().set(f); self } #[doc="Modify the CR register."] #[inline] pub fn with_cr<F: FnOnce(Cr) -> Cr>(&self, f: F) -> &Self { self.cr_reg().with(f); self } #[doc="Get the ISR Register."] #[inline] pub fn isr_reg(&self) -> ::bobbin_mcu::register::Register<Isr> { ::bobbin_mcu::register::Register::new(self.0 as *mut Isr, 0x4) } #[doc="Get the *mut pointer for the ISR register."] #[inline] pub fn isr_mut(&self) -> *mut Isr { self.isr_reg().ptr() } #[doc="Get the *const pointer for the ISR register."] #[inline] pub fn isr_ptr(&self) -> *const Isr { self.isr_reg().ptr() } #[doc="Read the ISR register."] #[inline] pub fn isr(&self) -> Isr { self.isr_reg().read() } #[doc="Get the IFCR Register."] #[inline] pub fn ifcr_reg(&self) -> ::bobbin_mcu::register::Register<Ifcr> { ::bobbin_mcu::register::Register::new(self.0 as *mut Ifcr, 0x8) } #[doc="Get the *mut pointer for the IFCR register."] #[inline] pub fn ifcr_mut(&self) -> *mut Ifcr { self.ifcr_reg().ptr() } #[doc="Get the *const pointer for the IFCR register."] #[inline] pub fn ifcr_ptr(&self) -> *const Ifcr { self.ifcr_reg().ptr() } #[doc="Read the IFCR register."] #[inline] pub fn ifcr(&self) -> Ifcr { self.ifcr_reg().read() } #[doc="Write the IFCR register."] #[inline] pub fn write_ifcr(&self, value: Ifcr) -> &Self { self.ifcr_reg().write(value); self } #[doc="Set the IFCR register."] #[inline] pub fn set_ifcr<F: FnOnce(Ifcr) -> Ifcr>(&self, f: F) -> &Self { self.ifcr_reg().set(f); self } #[doc="Modify the IFCR register."] #[inline] pub fn with_ifcr<F: FnOnce(Ifcr) -> Ifcr>(&self, f: F) -> &Self { self.ifcr_reg().with(f); self } #[doc="Get the FGMAR Register."] #[inline] pub fn fgmar_reg(&self) -> ::bobbin_mcu::register::Register<Fgmar> { ::bobbin_mcu::register::Register::new(self.0 as *mut Fgmar, 0xc) } #[doc="Get the *mut pointer for the FGMAR register."] #[inline] pub fn fgmar_mut(&self) -> *mut Fgmar { self.fgmar_reg().ptr() } #[doc="Get the *const pointer for the FGMAR register."] #[inline] pub fn fgmar_ptr(&self) -> *const Fgmar { self.fgmar_reg().ptr() } #[doc="Read the FGMAR register."] #[inline] pub fn fgmar(&self) -> Fgmar { self.fgmar_reg().read() } #[doc="Write the FGMAR register."] #[inline] pub fn write_fgmar(&self, value: Fgmar) -> &Self { self.fgmar_reg().write(value); self } #[doc="Set the FGMAR register."] #[inline] pub fn set_fgmar<F: FnOnce(Fgmar) -> Fgmar>(&self, f: F) -> &Self { self.fgmar_reg().set(f); self } #[doc="Modify the FGMAR register."] #[inline] pub fn with_fgmar<F: FnOnce(Fgmar) -> Fgmar>(&self, f: F) -> &Self { self.fgmar_reg().with(f); self } #[doc="Get the FGOR Register."] #[inline] pub fn fgor_reg(&self) -> ::bobbin_mcu::register::Register<Fgor> { ::bobbin_mcu::register::Register::new(self.0 as *mut Fgor, 0x10) } #[doc="Get the *mut pointer for the FGOR register."] #[inline] pub fn fgor_mut(&self) -> *mut Fgor { self.fgor_reg().ptr() } #[doc="Get the *const pointer for the FGOR register."] #[inline] pub fn fgor_ptr(&self) -> *const Fgor { self.fgor_reg().ptr() } #[doc="Read the FGOR register."] #[inline] pub fn fgor(&self) -> Fgor { self.fgor_reg().read() } #[doc="Write the FGOR register."] #[inline] pub fn write_fgor(&self, value: Fgor) -> &Self { self.fgor_reg().write(value); self } #[doc="Set the FGOR register."] #[inline] pub fn set_fgor<F: FnOnce(Fgor) -> Fgor>(&self, f: F) -> &Self { self.fgor_reg().set(f); self } #[doc="Modify the FGOR register."] #[inline] pub fn with_fgor<F: FnOnce(Fgor) -> Fgor>(&self, f: F) -> &Self { self.fgor_reg().with(f); self } #[doc="Get the BGMAR Register."] #[inline] pub fn bgmar_reg(&self) -> ::bobbin_mcu::register::Register<Bgmar> { ::bobbin_mcu::register::Register::new(self.0 as *mut Bgmar, 0x14) } #[doc="Get the *mut pointer for the BGMAR register."] #[inline] pub fn bgmar_mut(&self) -> *mut Bgmar { self.bgmar_reg().ptr() } #[doc="Get the *const pointer for the BGMAR register."] #[inline] pub fn bgmar_ptr(&self) -> *const Bgmar { self.bgmar_reg().ptr() } #[doc="Read the BGMAR register."] #[inline] pub fn bgmar(&self) -> Bgmar { self.bgmar_reg().read() } #[doc="Write the BGMAR register."] #[inline] pub fn write_bgmar(&self, value: Bgmar) -> &Self { self.bgmar_reg().write(value); self } #[doc="Set the BGMAR register."] #[inline] pub fn set_bgmar<F: FnOnce(Bgmar) -> Bgmar>(&self, f: F) -> &Self { self.bgmar_reg().set(f); self } #[doc="Modify the BGMAR register."] #[inline] pub fn with_bgmar<F: FnOnce(Bgmar) -> Bgmar>(&self, f: F) -> &Self { self.bgmar_reg().with(f); self } #[doc="Get the BGOR Register."] #[inline] pub fn bgor_reg(&self) -> ::bobbin_mcu::register::Register<Bgor> { ::bobbin_mcu::register::Register::new(self.0 as *mut Bgor, 0x18) } #[doc="Get the *mut pointer for the BGOR register."] #[inline] pub fn bgor_mut(&self) -> *mut Bgor { self.bgor_reg().ptr() } #[doc="Get the *const pointer for the BGOR register."] #[inline] pub fn bgor_ptr(&self) -> *const Bgor { self.bgor_reg().ptr() } #[doc="Read the BGOR register."] #[inline] pub fn bgor(&self) -> Bgor { self.bgor_reg().read() } #[doc="Write the BGOR register."] #[inline] pub fn write_bgor(&self, value: Bgor) -> &Self { self.bgor_reg().write(value); self } #[doc="Set the BGOR register."] #[inline] pub fn set_bgor<F: FnOnce(Bgor) -> Bgor>(&self, f: F) -> &Self { self.bgor_reg().set(f); self } #[doc="Modify the BGOR register."] #[inline] pub fn with_bgor<F: FnOnce(Bgor) -> Bgor>(&self, f: F) -> &Self { self.bgor_reg().with(f); self } #[doc="Get the FGPFCCR Register."] #[inline] pub fn fgpfccr_reg(&self) -> ::bobbin_mcu::register::Register<Fgpfccr> { ::bobbin_mcu::register::Register::new(self.0 as *mut Fgpfccr, 0x1c) } #[doc="Get the *mut pointer for the FGPFCCR register."] #[inline] pub fn fgpfccr_mut(&self) -> *mut Fgpfccr { self.fgpfccr_reg().ptr() } #[doc="Get the *const pointer for the FGPFCCR register."] #[inline] pub fn fgpfccr_ptr(&self) -> *const Fgpfccr { self.fgpfccr_reg().ptr() } #[doc="Read the FGPFCCR register."] #[inline] pub fn fgpfccr(&self) -> Fgpfccr { self.fgpfccr_reg().read() } #[doc="Write the FGPFCCR register."] #[inline] pub fn write_fgpfccr(&self, value: Fgpfccr) -> &Self { self.fgpfccr_reg().write(value); self } #[doc="Set the FGPFCCR register."] #[inline] pub fn set_fgpfccr<F: FnOnce(Fgpfccr) -> Fgpfccr>(&self, f: F) -> &Self { self.fgpfccr_reg().set(f); self } #[doc="Modify the FGPFCCR register."] #[inline] pub fn with_fgpfccr<F: FnOnce(Fgpfccr) -> Fgpfccr>(&self, f: F) -> &Self { self.fgpfccr_reg().with(f); self } #[doc="Get the FGCOLR Register."] #[inline] pub fn fgcolr_reg(&self) -> ::bobbin_mcu::register::Register<Fgcolr> { ::bobbin_mcu::register::Register::new(self.0 as *mut Fgcolr, 0x20) } #[doc="Get the *mut pointer for the FGCOLR register."] #[inline] pub fn fgcolr_mut(&self) -> *mut Fgcolr { self.fgcolr_reg().ptr() } #[doc="Get the *const pointer for the FGCOLR register."] #[inline] pub fn fgcolr_ptr(&self) -> *const Fgcolr { self.fgcolr_reg().ptr() } #[doc="Read the FGCOLR register."] #[inline] pub fn fgcolr(&self) -> Fgcolr { self.fgcolr_reg().read() } #[doc="Write the FGCOLR register."] #[inline] pub fn write_fgcolr(&self, value: Fgcolr) -> &Self { self.fgcolr_reg().write(value); self } #[doc="Set the FGCOLR register."] #[inline] pub fn set_fgcolr<F: FnOnce(Fgcolr) -> Fgcolr>(&self, f: F) -> &Self { self.fgcolr_reg().set(f); self } #[doc="Modify the FGCOLR register."] #[inline] pub fn with_fgcolr<F: FnOnce(Fgcolr) -> Fgcolr>(&self, f: F) -> &Self { self.fgcolr_reg().with(f); self } #[doc="Get the BGPFCCR Register."] #[inline] pub fn bgpfccr_reg(&self) -> ::bobbin_mcu::register::Register<Bgpfccr> { ::bobbin_mcu::register::Register::new(self.0 as *mut Bgpfccr, 0x24) } #[doc="Get the *mut pointer for the BGPFCCR register."] #[inline] pub fn bgpfccr_mut(&self) -> *mut Bgpfccr { self.bgpfccr_reg().ptr() } #[doc="Get the *const pointer for the BGPFCCR register."] #[inline] pub fn bgpfccr_ptr(&self) -> *const Bgpfccr { self.bgpfccr_reg().ptr() } #[doc="Read the BGPFCCR register."] #[inline] pub fn bgpfccr(&self) -> Bgpfccr { self.bgpfccr_reg().read() } #[doc="Write the BGPFCCR register."] #[inline] pub fn write_bgpfccr(&self, value: Bgpfccr) -> &Self { self.bgpfccr_reg().write(value); self } #[doc="Set the BGPFCCR register."] #[inline] pub fn set_bgpfccr<F: FnOnce(Bgpfccr) -> Bgpfccr>(&self, f: F) -> &Self { self.bgpfccr_reg().set(f); self } #[doc="Modify the BGPFCCR register."] #[inline] pub fn with_bgpfccr<F: FnOnce(Bgpfccr) -> Bgpfccr>(&self, f: F) -> &Self { self.bgpfccr_reg().with(f); self } #[doc="Get the BGCOLR Register."] #[inline] pub fn bgcolr_reg(&self) -> ::bobbin_mcu::register::Register<Bgcolr> { ::bobbin_mcu::register::Register::new(self.0 as *mut Bgcolr, 0x28) } #[doc="Get the *mut pointer for the BGCOLR register."] #[inline] pub fn bgcolr_mut(&self) -> *mut Bgcolr { self.bgcolr_reg().ptr() } #[doc="Get the *const pointer for the BGCOLR register."] #[inline] pub fn bgcolr_ptr(&self) -> *const Bgcolr { self.bgcolr_reg().ptr() } #[doc="Read the BGCOLR register."] #[inline] pub fn bgcolr(&self) -> Bgcolr { self.bgcolr_reg().read() } #[doc="Write the BGCOLR register."] #[inline] pub fn write_bgcolr(&self, value: Bgcolr) -> &Self { self.bgcolr_reg().write(value); self } #[doc="Set the BGCOLR register."] #[inline] pub fn set_bgcolr<F: FnOnce(Bgcolr) -> Bgcolr>(&self, f: F) -> &Self { self.bgcolr_reg().set(f); self } #[doc="Modify the BGCOLR register."] #[inline] pub fn with_bgcolr<F: FnOnce(Bgcolr) -> Bgcolr>(&self, f: F) -> &Self { self.bgcolr_reg().with(f); self } #[doc="Get the FGCMAR Register."] #[inline] pub fn fgcmar_reg(&self) -> ::bobbin_mcu::register::Register<Fgcmar> { ::bobbin_mcu::register::Register::new(self.0 as *mut Fgcmar, 0x2c) } #[doc="Get the *mut pointer for the FGCMAR register."] #[inline] pub fn fgcmar_mut(&self) -> *mut Fgcmar { self.fgcmar_reg().ptr() } #[doc="Get the *const pointer for the FGCMAR register."] #[inline] pub fn fgcmar_ptr(&self) -> *const Fgcmar { self.fgcmar_reg().ptr() } #[doc="Read the FGCMAR register."] #[inline] pub fn fgcmar(&self) -> Fgcmar { self.fgcmar_reg().read() } #[doc="Write the FGCMAR register."] #[inline] pub fn write_fgcmar(&self, value: Fgcmar) -> &Self { self.fgcmar_reg().write(value); self } #[doc="Set the FGCMAR register."] #[inline] pub fn set_fgcmar<F: FnOnce(Fgcmar) -> Fgcmar>(&self, f: F) -> &Self { self.fgcmar_reg().set(f); self } #[doc="Modify the FGCMAR register."] #[inline] pub fn with_fgcmar<F: FnOnce(Fgcmar) -> Fgcmar>(&self, f: F) -> &Self { self.fgcmar_reg().with(f); self } #[doc="Get the BGCMAR Register."] #[inline] pub fn bgcmar_reg(&self) -> ::bobbin_mcu::register::Register<Bgcmar> { ::bobbin_mcu::register::Register::new(self.0 as *mut Bgcmar, 0x30) } #[doc="Get the *mut pointer for the BGCMAR register."] #[inline] pub fn bgcmar_mut(&self) -> *mut Bgcmar { self.bgcmar_reg().ptr() } #[doc="Get the *const pointer for the BGCMAR register."] #[inline] pub fn bgcmar_ptr(&self) -> *const Bgcmar { self.bgcmar_reg().ptr() } #[doc="Read the BGCMAR register."] #[inline] pub fn bgcmar(&self) -> Bgcmar { self.bgcmar_reg().read() } #[doc="Write the BGCMAR register."] #[inline] pub fn write_bgcmar(&self, value: Bgcmar) -> &Self { self.bgcmar_reg().write(value); self } #[doc="Set the BGCMAR register."] #[inline] pub fn set_bgcmar<F: FnOnce(Bgcmar) -> Bgcmar>(&self, f: F) -> &Self { self.bgcmar_reg().set(f); self } #[doc="Modify the BGCMAR register."] #[inline] pub fn with_bgcmar<F: FnOnce(Bgcmar) -> Bgcmar>(&self, f: F) -> &Self { self.bgcmar_reg().with(f); self } #[doc="Get the OPFCCR Register."] #[inline] pub fn opfccr_reg(&self) -> ::bobbin_mcu::register::Register<Opfccr> { ::bobbin_mcu::register::Register::new(self.0 as *mut Opfccr, 0x34) } #[doc="Get the *mut pointer for the OPFCCR register."] #[inline] pub fn opfccr_mut(&self) -> *mut Opfccr { self.opfccr_reg().ptr() } #[doc="Get the *const pointer for the OPFCCR register."] #[inline] pub fn opfccr_ptr(&self) -> *const Opfccr { self.opfccr_reg().ptr() } #[doc="Read the OPFCCR register."] #[inline] pub fn opfccr(&self) -> Opfccr { self.opfccr_reg().read() } #[doc="Write the OPFCCR register."] #[inline] pub fn write_opfccr(&self, value: Opfccr) -> &Self { self.opfccr_reg().write(value); self } #[doc="Set the OPFCCR register."] #[inline] pub fn set_opfccr<F: FnOnce(Opfccr) -> Opfccr>(&self, f: F) -> &Self { self.opfccr_reg().set(f); self } #[doc="Modify the OPFCCR register."] #[inline] pub fn with_opfccr<F: FnOnce(Opfccr) -> Opfccr>(&self, f: F) -> &Self { self.opfccr_reg().with(f); self } #[doc="Get the OCOLR Register."] #[inline] pub fn ocolr_reg(&self) -> ::bobbin_mcu::register::Register<Ocolr> { ::bobbin_mcu::register::Register::new(self.0 as *mut Ocolr, 0x38) } #[doc="Get the *mut pointer for the OCOLR register."] #[inline] pub fn ocolr_mut(&self) -> *mut Ocolr { self.ocolr_reg().ptr() } #[doc="Get the *const pointer for the OCOLR register."] #[inline] pub fn ocolr_ptr(&self) -> *const Ocolr { self.ocolr_reg().ptr() } #[doc="Read the OCOLR register."] #[inline] pub fn ocolr(&self) -> Ocolr { self.ocolr_reg().read() } #[doc="Write the OCOLR register."] #[inline] pub fn write_ocolr(&self, value: Ocolr) -> &Self { self.ocolr_reg().write(value); self } #[doc="Set the OCOLR register."] #[inline] pub fn set_ocolr<F: FnOnce(Ocolr) -> Ocolr>(&self, f: F) -> &Self { self.ocolr_reg().set(f); self } #[doc="Modify the OCOLR register."] #[inline] pub fn with_ocolr<F: FnOnce(Ocolr) -> Ocolr>(&self, f: F) -> &Self { self.ocolr_reg().with(f); self } #[doc="Get the OMAR Register."] #[inline] pub fn omar_reg(&self) -> ::bobbin_mcu::register::Register<Omar> { ::bobbin_mcu::register::Register::new(self.0 as *mut Omar, 0x3c) } #[doc="Get the *mut pointer for the OMAR register."] #[inline] pub fn omar_mut(&self) -> *mut Omar { self.omar_reg().ptr() } #[doc="Get the *const pointer for the OMAR register."] #[inline] pub fn omar_ptr(&self) -> *const Omar { self.omar_reg().ptr() } #[doc="Read the OMAR register."] #[inline] pub fn omar(&self) -> Omar { self.omar_reg().read() } #[doc="Write the OMAR register."] #[inline] pub fn write_omar(&self, value: Omar) -> &Self { self.omar_reg().write(value); self } #[doc="Set the OMAR register."] #[inline] pub fn set_omar<F: FnOnce(Omar) -> Omar>(&self, f: F) -> &Self { self.omar_reg().set(f); self } #[doc="Modify the OMAR register."] #[inline] pub fn with_omar<F: FnOnce(Omar) -> Omar>(&self, f: F) -> &Self { self.omar_reg().with(f); self } #[doc="Get the OOR Register."] #[inline] pub fn oor_reg(&self) -> ::bobbin_mcu::register::Register<Oor> { ::bobbin_mcu::register::Register::new(self.0 as *mut Oor, 0x40) } #[doc="Get the *mut pointer for the OOR register."] #[inline] pub fn oor_mut(&self) -> *mut Oor { self.oor_reg().ptr() } #[doc="Get the *const pointer for the OOR register."] #[inline] pub fn oor_ptr(&self) -> *const Oor { self.oor_reg().ptr() } #[doc="Read the OOR register."] #[inline] pub fn oor(&self) -> Oor { self.oor_reg().read() } #[doc="Write the OOR register."] #[inline] pub fn write_oor(&self, value: Oor) -> &Self { self.oor_reg().write(value); self } #[doc="Set the OOR register."] #[inline] pub fn set_oor<F: FnOnce(Oor) -> Oor>(&self, f: F) -> &Self { self.oor_reg().set(f); self } #[doc="Modify the OOR register."] #[inline] pub fn with_oor<F: FnOnce(Oor) -> Oor>(&self, f: F) -> &Self { self.oor_reg().with(f); self } #[doc="Get the NLR Register."] #[inline] pub fn nlr_reg(&self) -> ::bobbin_mcu::register::Register<Nlr> { ::bobbin_mcu::register::Register::new(self.0 as *mut Nlr, 0x44) } #[doc="Get the *mut pointer for the NLR register."] #[inline] pub fn nlr_mut(&self) -> *mut Nlr { self.nlr_reg().ptr() } #[doc="Get the *const pointer for the NLR register."] #[inline] pub fn nlr_ptr(&self) -> *const Nlr { self.nlr_reg().ptr() } #[doc="Read the NLR register."] #[inline] pub fn nlr(&self) -> Nlr { self.nlr_reg().read() } #[doc="Write the NLR register."] #[inline] pub fn write_nlr(&self, value: Nlr) -> &Self { self.nlr_reg().write(value); self } #[doc="Set the NLR register."] #[inline] pub fn set_nlr<F: FnOnce(Nlr) -> Nlr>(&self, f: F) -> &Self { self.nlr_reg().set(f); self } #[doc="Modify the NLR register."] #[inline] pub fn with_nlr<F: FnOnce(Nlr) -> Nlr>(&self, f: F) -> &Self { self.nlr_reg().with(f); self } #[doc="Get the LWR Register."] #[inline] pub fn lwr_reg(&self) -> ::bobbin_mcu::register::Register<Lwr> { ::bobbin_mcu::register::Register::new(self.0 as *mut Lwr, 0x48) } #[doc="Get the *mut pointer for the LWR register."] #[inline] pub fn lwr_mut(&self) -> *mut Lwr { self.lwr_reg().ptr() } #[doc="Get the *const pointer for the LWR register."] #[inline] pub fn lwr_ptr(&self) -> *const Lwr { self.lwr_reg().ptr() } #[doc="Read the LWR register."] #[inline] pub fn lwr(&self) -> Lwr { self.lwr_reg().read() } #[doc="Write the LWR register."] #[inline] pub fn write_lwr(&self, value: Lwr) -> &Self { self.lwr_reg().write(value); self } #[doc="Set the LWR register."] #[inline] pub fn set_lwr<F: FnOnce(Lwr) -> Lwr>(&self, f: F) -> &Self { self.lwr_reg().set(f); self } #[doc="Modify the LWR register."] #[inline] pub fn with_lwr<F: FnOnce(Lwr) -> Lwr>(&self, f: F) -> &Self { self.lwr_reg().with(f); self } #[doc="Get the AMTCR Register."] #[inline] pub fn amtcr_reg(&self) -> ::bobbin_mcu::register::Register<Amtcr> { ::bobbin_mcu::register::Register::new(self.0 as *mut Amtcr, 0x4c) } #[doc="Get the *mut pointer for the AMTCR register."] #[inline] pub fn amtcr_mut(&self) -> *mut Amtcr { self.amtcr_reg().ptr() } #[doc="Get the *const pointer for the AMTCR register."] #[inline] pub fn amtcr_ptr(&self) -> *const Amtcr { self.amtcr_reg().ptr() } #[doc="Read the AMTCR register."] #[inline] pub fn amtcr(&self) -> Amtcr { self.amtcr_reg().read() } #[doc="Write the AMTCR register."] #[inline] pub fn write_amtcr(&self, value: Amtcr) -> &Self { self.amtcr_reg().write(value); self } #[doc="Set the AMTCR register."] #[inline] pub fn set_amtcr<F: FnOnce(Amtcr) -> Amtcr>(&self, f: F) -> &Self { self.amtcr_reg().set(f); self } #[doc="Modify the AMTCR register."] #[inline] pub fn with_amtcr<F: FnOnce(Amtcr) -> Amtcr>(&self, f: F) -> &Self { self.amtcr_reg().with(f); self } #[doc="Get the FGCLUT Register."] #[inline] pub fn fgclut_reg(&self) -> ::bobbin_mcu::register::Register<Fgclut> { ::bobbin_mcu::register::Register::new(self.0 as *mut Fgclut, 0x400) } #[doc="Get the *mut pointer for the FGCLUT register."] #[inline] pub fn fgclut_mut(&self) -> *mut Fgclut { self.fgclut_reg().ptr() } #[doc="Get the *const pointer for the FGCLUT register."] #[inline] pub fn fgclut_ptr(&self) -> *const Fgclut { self.fgclut_reg().ptr() } #[doc="Read the FGCLUT register."] #[inline] pub fn fgclut(&self) -> Fgclut { self.fgclut_reg().read() } #[doc="Write the FGCLUT register."] #[inline] pub fn write_fgclut(&self, value: Fgclut) -> &Self { self.fgclut_reg().write(value); self } #[doc="Set the FGCLUT register."] #[inline] pub fn set_fgclut<F: FnOnce(Fgclut) -> Fgclut>(&self, f: F) -> &Self { self.fgclut_reg().set(f); self } #[doc="Modify the FGCLUT register."] #[inline] pub fn with_fgclut<F: FnOnce(Fgclut) -> Fgclut>(&self, f: F) -> &Self { self.fgclut_reg().with(f); self } #[doc="Get the BGCLUT Register."] #[inline] pub fn bgclut_reg(&self) -> ::bobbin_mcu::register::Register<Bgclut> { ::bobbin_mcu::register::Register::new(self.0 as *mut Bgclut, 0x800) } #[doc="Get the *mut pointer for the BGCLUT register."] #[inline] pub fn bgclut_mut(&self) -> *mut Bgclut { self.bgclut_reg().ptr() } #[doc="Get the *const pointer for the BGCLUT register."] #[inline] pub fn bgclut_ptr(&self) -> *const Bgclut { self.bgclut_reg().ptr() } #[doc="Read the BGCLUT register."] #[inline] pub fn bgclut(&self) -> Bgclut { self.bgclut_reg().read() } #[doc="Write the BGCLUT register."] #[inline] pub fn write_bgclut(&self, value: Bgclut) -> &Self { self.bgclut_reg().write(value); self } #[doc="Set the BGCLUT register."] #[inline] pub fn set_bgclut<F: FnOnce(Bgclut) -> Bgclut>(&self, f: F) -> &Self { self.bgclut_reg().set(f); self } #[doc="Modify the BGCLUT register."] #[inline] pub fn with_bgclut<F: FnOnce(Bgclut) -> Bgclut>(&self, f: F) -> &Self { self.bgclut_reg().with(f); self } } #[doc="control register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Cr(pub u32); impl Cr { #[doc="DMA2D mode"] #[inline] pub fn mode(&self) -> ::bobbin_bits::U2 { unsafe { ::core::mem::transmute(((self.0 >> 16) & 0x3) as u8) } // [17:16] } #[doc="Returns true if MODE != 0"] #[inline] pub fn test_mode(&self) -> bool { self.mode() != 0 } #[doc="Sets the MODE field."] #[inline] pub fn set_mode<V: Into<::bobbin_bits::U2>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U2 = value.into(); let value: u32 = value.into(); self.0 &= !(0x3 << 16); self.0 |= value << 16; self } #[doc="Configuration Error Interrupt Enable"] #[inline] pub fn ceie(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 13) & 0x1) as u8) } // [13] } #[doc="Returns true if CEIE != 0"] #[inline] pub fn test_ceie(&self) -> bool { self.ceie() != 0 } #[doc="Sets the CEIE field."] #[inline] pub fn set_ceie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 13); self.0 |= value << 13; self } #[doc="CLUT transfer complete interrupt enable"] #[inline] pub fn ctcie(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 12) & 0x1) as u8) } // [12] } #[doc="Returns true if CTCIE != 0"] #[inline] pub fn test_ctcie(&self) -> bool { self.ctcie() != 0 } #[doc="Sets the CTCIE field."] #[inline] pub fn set_ctcie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 12); self.0 |= value << 12; self } #[doc="CLUT access error interrupt enable"] #[inline] pub fn caeie(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 11) & 0x1) as u8) } // [11] } #[doc="Returns true if CAEIE != 0"] #[inline] pub fn test_caeie(&self) -> bool { self.caeie() != 0 } #[doc="Sets the CAEIE field."] #[inline] pub fn set_caeie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 11); self.0 |= value << 11; self } #[doc="Transfer watermark interrupt enable"] #[inline] pub fn twie(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 10) & 0x1) as u8) } // [10] } #[doc="Returns true if TWIE != 0"] #[inline] pub fn test_twie(&self) -> bool { self.twie() != 0 } #[doc="Sets the TWIE field."] #[inline] pub fn set_twie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 10); self.0 |= value << 10; self } #[doc="Transfer complete interrupt enable"] #[inline] pub fn tcie(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 9) & 0x1) as u8) } // [9] } #[doc="Returns true if TCIE != 0"] #[inline] pub fn test_tcie(&self) -> bool { self.tcie() != 0 } #[doc="Sets the TCIE field."] #[inline] pub fn set_tcie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 9); self.0 |= value << 9; self } #[doc="Transfer error interrupt enable"] #[inline] pub fn teie(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 8) & 0x1) as u8) } // [8] } #[doc="Returns true if TEIE != 0"] #[inline] pub fn test_teie(&self) -> bool { self.teie() != 0 } #[doc="Sets the TEIE field."] #[inline] pub fn set_teie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 8); self.0 |= value << 8; self } #[doc="Abort"] #[inline] pub fn abort(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 2) & 0x1) as u8) } // [2] } #[doc="Returns true if ABORT != 0"] #[inline] pub fn test_abort(&self) -> bool { self.abort() != 0 } #[doc="Sets the ABORT field."] #[inline] pub fn set_abort<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 2); self.0 |= value << 2; self } #[doc="Suspend"] #[inline] pub fn susp(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 1) & 0x1) as u8) } // [1] } #[doc="Returns true if SUSP != 0"] #[inline] pub fn test_susp(&self) -> bool { self.susp() != 0 } #[doc="Sets the SUSP field."] #[inline] pub fn set_susp<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 1); self.0 |= value << 1; self } #[doc="Start"] #[inline] pub fn start(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x1) as u8) } // [0] } #[doc="Returns true if START != 0"] #[inline] pub fn test_start(&self) -> bool { self.start() != 0 } #[doc="Sets the START field."] #[inline] pub fn set_start<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 0); self.0 |= value << 0; self } } impl From<u32> for Cr { #[inline] fn from(other: u32) -> Self { Cr(other) } } impl ::core::fmt::Display for Cr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Cr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.mode() != 0 { try!(write!(f, " mode=0x{:x}", self.mode()))} if self.ceie() != 0 { try!(write!(f, " ceie"))} if self.ctcie() != 0 { try!(write!(f, " ctcie"))} if self.caeie() != 0 { try!(write!(f, " caeie"))} if self.twie() != 0 { try!(write!(f, " twie"))} if self.tcie() != 0 { try!(write!(f, " tcie"))} if self.teie() != 0 { try!(write!(f, " teie"))} if self.abort() != 0 { try!(write!(f, " abort"))} if self.susp() != 0 { try!(write!(f, " susp"))} if self.start() != 0 { try!(write!(f, " start"))} try!(write!(f, "]")); Ok(()) } } #[doc="Interrupt Status Register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Isr(pub u32); impl Isr { #[doc="Configuration error interrupt flag"] #[inline] pub fn ceif(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 5) & 0x1) as u8) } // [5] } #[doc="Returns true if CEIF != 0"] #[inline] pub fn test_ceif(&self) -> bool { self.ceif() != 0 } #[doc="Sets the CEIF field."] #[inline] pub fn set_ceif<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 5); self.0 |= value << 5; self } #[doc="CLUT transfer complete interrupt flag"] #[inline] pub fn ctcif(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x1) as u8) } // [4] } #[doc="Returns true if CTCIF != 0"] #[inline] pub fn test_ctcif(&self) -> bool { self.ctcif() != 0 } #[doc="Sets the CTCIF field."] #[inline] pub fn set_ctcif<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 4); self.0 |= value << 4; self } #[doc="CLUT access error interrupt flag"] #[inline] pub fn caeif(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 3) & 0x1) as u8) } // [3] } #[doc="Returns true if CAEIF != 0"] #[inline] pub fn test_caeif(&self) -> bool { self.caeif() != 0 } #[doc="Sets the CAEIF field."] #[inline] pub fn set_caeif<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 3); self.0 |= value << 3; self } #[doc="Transfer watermark interrupt flag"] #[inline] pub fn twif(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 2) & 0x1) as u8) } // [2] } #[doc="Returns true if TWIF != 0"] #[inline] pub fn test_twif(&self) -> bool { self.twif() != 0 } #[doc="Sets the TWIF field."] #[inline] pub fn set_twif<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 2); self.0 |= value << 2; self } #[doc="Transfer complete interrupt flag"] #[inline] pub fn tcif(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 1) & 0x1) as u8) } // [1] } #[doc="Returns true if TCIF != 0"] #[inline] pub fn test_tcif(&self) -> bool { self.tcif() != 0 } #[doc="Sets the TCIF field."] #[inline] pub fn set_tcif<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 1); self.0 |= value << 1; self } #[doc="Transfer error interrupt flag"] #[inline] pub fn teif(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x1) as u8) } // [0] } #[doc="Returns true if TEIF != 0"] #[inline] pub fn test_teif(&self) -> bool { self.teif() != 0 } #[doc="Sets the TEIF field."] #[inline] pub fn set_teif<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 0); self.0 |= value << 0; self } } impl From<u32> for Isr { #[inline] fn from(other: u32) -> Self { Isr(other) } } impl ::core::fmt::Display for Isr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Isr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.ceif() != 0 { try!(write!(f, " ceif"))} if self.ctcif() != 0 { try!(write!(f, " ctcif"))} if self.caeif() != 0 { try!(write!(f, " caeif"))} if self.twif() != 0 { try!(write!(f, " twif"))} if self.tcif() != 0 { try!(write!(f, " tcif"))} if self.teif() != 0 { try!(write!(f, " teif"))} try!(write!(f, "]")); Ok(()) } } #[doc="interrupt flag clear register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Ifcr(pub u32); impl Ifcr { #[doc="Clear configuration error interrupt flag"] #[inline] pub fn cceif(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 5) & 0x1) as u8) } // [5] } #[doc="Returns true if CCEIF != 0"] #[inline] pub fn test_cceif(&self) -> bool { self.cceif() != 0 } #[doc="Sets the CCEIF field."] #[inline] pub fn set_cceif<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 5); self.0 |= value << 5; self } #[doc="Clear CLUT transfer complete interrupt flag"] #[inline] pub fn cctcif(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x1) as u8) } // [4] } #[doc="Returns true if CCTCIF != 0"] #[inline] pub fn test_cctcif(&self) -> bool { self.cctcif() != 0 } #[doc="Sets the CCTCIF field."] #[inline] pub fn set_cctcif<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 4); self.0 |= value << 4; self } #[doc="Clear CLUT access error interrupt flag"] #[inline] pub fn caecif(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 3) & 0x1) as u8) } // [3] } #[doc="Returns true if CAECIF != 0"] #[inline] pub fn test_caecif(&self) -> bool { self.caecif() != 0 } #[doc="Sets the CAECIF field."] #[inline] pub fn set_caecif<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 3); self.0 |= value << 3; self } #[doc="Clear transfer watermark interrupt flag"] #[inline] pub fn ctwif(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 2) & 0x1) as u8) } // [2] } #[doc="Returns true if CTWIF != 0"] #[inline] pub fn test_ctwif(&self) -> bool { self.ctwif() != 0 } #[doc="Sets the CTWIF field."] #[inline] pub fn set_ctwif<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 2); self.0 |= value << 2; self } #[doc="Clear transfer complete interrupt flag"] #[inline] pub fn ctcif(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 1) & 0x1) as u8) } // [1] } #[doc="Returns true if CTCIF != 0"] #[inline] pub fn test_ctcif(&self) -> bool { self.ctcif() != 0 } #[doc="Sets the CTCIF field."] #[inline] pub fn set_ctcif<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 1); self.0 |= value << 1; self } #[doc="Clear Transfer error interrupt flag"] #[inline] pub fn cteif(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x1) as u8) } // [0] } #[doc="Returns true if CTEIF != 0"] #[inline] pub fn test_cteif(&self) -> bool { self.cteif() != 0 } #[doc="Sets the CTEIF field."] #[inline] pub fn set_cteif<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 0); self.0 |= value << 0; self } } impl From<u32> for Ifcr { #[inline] fn from(other: u32) -> Self { Ifcr(other) } } impl ::core::fmt::Display for Ifcr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Ifcr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.cceif() != 0 { try!(write!(f, " cceif"))} if self.cctcif() != 0 { try!(write!(f, " cctcif"))} if self.caecif() != 0 { try!(write!(f, " caecif"))} if self.ctwif() != 0 { try!(write!(f, " ctwif"))} if self.ctcif() != 0 { try!(write!(f, " ctcif"))} if self.cteif() != 0 { try!(write!(f, " cteif"))} try!(write!(f, "]")); Ok(()) } } #[doc="foreground memory address register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Fgmar(pub u32); impl Fgmar { #[doc="Memory address"] #[inline] pub fn ma(&self) -> ::bobbin_bits::U32 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0] } #[doc="Returns true if MA != 0"] #[inline] pub fn test_ma(&self) -> bool { self.ma() != 0 } #[doc="Sets the MA field."] #[inline] pub fn set_ma<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U32 = value.into(); let value: u32 = value.into(); self.0 &= !(0xffffffff << 0); self.0 |= value << 0; self } } impl From<u32> for Fgmar { #[inline] fn from(other: u32) -> Self { Fgmar(other) } } impl ::core::fmt::Display for Fgmar { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Fgmar { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); try!(write!(f, "]")); Ok(()) } } #[doc="foreground offset register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Fgor(pub u32); impl Fgor { #[doc="Line offset"] #[inline] pub fn lo(&self) -> ::bobbin_bits::U14 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x3fff) as u16) } // [13:0] } #[doc="Returns true if LO != 0"] #[inline] pub fn test_lo(&self) -> bool { self.lo() != 0 } #[doc="Sets the LO field."] #[inline] pub fn set_lo<V: Into<::bobbin_bits::U14>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U14 = value.into(); let value: u32 = value.into(); self.0 &= !(0x3fff << 0); self.0 |= value << 0; self } } impl From<u32> for Fgor { #[inline] fn from(other: u32) -> Self { Fgor(other) } } impl ::core::fmt::Display for Fgor { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Fgor { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.lo() != 0 { try!(write!(f, " lo=0x{:x}", self.lo()))} try!(write!(f, "]")); Ok(()) } } #[doc="background memory address register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Bgmar(pub u32); impl Bgmar { #[doc="Memory address"] #[inline] pub fn ma(&self) -> ::bobbin_bits::U32 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0] } #[doc="Returns true if MA != 0"] #[inline] pub fn test_ma(&self) -> bool { self.ma() != 0 } #[doc="Sets the MA field."] #[inline] pub fn set_ma<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U32 = value.into(); let value: u32 = value.into(); self.0 &= !(0xffffffff << 0); self.0 |= value << 0; self } } impl From<u32> for Bgmar { #[inline] fn from(other: u32) -> Self { Bgmar(other) } } impl ::core::fmt::Display for Bgmar { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Bgmar { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); try!(write!(f, "]")); Ok(()) } } #[doc="background offset register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Bgor(pub u32); impl Bgor { #[doc="Line offset"] #[inline] pub fn lo(&self) -> ::bobbin_bits::U14 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x3fff) as u16) } // [13:0] } #[doc="Returns true if LO != 0"] #[inline] pub fn test_lo(&self) -> bool { self.lo() != 0 } #[doc="Sets the LO field."] #[inline] pub fn set_lo<V: Into<::bobbin_bits::U14>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U14 = value.into(); let value: u32 = value.into(); self.0 &= !(0x3fff << 0); self.0 |= value << 0; self } } impl From<u32> for Bgor { #[inline] fn from(other: u32) -> Self { Bgor(other) } } impl ::core::fmt::Display for Bgor { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Bgor { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.lo() != 0 { try!(write!(f, " lo=0x{:x}", self.lo()))} try!(write!(f, "]")); Ok(()) } } #[doc="foreground PFC control register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Fgpfccr(pub u32); impl Fgpfccr { #[doc="Alpha value"] #[inline] pub fn alpha(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 24) & 0xff) as u8) } // [31:24] } #[doc="Returns true if ALPHA != 0"] #[inline] pub fn test_alpha(&self) -> bool { self.alpha() != 0 } #[doc="Sets the ALPHA field."] #[inline] pub fn set_alpha<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 24); self.0 |= value << 24; self } #[doc="Alpha mode"] #[inline] pub fn am(&self) -> ::bobbin_bits::U2 { unsafe { ::core::mem::transmute(((self.0 >> 16) & 0x3) as u8) } // [17:16] } #[doc="Returns true if AM != 0"] #[inline] pub fn test_am(&self) -> bool { self.am() != 0 } #[doc="Sets the AM field."] #[inline] pub fn set_am<V: Into<::bobbin_bits::U2>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U2 = value.into(); let value: u32 = value.into(); self.0 &= !(0x3 << 16); self.0 |= value << 16; self } #[doc="CLUT size"] #[inline] pub fn cs(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 8) & 0xff) as u8) } // [15:8] } #[doc="Returns true if CS != 0"] #[inline] pub fn test_cs(&self) -> bool { self.cs() != 0 } #[doc="Sets the CS field."] #[inline] pub fn set_cs<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 8); self.0 |= value << 8; self } #[doc="Start"] #[inline] pub fn start(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 5) & 0x1) as u8) } // [5] } #[doc="Returns true if START != 0"] #[inline] pub fn test_start(&self) -> bool { self.start() != 0 } #[doc="Sets the START field."] #[inline] pub fn set_start<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 5); self.0 |= value << 5; self } #[doc="CLUT color mode"] #[inline] pub fn ccm(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x1) as u8) } // [4] } #[doc="Returns true if CCM != 0"] #[inline] pub fn test_ccm(&self) -> bool { self.ccm() != 0 } #[doc="Sets the CCM field."] #[inline] pub fn set_ccm<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 4); self.0 |= value << 4; self } #[doc="Color mode"] #[inline] pub fn cm(&self) -> ::bobbin_bits::U4 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xf) as u8) } // [3:0] } #[doc="Returns true if CM != 0"] #[inline] pub fn test_cm(&self) -> bool { self.cm() != 0 } #[doc="Sets the CM field."] #[inline] pub fn set_cm<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U4 = value.into(); let value: u32 = value.into(); self.0 &= !(0xf << 0); self.0 |= value << 0; self } } impl From<u32> for Fgpfccr { #[inline] fn from(other: u32) -> Self { Fgpfccr(other) } } impl ::core::fmt::Display for Fgpfccr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Fgpfccr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.alpha() != 0 { try!(write!(f, " alpha=0x{:x}", self.alpha()))} if self.am() != 0 { try!(write!(f, " am=0x{:x}", self.am()))} if self.cs() != 0 { try!(write!(f, " cs=0x{:x}", self.cs()))} if self.start() != 0 { try!(write!(f, " start"))} if self.ccm() != 0 { try!(write!(f, " ccm"))} if self.cm() != 0 { try!(write!(f, " cm=0x{:x}", self.cm()))} try!(write!(f, "]")); Ok(()) } } #[doc="foreground color register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Fgcolr(pub u32); impl Fgcolr { #[doc="Red Value"] #[inline] pub fn red(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 16) & 0xff) as u8) } // [23:16] } #[doc="Returns true if RED != 0"] #[inline] pub fn test_red(&self) -> bool { self.red() != 0 } #[doc="Sets the RED field."] #[inline] pub fn set_red<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 16); self.0 |= value << 16; self } #[doc="Green Value"] #[inline] pub fn green(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 8) & 0xff) as u8) } // [15:8] } #[doc="Returns true if GREEN != 0"] #[inline] pub fn test_green(&self) -> bool { self.green() != 0 } #[doc="Sets the GREEN field."] #[inline] pub fn set_green<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 8); self.0 |= value << 8; self } #[doc="Blue Value"] #[inline] pub fn blue(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xff) as u8) } // [7:0] } #[doc="Returns true if BLUE != 0"] #[inline] pub fn test_blue(&self) -> bool { self.blue() != 0 } #[doc="Sets the BLUE field."] #[inline] pub fn set_blue<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 0); self.0 |= value << 0; self } } impl From<u32> for Fgcolr { #[inline] fn from(other: u32) -> Self { Fgcolr(other) } } impl ::core::fmt::Display for Fgcolr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Fgcolr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.red() != 0 { try!(write!(f, " red=0x{:x}", self.red()))} if self.green() != 0 { try!(write!(f, " green=0x{:x}", self.green()))} if self.blue() != 0 { try!(write!(f, " blue=0x{:x}", self.blue()))} try!(write!(f, "]")); Ok(()) } } #[doc="background PFC control register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Bgpfccr(pub u32); impl Bgpfccr { #[doc="Alpha value"] #[inline] pub fn alpha(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 24) & 0xff) as u8) } // [31:24] } #[doc="Returns true if ALPHA != 0"] #[inline] pub fn test_alpha(&self) -> bool { self.alpha() != 0 } #[doc="Sets the ALPHA field."] #[inline] pub fn set_alpha<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 24); self.0 |= value << 24; self } #[doc="Alpha mode"] #[inline] pub fn am(&self) -> ::bobbin_bits::U2 { unsafe { ::core::mem::transmute(((self.0 >> 16) & 0x3) as u8) } // [17:16] } #[doc="Returns true if AM != 0"] #[inline] pub fn test_am(&self) -> bool { self.am() != 0 } #[doc="Sets the AM field."] #[inline] pub fn set_am<V: Into<::bobbin_bits::U2>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U2 = value.into(); let value: u32 = value.into(); self.0 &= !(0x3 << 16); self.0 |= value << 16; self } #[doc="CLUT size"] #[inline] pub fn cs(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 8) & 0xff) as u8) } // [15:8] } #[doc="Returns true if CS != 0"] #[inline] pub fn test_cs(&self) -> bool { self.cs() != 0 } #[doc="Sets the CS field."] #[inline] pub fn set_cs<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 8); self.0 |= value << 8; self } #[doc="Start"] #[inline] pub fn start(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 5) & 0x1) as u8) } // [5] } #[doc="Returns true if START != 0"] #[inline] pub fn test_start(&self) -> bool { self.start() != 0 } #[doc="Sets the START field."] #[inline] pub fn set_start<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 5); self.0 |= value << 5; self } #[doc="CLUT Color mode"] #[inline] pub fn ccm(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x1) as u8) } // [4] } #[doc="Returns true if CCM != 0"] #[inline] pub fn test_ccm(&self) -> bool { self.ccm() != 0 } #[doc="Sets the CCM field."] #[inline] pub fn set_ccm<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 4); self.0 |= value << 4; self } #[doc="Color mode"] #[inline] pub fn cm(&self) -> ::bobbin_bits::U4 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xf) as u8) } // [3:0] } #[doc="Returns true if CM != 0"] #[inline] pub fn test_cm(&self) -> bool { self.cm() != 0 } #[doc="Sets the CM field."] #[inline] pub fn set_cm<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U4 = value.into(); let value: u32 = value.into(); self.0 &= !(0xf << 0); self.0 |= value << 0; self } } impl From<u32> for Bgpfccr { #[inline] fn from(other: u32) -> Self { Bgpfccr(other) } } impl ::core::fmt::Display for Bgpfccr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Bgpfccr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.alpha() != 0 { try!(write!(f, " alpha=0x{:x}", self.alpha()))} if self.am() != 0 { try!(write!(f, " am=0x{:x}", self.am()))} if self.cs() != 0 { try!(write!(f, " cs=0x{:x}", self.cs()))} if self.start() != 0 { try!(write!(f, " start"))} if self.ccm() != 0 { try!(write!(f, " ccm"))} if self.cm() != 0 { try!(write!(f, " cm=0x{:x}", self.cm()))} try!(write!(f, "]")); Ok(()) } } #[doc="background color register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Bgcolr(pub u32); impl Bgcolr { #[doc="Red Value"] #[inline] pub fn red(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 16) & 0xff) as u8) } // [23:16] } #[doc="Returns true if RED != 0"] #[inline] pub fn test_red(&self) -> bool { self.red() != 0 } #[doc="Sets the RED field."] #[inline] pub fn set_red<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 16); self.0 |= value << 16; self } #[doc="Green Value"] #[inline] pub fn green(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 8) & 0xff) as u8) } // [15:8] } #[doc="Returns true if GREEN != 0"] #[inline] pub fn test_green(&self) -> bool { self.green() != 0 } #[doc="Sets the GREEN field."] #[inline] pub fn set_green<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 8); self.0 |= value << 8; self } #[doc="Blue Value"] #[inline] pub fn blue(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xff) as u8) } // [7:0] } #[doc="Returns true if BLUE != 0"] #[inline] pub fn test_blue(&self) -> bool { self.blue() != 0 } #[doc="Sets the BLUE field."] #[inline] pub fn set_blue<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 0); self.0 |= value << 0; self } } impl From<u32> for Bgcolr { #[inline] fn from(other: u32) -> Self { Bgcolr(other) } } impl ::core::fmt::Display for Bgcolr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Bgcolr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.red() != 0 { try!(write!(f, " red=0x{:x}", self.red()))} if self.green() != 0 { try!(write!(f, " green=0x{:x}", self.green()))} if self.blue() != 0 { try!(write!(f, " blue=0x{:x}", self.blue()))} try!(write!(f, "]")); Ok(()) } } #[doc="foreground CLUT memory address register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Fgcmar(pub u32); impl Fgcmar { #[doc="Memory Address"] #[inline] pub fn ma(&self) -> ::bobbin_bits::U32 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0] } #[doc="Returns true if MA != 0"] #[inline] pub fn test_ma(&self) -> bool { self.ma() != 0 } #[doc="Sets the MA field."] #[inline] pub fn set_ma<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U32 = value.into(); let value: u32 = value.into(); self.0 &= !(0xffffffff << 0); self.0 |= value << 0; self } } impl From<u32> for Fgcmar { #[inline] fn from(other: u32) -> Self { Fgcmar(other) } } impl ::core::fmt::Display for Fgcmar { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Fgcmar { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); try!(write!(f, "]")); Ok(()) } } #[doc="background CLUT memory address register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Bgcmar(pub u32); impl Bgcmar { #[doc="Memory address"] #[inline] pub fn ma(&self) -> ::bobbin_bits::U32 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0] } #[doc="Returns true if MA != 0"] #[inline] pub fn test_ma(&self) -> bool { self.ma() != 0 } #[doc="Sets the MA field."] #[inline] pub fn set_ma<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U32 = value.into(); let value: u32 = value.into(); self.0 &= !(0xffffffff << 0); self.0 |= value << 0; self } } impl From<u32> for Bgcmar { #[inline] fn from(other: u32) -> Self { Bgcmar(other) } } impl ::core::fmt::Display for Bgcmar { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Bgcmar { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); try!(write!(f, "]")); Ok(()) } } #[doc="output PFC control register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Opfccr(pub u32); impl Opfccr { #[doc="Color mode"] #[inline] pub fn cm(&self) -> ::bobbin_bits::U3 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x7) as u8) } // [2:0] } #[doc="Returns true if CM != 0"] #[inline] pub fn test_cm(&self) -> bool { self.cm() != 0 } #[doc="Sets the CM field."] #[inline] pub fn set_cm<V: Into<::bobbin_bits::U3>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U3 = value.into(); let value: u32 = value.into(); self.0 &= !(0x7 << 0); self.0 |= value << 0; self } } impl From<u32> for Opfccr { #[inline] fn from(other: u32) -> Self { Opfccr(other) } } impl ::core::fmt::Display for Opfccr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Opfccr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.cm() != 0 { try!(write!(f, " cm=0x{:x}", self.cm()))} try!(write!(f, "]")); Ok(()) } } #[doc="output color register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Ocolr(pub u32); impl Ocolr { #[doc="Alpha Channel Value"] #[inline] pub fn aplha(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 24) & 0xff) as u8) } // [31:24] } #[doc="Returns true if APLHA != 0"] #[inline] pub fn test_aplha(&self) -> bool { self.aplha() != 0 } #[doc="Sets the APLHA field."] #[inline] pub fn set_aplha<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 24); self.0 |= value << 24; self } #[doc="Red Value"] #[inline] pub fn red(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 16) & 0xff) as u8) } // [23:16] } #[doc="Returns true if RED != 0"] #[inline] pub fn test_red(&self) -> bool { self.red() != 0 } #[doc="Sets the RED field."] #[inline] pub fn set_red<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 16); self.0 |= value << 16; self } #[doc="Green Value"] #[inline] pub fn green(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 8) & 0xff) as u8) } // [15:8] } #[doc="Returns true if GREEN != 0"] #[inline] pub fn test_green(&self) -> bool { self.green() != 0 } #[doc="Sets the GREEN field."] #[inline] pub fn set_green<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 8); self.0 |= value << 8; self } #[doc="Blue Value"] #[inline] pub fn blue(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xff) as u8) } // [7:0] } #[doc="Returns true if BLUE != 0"] #[inline] pub fn test_blue(&self) -> bool { self.blue() != 0 } #[doc="Sets the BLUE field."] #[inline] pub fn set_blue<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 0); self.0 |= value << 0; self } } impl From<u32> for Ocolr { #[inline] fn from(other: u32) -> Self { Ocolr(other) } } impl ::core::fmt::Display for Ocolr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Ocolr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.aplha() != 0 { try!(write!(f, " aplha=0x{:x}", self.aplha()))} if self.red() != 0 { try!(write!(f, " red=0x{:x}", self.red()))} if self.green() != 0 { try!(write!(f, " green=0x{:x}", self.green()))} if self.blue() != 0 { try!(write!(f, " blue=0x{:x}", self.blue()))} try!(write!(f, "]")); Ok(()) } } #[doc="output memory address register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Omar(pub u32); impl Omar { #[doc="Memory Address"] #[inline] pub fn ma(&self) -> ::bobbin_bits::U32 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0] } #[doc="Returns true if MA != 0"] #[inline] pub fn test_ma(&self) -> bool { self.ma() != 0 } #[doc="Sets the MA field."] #[inline] pub fn set_ma<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U32 = value.into(); let value: u32 = value.into(); self.0 &= !(0xffffffff << 0); self.0 |= value << 0; self } } impl From<u32> for Omar { #[inline] fn from(other: u32) -> Self { Omar(other) } } impl ::core::fmt::Display for Omar { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Omar { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); try!(write!(f, "]")); Ok(()) } } #[doc="output offset register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Oor(pub u32); impl Oor { #[doc="Line Offset"] #[inline] pub fn lo(&self) -> ::bobbin_bits::U14 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x3fff) as u16) } // [13:0] } #[doc="Returns true if LO != 0"] #[inline] pub fn test_lo(&self) -> bool { self.lo() != 0 } #[doc="Sets the LO field."] #[inline] pub fn set_lo<V: Into<::bobbin_bits::U14>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U14 = value.into(); let value: u32 = value.into(); self.0 &= !(0x3fff << 0); self.0 |= value << 0; self } } impl From<u32> for Oor { #[inline] fn from(other: u32) -> Self { Oor(other) } } impl ::core::fmt::Display for Oor { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Oor { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.lo() != 0 { try!(write!(f, " lo=0x{:x}", self.lo()))} try!(write!(f, "]")); Ok(()) } } #[doc="number of line register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Nlr(pub u32); impl Nlr { #[doc="Pixel per lines"] #[inline] pub fn pl(&self) -> ::bobbin_bits::U14 { unsafe { ::core::mem::transmute(((self.0 >> 16) & 0x3fff) as u16) } // [29:16] } #[doc="Returns true if PL != 0"] #[inline] pub fn test_pl(&self) -> bool { self.pl() != 0 } #[doc="Sets the PL field."] #[inline] pub fn set_pl<V: Into<::bobbin_bits::U14>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U14 = value.into(); let value: u32 = value.into(); self.0 &= !(0x3fff << 16); self.0 |= value << 16; self } #[doc="Number of lines"] #[inline] pub fn nl(&self) -> ::bobbin_bits::U16 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffff) as u16) } // [15:0] } #[doc="Returns true if NL != 0"] #[inline] pub fn test_nl(&self) -> bool { self.nl() != 0 } #[doc="Sets the NL field."] #[inline] pub fn set_nl<V: Into<::bobbin_bits::U16>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U16 = value.into(); let value: u32 = value.into(); self.0 &= !(0xffff << 0); self.0 |= value << 0; self } } impl From<u32> for Nlr { #[inline] fn from(other: u32) -> Self { Nlr(other) } } impl ::core::fmt::Display for Nlr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Nlr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.pl() != 0 { try!(write!(f, " pl=0x{:x}", self.pl()))} if self.nl() != 0 { try!(write!(f, " nl=0x{:x}", self.nl()))} try!(write!(f, "]")); Ok(()) } } #[doc="line watermark register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Lwr(pub u32); impl Lwr { #[doc="Line watermark"] #[inline] pub fn lw(&self) -> ::bobbin_bits::U16 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffff) as u16) } // [15:0] } #[doc="Returns true if LW != 0"] #[inline] pub fn test_lw(&self) -> bool { self.lw() != 0 } #[doc="Sets the LW field."] #[inline] pub fn set_lw<V: Into<::bobbin_bits::U16>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U16 = value.into(); let value: u32 = value.into(); self.0 &= !(0xffff << 0); self.0 |= value << 0; self } } impl From<u32> for Lwr { #[inline] fn from(other: u32) -> Self { Lwr(other) } } impl ::core::fmt::Display for Lwr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Lwr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.lw() != 0 { try!(write!(f, " lw=0x{:x}", self.lw()))} try!(write!(f, "]")); Ok(()) } } #[doc="AHB master timer configuration register"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Amtcr(pub u32); impl Amtcr { #[doc="Dead Time"] #[inline] pub fn dt(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 8) & 0xff) as u8) } // [15:8] } #[doc="Returns true if DT != 0"] #[inline] pub fn test_dt(&self) -> bool { self.dt() != 0 } #[doc="Sets the DT field."] #[inline] pub fn set_dt<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 8); self.0 |= value << 8; self } #[doc="Enable"] #[inline] pub fn en(&self) -> ::bobbin_bits::U1 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x1) as u8) } // [0] } #[doc="Returns true if EN != 0"] #[inline] pub fn test_en(&self) -> bool { self.en() != 0 } #[doc="Sets the EN field."] #[inline] pub fn set_en<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U1 = value.into(); let value: u32 = value.into(); self.0 &= !(0x1 << 0); self.0 |= value << 0; self } } impl From<u32> for Amtcr { #[inline] fn from(other: u32) -> Self { Amtcr(other) } } impl ::core::fmt::Display for Amtcr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Amtcr { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.dt() != 0 { try!(write!(f, " dt=0x{:x}", self.dt()))} if self.en() != 0 { try!(write!(f, " en"))} try!(write!(f, "]")); Ok(()) } } #[doc="FGCLUT"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Fgclut(pub u32); impl Fgclut { #[doc="APLHA"] #[inline] pub fn aplha(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 24) & 0xff) as u8) } // [31:24] } #[doc="Returns true if APLHA != 0"] #[inline] pub fn test_aplha(&self) -> bool { self.aplha() != 0 } #[doc="Sets the APLHA field."] #[inline] pub fn set_aplha<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 24); self.0 |= value << 24; self } #[doc="RED"] #[inline] pub fn red(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 16) & 0xff) as u8) } // [23:16] } #[doc="Returns true if RED != 0"] #[inline] pub fn test_red(&self) -> bool { self.red() != 0 } #[doc="Sets the RED field."] #[inline] pub fn set_red<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 16); self.0 |= value << 16; self } #[doc="GREEN"] #[inline] pub fn green(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 8) & 0xff) as u8) } // [15:8] } #[doc="Returns true if GREEN != 0"] #[inline] pub fn test_green(&self) -> bool { self.green() != 0 } #[doc="Sets the GREEN field."] #[inline] pub fn set_green<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 8); self.0 |= value << 8; self } #[doc="BLUE"] #[inline] pub fn blue(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xff) as u8) } // [7:0] } #[doc="Returns true if BLUE != 0"] #[inline] pub fn test_blue(&self) -> bool { self.blue() != 0 } #[doc="Sets the BLUE field."] #[inline] pub fn set_blue<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 0); self.0 |= value << 0; self } } impl From<u32> for Fgclut { #[inline] fn from(other: u32) -> Self { Fgclut(other) } } impl ::core::fmt::Display for Fgclut { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Fgclut { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.aplha() != 0 { try!(write!(f, " aplha=0x{:x}", self.aplha()))} if self.red() != 0 { try!(write!(f, " red=0x{:x}", self.red()))} if self.green() != 0 { try!(write!(f, " green=0x{:x}", self.green()))} if self.blue() != 0 { try!(write!(f, " blue=0x{:x}", self.blue()))} try!(write!(f, "]")); Ok(()) } } #[doc="BGCLUT"] #[derive(Default, Clone, Copy, PartialEq, Eq)] pub struct Bgclut(pub u32); impl Bgclut { #[doc="APLHA"] #[inline] pub fn aplha(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 24) & 0xff) as u8) } // [31:24] } #[doc="Returns true if APLHA != 0"] #[inline] pub fn test_aplha(&self) -> bool { self.aplha() != 0 } #[doc="Sets the APLHA field."] #[inline] pub fn set_aplha<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 24); self.0 |= value << 24; self } #[doc="RED"] #[inline] pub fn red(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 16) & 0xff) as u8) } // [23:16] } #[doc="Returns true if RED != 0"] #[inline] pub fn test_red(&self) -> bool { self.red() != 0 } #[doc="Sets the RED field."] #[inline] pub fn set_red<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 16); self.0 |= value << 16; self } #[doc="GREEN"] #[inline] pub fn green(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 8) & 0xff) as u8) } // [15:8] } #[doc="Returns true if GREEN != 0"] #[inline] pub fn test_green(&self) -> bool { self.green() != 0 } #[doc="Sets the GREEN field."] #[inline] pub fn set_green<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 8); self.0 |= value << 8; self } #[doc="BLUE"] #[inline] pub fn blue(&self) -> ::bobbin_bits::U8 { unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xff) as u8) } // [7:0] } #[doc="Returns true if BLUE != 0"] #[inline] pub fn test_blue(&self) -> bool { self.blue() != 0 } #[doc="Sets the BLUE field."] #[inline] pub fn set_blue<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self { let value: ::bobbin_bits::U8 = value.into(); let value: u32 = value.into(); self.0 &= !(0xff << 0); self.0 |= value << 0; self } } impl From<u32> for Bgclut { #[inline] fn from(other: u32) -> Self { Bgclut(other) } } impl ::core::fmt::Display for Bgclut { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { self.0.fmt(f) } } impl ::core::fmt::Debug for Bgclut { fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result { try!(write!(f, "[0x{:08x}", self.0)); if self.aplha() != 0 { try!(write!(f, " aplha=0x{:x}", self.aplha()))} if self.red() != 0 { try!(write!(f, " red=0x{:x}", self.red()))} if self.green() != 0 { try!(write!(f, " green=0x{:x}", self.green()))} if self.blue() != 0 { try!(write!(f, " blue=0x{:x}", self.blue()))} try!(write!(f, "]")); Ok(()) } }
29.467129
98
0.521139
ed1e6131e45ac75dd18b9bc3f34c92c25a9b5602
1,571
use std::pin::Pin; use std::time::Duration; use async_trait::async_trait; use futures03::prelude::Stream; use serde_json::Value; use slog::Logger; use crate::data::subgraph::Link; use crate::prelude::Error; /// The values that `json_stream` returns. The struct contains the deserialized /// JSON value from the input stream, together with the line number from which /// the value was read. pub struct JsonStreamValue { pub value: Value, pub line: usize, } pub type JsonValueStream = Pin<Box<dyn Stream<Item = Result<JsonStreamValue, Error>> + Send + 'static>>; /// Resolves links to subgraph manifests and resources referenced by them. #[async_trait] pub trait LinkResolver: Send + Sync + 'static { /// Updates the timeout used by the resolver. fn with_timeout(self, timeout: Duration) -> Self where Self: Sized; /// Enables infinite retries. fn with_retries(self) -> Self where Self: Sized; /// Fetches the link contents as bytes. async fn cat(&self, logger: &Logger, link: &Link) -> Result<Vec<u8>, Error>; /// Fetches the link contents as bytes. async fn http_get(&self, logger: &Logger, link: &Link) -> Result<Vec<u8>, Error>; /// Read the contents of `link` and deserialize them into a stream of JSON /// values. The values must each be on a single line; newlines are significant /// as they are used to split the file contents and each line is deserialized /// separately. async fn json_stream(&self, logger: &Logger, link: &Link) -> Result<JsonValueStream, Error>; }
32.729167
96
0.690643
0a6a6823d4614d341c8771033194d6e82d4b24eb
138
pub mod paging; pub mod driver; pub mod cpu; pub mod interrupts; // pub mod smp; pub mod pti; pub mod gdt; pub mod idt; pub mod syscall;
12.545455
19
0.710145
6a4833ecef18200732c81a978ce45050e137afb4
11,898
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Overnet daemon for Fuchsia #![deny(missing_docs)] mod mdns; mod serial; use anyhow::{Context as _, Error}; use argh::FromArgs; use fidl_fuchsia_overnet::{ MeshControllerRequest, MeshControllerRequestStream, ServiceConsumerRequest, ServiceConsumerRequestStream, ServicePublisherRequest, ServicePublisherRequestStream, }; use fuchsia_async as fasync; use fuchsia_component::server::ServiceFs; use futures::future::{abortable, AbortHandle}; use futures::lock::Mutex; use futures::prelude::*; use overnet_core::{ log_errors, LinkReceiver, NodeId, Router, RouterOptions, SimpleSecurityContext, }; use std::collections::HashMap; use std::net::{SocketAddr, SocketAddrV6}; use std::sync::Arc; #[derive(FromArgs)] /// Overnet. struct Opts { #[argh(switch)] /// publish mdns service mdns_publish: bool, #[argh(switch)] /// connect to mdns services mdns_connect: bool, #[argh(switch)] /// open a udp port udp: bool, #[argh(option, default = "\"debug\".to_string()")] /// add serial links /// Can be 'none', 'all', or a specific path to a serial device. serial: String, } struct UdpSocketHolder { sock: Arc<fasync::net::UdpSocket>, abort_publisher: Option<AbortHandle>, } impl UdpSocketHolder { fn new(node_id: NodeId, publish_mdns: bool) -> Result<Self, Error> { let sock = std::net::UdpSocket::bind("[::]:0").context("Creating UDP socket")?; let port = sock.local_addr().context("Getting UDP local address")?.port(); let sock = Arc::new(fasync::net::UdpSocket::from_socket(sock)?); let abort_publisher = if publish_mdns { let (publisher, abort_publisher) = abortable(mdns::publish(node_id, port)); fasync::Task::local(async move { let _ = publisher.await; }) .detach(); Some(abort_publisher) } else { None }; Ok(Self { sock, abort_publisher }) } } impl Drop for UdpSocketHolder { fn drop(&mut self) { self.abort_publisher.take().map(|a| a.abort()); } } // TODO: bundle send task with receiver and get memory management right here type UdpLinks = Arc<Mutex<HashMap<SocketAddrV6, LinkReceiver>>>; fn normalize_addr(addr: SocketAddr) -> SocketAddrV6 { match addr { SocketAddr::V6(a) => SocketAddrV6::new(*a.ip(), a.port(), 0, 0), SocketAddr::V4(a) => SocketAddrV6::new(a.ip().to_ipv6_mapped(), a.port(), 0, 0), } } /// UDP read inner loop. async fn read_udp(udp_socket: Arc<UdpSocketHolder>, udp_links: UdpLinks) -> Result<(), Error> { let mut buf = [0u8; 1500]; loop { let sock = udp_socket.sock.clone(); let (length, sender) = sock.recv_from(&mut buf).await?; println!("UDP_RECV from:{} len:{}", sender, length); let sender = normalize_addr(sender); let udp_links = udp_links.lock().await; if let Some(link) = udp_links.get(&sender) { if let Err(e) = link.received_packet(&mut buf[..length]).await { log::warn!("Failed receiving packet: {:?}", e); } } else { log::warn!("No link for received packet {:?}", sender); } } } /// Register a new UDP endpoint for some node_id. async fn register_udp( addr: SocketAddr, node_id: NodeId, node: Arc<Router>, udp_socket: Arc<UdpSocketHolder>, udp_links: UdpLinks, ) -> Result<(), Error> { let addr = normalize_addr(addr); let mut udp_links = udp_links.lock().await; if udp_links.get(&addr).is_none() { let (link_sender, link_receiver) = node.new_link(node_id).await?; udp_links.insert(addr, link_receiver); fasync::Task::local(log_errors( async move { let mut buf = [0u8; 1400]; while let Some(n) = link_sender.next_send(&mut buf).await? { println!("UDP_SEND to:{} len:{}", addr, n); udp_socket.sock.clone().send_to(&buf[..n], addr.into()).await?; } Ok(()) }, "Failed sending UDP on link", )) .detach(); } Ok(()) } async fn run_service_publisher_server( node: Arc<Router>, stream: ServicePublisherRequestStream, ) -> Result<(), Error> { stream .map_err(Into::into) .try_for_each_concurrent(None, |request| { let node = node.clone(); async move { match request { ServicePublisherRequest::PublishService { service_name, provider, .. } => { node.register_service(service_name, provider).await } } } }) .await } async fn run_service_consumer_server( node: Arc<Router>, stream: ServiceConsumerRequestStream, ) -> Result<(), Error> { let list_peers_context = Arc::new(node.new_list_peers_context()); stream .map_err(Into::into) .try_for_each_concurrent(None, |request| { let node = node.clone(); let list_peers_context = list_peers_context.clone(); async move { match request { ServiceConsumerRequest::ListPeers { responder, .. } => { let mut peers = list_peers_context.list_peers().await?; responder.send(&mut peers.iter_mut())?; Ok(()) } ServiceConsumerRequest::ConnectToService { node: node_id, service_name, chan, .. } => node.connect_to_service(node_id.id.into(), &service_name, chan).await, } } }) .await } async fn run_mesh_controller_server( node: Arc<Router>, stream: MeshControllerRequestStream, ) -> Result<(), Error> { stream .map_err(Into::into) .try_for_each_concurrent(None, |request| { let node = node.clone(); async move { match request { MeshControllerRequest::AttachSocketLink { socket, options, .. } => { if let Err(e) = node.run_socket_link(socket, options).await { log::warn!("Socket link failed: {:?}", e); } Ok(()) } } } }) .await } enum IncomingService { ServiceConsumer(ServiceConsumerRequestStream), ServicePublisher(ServicePublisherRequestStream), MeshController(MeshControllerRequestStream), // ... more services here } #[fasync::run_singlethreaded] async fn main() -> Result<(), Error> { let opt: Opts = argh::from_env(); fuchsia_syslog::init_with_tags(&["overnet"]).context("initialize logging")?; let mut fs = ServiceFs::new_local(); let mut svc_dir = fs.dir("svc"); svc_dir.add_fidl_service(IncomingService::ServiceConsumer); svc_dir.add_fidl_service(IncomingService::ServicePublisher); svc_dir.add_fidl_service(IncomingService::MeshController); fs.take_and_serve_directory_handle()?; let node = Router::new( RouterOptions::new() .export_diagnostics(fidl_fuchsia_overnet_protocol::Implementation::OvernetStack), Box::new(SimpleSecurityContext { node_cert: "/pkg/data/cert.crt", node_private_key: "/pkg/data/cert.key", root_cert: "/pkg/data/root.crt", }), )?; fasync::Task::local(log_errors( crate::serial::run_serial_link_handlers(Arc::downgrade(&node), opt.serial), "serial handler failed", )) .detach(); if opt.udp { let udp_socket = Arc::new(UdpSocketHolder::new(node.node_id(), opt.mdns_publish)?); let udp_links: UdpLinks = Arc::new(Mutex::new(HashMap::new())); let (tx_addr, mut rx_addr) = futures::channel::mpsc::channel(1); fasync::Task::local(log_errors( read_udp(udp_socket.clone(), udp_links.clone()), "Error reading UDP socket", )) .detach(); if opt.mdns_connect { fasync::Task::local(log_errors(mdns::subscribe(tx_addr), "MDNS Subscriber failed")) .detach(); } let udp_node = node.clone(); fasync::Task::local(log_errors( async move { while let Some((addr, node_id)) = rx_addr.next().await { register_udp( addr, node_id, udp_node.clone(), udp_socket.clone(), udp_links.clone(), ) .await?; } Ok(()) }, "Error registering links", )) .detach(); } fs.for_each_concurrent(None, move |svcreq| match svcreq { IncomingService::MeshController(stream) => run_mesh_controller_server(node.clone(), stream) .unwrap_or_else(|e| log::trace!("{:?}", e)) .boxed_local(), IncomingService::ServicePublisher(stream) => { run_service_publisher_server(node.clone(), stream) .unwrap_or_else(|e| log::trace!("{:?}", e)) .boxed_local() } IncomingService::ServiceConsumer(stream) => { run_service_consumer_server(node.clone(), stream) .unwrap_or_else(|e| log::trace!("{:?}", e)) .boxed_local() } }) .await; Ok(()) } // [START test_mod] #[cfg(test)] mod tests { use super::*; #[fasync::run_until_stalled(test)] async fn test_udplinks_hashmap() { //construct a router node let node = Router::new( RouterOptions::new(), Box::new(SimpleSecurityContext { node_cert: "/pkg/data/cert.crt", node_private_key: "/pkg/data/cert.key", root_cert: "/pkg/data/root.crt", }), ).unwrap(); //let peer node id=9999 ,udp socket: [fe80::5054:ff:fe40:5763] port 56424 //in function register_udp, arg: SocketAddr is construct at function endpoint6_to_socket in mdns.rs let socket_addr = SocketAddr::new(std::net::IpAddr::V6(std::net::Ipv6Addr::new( 0xff80, 0x0000, 0x0000, 0x0000, 0x5054, 0x00ff, 0xfe40, 0x5763)), 56424); let node_id =NodeId{0 : 9999}; //construct a peer link let (_link_sender, link_receiver) = node.new_link(node_id).await.unwrap(); let udp_links: UdpLinks = Arc::new(Mutex::new(HashMap::new())); let mut udp_links = udp_links.lock().await; assert_eq!(udp_links.is_empty(), true); //insert (addr, link_receiver) hashmap let addr = normalize_addr(socket_addr); udp_links.insert(addr, link_receiver); assert_eq!(udp_links.is_empty(), false); //let socket_addr_v6 recv from udp package. flowinfo:0,scope_id:0 let socket_addr_v6 = SocketAddrV6::new(std::net::Ipv6Addr::new( 0xff80, 0x0000, 0x0000, 0x0000, 0x5054, 0x00ff, 0xfe40, 0x5763), 56424, 0, 0); assert_eq!(udp_links.get(&socket_addr_v6).is_none(), false); //let socket_addr_v6 recv from udp package. flowinfo:2,scope_id:0 let socket_addr_v6 = SocketAddrV6::new(std::net::Ipv6Addr::new( 0xff80, 0x0000, 0x0000, 0x0000, 0x5054, 0x00ff, 0xfe40, 0x5763), 56424, 2, 0); assert_eq!(udp_links.get(&socket_addr_v6).is_none(), true); assert_eq!(udp_links.get(&normalize_addr(SocketAddr::V6(socket_addr_v6))).is_none(), false); } }
34.486957
107
0.576483
ed006bb243415e42de0fecf17332f89b18547314
107
#[derive(Queryable)] pub struct User { pub id: i32, pub email: String, pub password: String, }
15.285714
25
0.626168
031d56bfa0389847d080a46e0c8e440408502c3e
5,833
use crate::dhcp::constant::{BULLETIN_HELPER, COMMAND_PROMPT, WINDOWS_BULLETIN, DIRECTORY_PATH, DHCP_FILE, DHCP_FILE_PATH, DHCP_LOGS}; use crate::dhcp::operations::fetch_dhcp_logs::fetch_dhcp_logs; use crate::dhcp::operations::filter_dhcp_logs::filter_dhcp_logs; use crate::utilities::constant::{ERROR_MESSAGE, INACTIVE_SERVICE, INVALID_MATCH, SERVICE_DISCOVERED, CONFIG_FILE}; use crate::utilities::configuration::fetch_configuration; use crate::kafka::producer::{kafka_producer, Kafka}; use crate::ad::constant::CONFIG_ERROR; /// This structure we use as the object which contains path of DHCP logs and related commands. #[derive(Clone, Debug)] pub struct Dhcp{ pub configuration: Result<Configurations, String> } #[derive(Clone, Debug)] pub struct Configurations { pub path: String, pub dhcp_file: String, pub command_prompt: String, pub windows_bulletin: String, pub bulletin_helper: String, pub dhcp_file_path: String, pub dhcp_log: String, } impl Default for Dhcp{ fn default() -> self::Dhcp { match fetch_configuration(CONFIG_FILE){ Ok(configurations) => { Dhcp { configuration: Ok(Configurations{ path: configurations.get(&DIRECTORY_PATH.to_string()) .expect(CONFIG_ERROR).to_string(), dhcp_file: configurations.get(&DHCP_FILE.to_string()) .expect(CONFIG_ERROR).to_string(), command_prompt: COMMAND_PROMPT.to_string(), windows_bulletin: WINDOWS_BULLETIN.to_string(), bulletin_helper: BULLETIN_HELPER.to_string(), dhcp_file_path: configurations.get(&DHCP_FILE_PATH.to_string()) .expect(CONFIG_ERROR).to_string(), dhcp_log: configurations.get(&DHCP_LOGS.to_string()) .expect(CONFIG_ERROR).to_string(), }) } } Err(error) => { Dhcp{ configuration: Err(error.to_string()) } } } } } /// This function compress the DHCP logs. /// /// #Arguments /// /// *'with_filter' - A bool value that can define either want filtered logs or raw logs. /// *'service_response' - A string literal that can contain the response of service discovery. /// *'dhcp' - A object of DHCP protocol. /// *'kafka' - A object which contains the socket and topic. /// /// #Return /// /// Return the string literal which contains the success or error message. pub fn publish_dhcp_logs(with_filter: bool, service_response: &str, dhcp: Dhcp, kafka: Kafka) -> String { if !with_filter { match service_response { SERVICE_DISCOVERED => { let data: String = fetch_dhcp_logs(dhcp); kafka_producer(kafka, data) } INACTIVE_SERVICE => INACTIVE_SERVICE.to_string(), ERROR_MESSAGE => ERROR_MESSAGE.to_string(), _ => INVALID_MATCH.to_string() } } else { match service_response { SERVICE_DISCOVERED => { let data: String = filter_dhcp_logs(dhcp); kafka_producer(kafka, data) } INACTIVE_SERVICE => INACTIVE_SERVICE.to_string(), ERROR_MESSAGE => ERROR_MESSAGE.to_string(), _ => INVALID_MATCH.to_string() } } } #[cfg(test)] mod tests { use crate::dhcp::operations::publish_dhcp_logs::{publish_dhcp_logs, Dhcp}; use crate::utilities::constant::{ERROR_MESSAGE, INACTIVE_SERVICE, SERVICE_DISCOVERED}; use crate::kafka::constant::STREAM_SUCCESS; use crate::kafka::producer::Kafka; #[test] fn test_publish_dhcp_logs_success() { let dhcp: Dhcp = Dhcp::default(); let kafka: Kafka = Kafka::default(); assert_eq!(publish_dhcp_logs(false, SERVICE_DISCOVERED, dhcp, kafka), STREAM_SUCCESS); } #[test] fn test_publish_dhcp_logs_service_failure() { let dhcp: Dhcp = Dhcp::default(); let kafka: Kafka = Kafka::default(); assert_eq!(publish_dhcp_logs(false, INACTIVE_SERVICE, dhcp, kafka), INACTIVE_SERVICE); } #[test] fn test_publish_dhcp_logs_command_failure() { let dhcp: Dhcp = Dhcp::default(); let kafka: Kafka = Kafka::default(); assert_eq!(publish_dhcp_logs(false, ERROR_MESSAGE, dhcp, kafka), ERROR_MESSAGE); } #[test] fn test_publish_filtered_dhcp_logs_success() { let dhcp: Dhcp = Dhcp::default(); let kafka: Kafka = Kafka::default(); assert_eq!(publish_dhcp_logs(true, SERVICE_DISCOVERED, dhcp, kafka), STREAM_SUCCESS); } #[test] fn test_publish_filtered_dhcp_logs_service_failure() { let dhcp: Dhcp = Dhcp::default(); let kafka: Kafka = Kafka::default(); assert_eq!(publish_dhcp_logs(true, INACTIVE_SERVICE, dhcp, kafka), INACTIVE_SERVICE); } #[test] fn test_publish_filtered_dhcp_logs_command_failure() { let dhcp: Dhcp = Dhcp::default(); let kafka: Kafka = Kafka::default(); assert_eq!(publish_dhcp_logs(true, ERROR_MESSAGE, dhcp, kafka), ERROR_MESSAGE); } #[test] fn test_dhcp_default_success() { let dhcp: Dhcp = Dhcp::default(); if let Ok(configurations) = dhcp.clone().configuration { assert_eq!(configurations.command_prompt, "cmd"); } } }
37.391026
100
0.590091
760aea02b5f4e8a4bc034ea2c567b773651d88c3
412
//! Tests auto-converted from "sass-spec/spec/non_conformant/extend-tests/164_test_combinator_unification_angle_space.hrx" #[allow(unused)] fn runner() -> crate::TestRunner { super::runner() } #[test] #[ignore] // wrong result fn test() { assert_eq!( runner().ok(".a.b > x {a: b}\ \n.a y {@extend x}\n"), ".a.b > x, .a.b > y {\ \n a: b;\ \n}\n" ); }
21.684211
122
0.536408
640d80dfa82d5634b506ae38347861257a839e29
4,433
//! (!) a decision was made to go with the approach of recording rarities PER BANK //! //! an alternative would be to record rarities PER COLLECTION //! then we'd only allow the update_authority recorded on the Metadata to store rarity scores //! //! Pros of chosen approach: //! - flexibility: if update_authority Keypair is lost, a collection would never be able to run a bank with rarities //! - speed/ux: less computation needs to happen on-chain, hence can fit in more record ixs per tx //! - full reliance on bank manager: bank manager can offer rewards for someone else's collection, //! using their own rarity set, without asking for permission //! //! Cons: //! - if 2 banks are started, even by the same manager, the rarity PDAs will have to be recorded twice //! this means fees to record them (10 sol for 10k collection) will have to be paid twice use anchor_lang::prelude::*; use anchor_lang::solana_program::hash::hash; use anchor_lang::solana_program::program::invoke_signed; use anchor_lang::solana_program::system_instruction::create_account; use crate::state::*; #[derive(Accounts)] pub struct RecordRarityPoints<'info> { // bank #[account(has_one = bank_manager)] pub bank: Box<Account<'info, Bank>>, pub bank_manager: Signer<'info>, // misc #[account(mut)] pub payer: Signer<'info>, pub system_program: Program<'info, System>, // // remaining accounts can be any number of: // pub gem_mint: Box<Account<'info, Mint>>, // #[account(mut)] // pub gem_rarity: Box<Account<'info, Rarity>>, } pub fn handler<'a, 'b, 'c, 'info>( ctx: Context<'a, 'b, 'c, 'info, RecordRarityPoints<'info>>, rarity_configs: Vec<RarityConfig>, ) -> ProgramResult { let remaining_accs = &mut ctx.remaining_accounts.iter(); // the limiting factor here is actually not compute budget, but tx size client-side for config in rarity_configs.iter() { let gem_mint = next_account_info(remaining_accs)?; let gem_rarity = next_account_info(remaining_accs)?; // find bump - doing this program-side to reduce amount of info to be passed in (tx size) let (_pk, bump) = Pubkey::find_program_address( &[ b"gem_rarity".as_ref(), ctx.accounts.bank.key().as_ref(), gem_mint.key().as_ref(), ], ctx.program_id, ); // create the PDA if doesn't exist if gem_rarity.data_is_empty() { create_pda_with_space( &[ b"gem_rarity".as_ref(), ctx.accounts.bank.key().as_ref(), gem_mint.key().as_ref(), &[bump], ], gem_rarity, 8 + std::mem::size_of::<Rarity>(), ctx.program_id, &ctx.accounts.payer.to_account_info(), &ctx.accounts.system_program.to_account_info(), )?; } let disc = hash("account:Rarity".as_bytes()); let mut gem_rarity_raw = gem_rarity.data.borrow_mut(); gem_rarity_raw[..8].clone_from_slice(&disc.0[..8]); gem_rarity_raw[8..10].clone_from_slice(&config.rarity_points.to_le_bytes()); } Ok(()) } // try to make this as small as possible, to fit in max # of txs #[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, Default, PartialEq)] pub struct RarityConfig { pub mint: Pubkey, pub rarity_points: u16, } fn create_pda_with_space<'info>( pda_seeds: &[&[u8]], pda_info: &AccountInfo<'info>, space: usize, owner: &Pubkey, funder_info: &AccountInfo<'info>, system_program_info: &AccountInfo<'info>, ) -> ProgramResult { //create a PDA and allocate space inside of it at the same time //can only be done from INSIDE the program //based on https://github.com/solana-labs/solana-program-library/blob/7c8e65292a6ebc90de54468c665e30bc590c513a/feature-proposal/program/src/processor.rs#L148-L163 invoke_signed( &create_account( &funder_info.key, &pda_info.key, 1.max(Rent::get()?.minimum_balance(space)), space as u64, owner, ), &[ funder_info.clone(), pda_info.clone(), system_program_info.clone(), ], &[pda_seeds], //this is the part you can't do outside the program ) }
36.04065
166
0.625987
d50bf01b7c2cf9428ad4b08a527b58a151a53d2b
1,958
use super::*; use std::io::*; pub fn read_u1(r: &mut impl Read) -> Result<u8> { let mut buffer = [0u8; 1]; r.read_exact(&mut buffer)?; Ok(buffer[0]) } pub fn read_u2(r: &mut impl Read) -> Result<u16> { let mut buffer = [0u8; 2]; r.read_exact(&mut buffer)?; Ok(u16::from_be_bytes(buffer)) } pub fn read_u4(r: &mut impl Read) -> Result<u32> { let mut buffer = [0u8; 4]; r.read_exact(&mut buffer)?; Ok(u32::from_be_bytes(buffer)) } pub fn read_u8(r: &mut impl Read) -> Result<u64> { let mut buffer = [0u8; 8]; r.read_exact(&mut buffer)?; Ok(u64::from_be_bytes(buffer)) } //pub fn read_i1(r: &mut impl Read) -> Result< i8> { read_u1(r).map(|u| u as i8) } //pub fn read_i2(r: &mut impl Read) -> Result<i16> { read_u2(r).map(|u| u as i16) } pub fn read_i4(r: &mut impl Read) -> Result<i32> { read_u4(r).map(|u| u as i32) } pub fn read_i8(r: &mut impl Read) -> Result<i64> { read_u8(r).map(|u| u as i64) } pub fn read_ignore(read: &mut impl Read, bytes: usize) -> io::Result<()> { let mut info = Vec::new(); info.resize(bytes, 0u8); read.read_exact(&mut info[..])?; Ok(()) } // I/O errors here "probably" indicate bugs in class parsing - break at the callsite for ease of debugging. // The other alternative is you're parsing bad/corrupt classes, so good luck with that. macro_rules! io_data_error { ($($arg:tt)*) => {{ use bugsalot::*; let message = format!($($arg)*); bug!("{}", &message); std::io::Error::new(std::io::ErrorKind::InvalidData, message) }}; } macro_rules! io_data_err { ($($arg:tt)*) => { Err(io_data_error!($($arg)*)) }; } macro_rules! io_assert { ($condition:expr) => { if !$condition { return io_data_err!("Assertion failed: {}", stringify!($condition)); } }; ($condition:expr, $($arg:tt)*) => { if !$condition { return io_data_err!($($arg)*); } }; }
27.577465
107
0.578652
67ce237918cdea21612eeeb15073bb3cfb6d2723
177
use day_3::day_3; fn main() { let input = day_3::input::<12>(); println!("part 1 => {}", day_3::part_1(&input)); println!("part 2 => {}", day_3::part_2(&input)); }
22.125
52
0.536723
29e401b48c91072cfa09b2447b36aaebc44adf41
61,405
// Generated by gir (https://github.com/gtk-rs/gir @ 79e747a1a188) // from gir-files (https://github.com/gtk-rs/gir-files @ b827978e7d18) // from gst-gir-files (https://gitlab.freedesktop.org/gstreamer/gir-files-rs.git @ 0220d4948268) // 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}; // Enums pub type GstRTCPFBType = c_int; pub const GST_RTCP_FB_TYPE_INVALID: GstRTCPFBType = 0; pub const GST_RTCP_RTPFB_TYPE_NACK: GstRTCPFBType = 1; pub const GST_RTCP_RTPFB_TYPE_TMMBR: GstRTCPFBType = 3; pub const GST_RTCP_RTPFB_TYPE_TMMBN: GstRTCPFBType = 4; pub const GST_RTCP_RTPFB_TYPE_RTCP_SR_REQ: GstRTCPFBType = 5; pub const GST_RTCP_RTPFB_TYPE_TWCC: GstRTCPFBType = 15; pub const GST_RTCP_PSFB_TYPE_PLI: GstRTCPFBType = 1; pub const GST_RTCP_PSFB_TYPE_SLI: GstRTCPFBType = 2; pub const GST_RTCP_PSFB_TYPE_RPSI: GstRTCPFBType = 3; pub const GST_RTCP_PSFB_TYPE_AFB: GstRTCPFBType = 15; pub const GST_RTCP_PSFB_TYPE_FIR: GstRTCPFBType = 4; pub const GST_RTCP_PSFB_TYPE_TSTR: GstRTCPFBType = 5; pub const GST_RTCP_PSFB_TYPE_TSTN: GstRTCPFBType = 6; pub const GST_RTCP_PSFB_TYPE_VBCN: GstRTCPFBType = 7; pub type GstRTCPSDESType = c_int; pub const GST_RTCP_SDES_INVALID: GstRTCPSDESType = -1; pub const GST_RTCP_SDES_END: GstRTCPSDESType = 0; pub const GST_RTCP_SDES_CNAME: GstRTCPSDESType = 1; pub const GST_RTCP_SDES_NAME: GstRTCPSDESType = 2; pub const GST_RTCP_SDES_EMAIL: GstRTCPSDESType = 3; pub const GST_RTCP_SDES_PHONE: GstRTCPSDESType = 4; pub const GST_RTCP_SDES_LOC: GstRTCPSDESType = 5; pub const GST_RTCP_SDES_TOOL: GstRTCPSDESType = 6; pub const GST_RTCP_SDES_NOTE: GstRTCPSDESType = 7; pub const GST_RTCP_SDES_PRIV: GstRTCPSDESType = 8; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub const GST_RTCP_SDES_H323_CADDR: GstRTCPSDESType = 9; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub const GST_RTCP_SDES_APSI: GstRTCPSDESType = 10; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub const GST_RTCP_SDES_RGRP: GstRTCPSDESType = 11; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub const GST_RTCP_SDES_RTP_STREAM_ID: GstRTCPSDESType = 12; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub const GST_RTCP_SDES_REPAIRED_RTP_STREAM_ID: GstRTCPSDESType = 13; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub const GST_RTCP_SDES_CCID: GstRTCPSDESType = 14; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub const GST_RTCP_SDES_MID: GstRTCPSDESType = 15; pub type GstRTCPType = c_int; pub const GST_RTCP_TYPE_INVALID: GstRTCPType = 0; pub const GST_RTCP_TYPE_SR: GstRTCPType = 200; pub const GST_RTCP_TYPE_RR: GstRTCPType = 201; pub const GST_RTCP_TYPE_SDES: GstRTCPType = 202; pub const GST_RTCP_TYPE_BYE: GstRTCPType = 203; pub const GST_RTCP_TYPE_APP: GstRTCPType = 204; pub const GST_RTCP_TYPE_RTPFB: GstRTCPType = 205; pub const GST_RTCP_TYPE_PSFB: GstRTCPType = 206; pub const GST_RTCP_TYPE_XR: GstRTCPType = 207; pub type GstRTCPXRType = c_int; pub const GST_RTCP_XR_TYPE_INVALID: GstRTCPXRType = -1; pub const GST_RTCP_XR_TYPE_LRLE: GstRTCPXRType = 1; pub const GST_RTCP_XR_TYPE_DRLE: GstRTCPXRType = 2; pub const GST_RTCP_XR_TYPE_PRT: GstRTCPXRType = 3; pub const GST_RTCP_XR_TYPE_RRT: GstRTCPXRType = 4; pub const GST_RTCP_XR_TYPE_DLRR: GstRTCPXRType = 5; pub const GST_RTCP_XR_TYPE_SSUMM: GstRTCPXRType = 6; pub const GST_RTCP_XR_TYPE_VOIP_METRICS: GstRTCPXRType = 7; pub type GstRTPPayload = c_int; pub const GST_RTP_PAYLOAD_PCMU: GstRTPPayload = 0; pub const GST_RTP_PAYLOAD_1016: GstRTPPayload = 1; pub const GST_RTP_PAYLOAD_G721: GstRTPPayload = 2; pub const GST_RTP_PAYLOAD_GSM: GstRTPPayload = 3; pub const GST_RTP_PAYLOAD_G723: GstRTPPayload = 4; pub const GST_RTP_PAYLOAD_DVI4_8000: GstRTPPayload = 5; pub const GST_RTP_PAYLOAD_DVI4_16000: GstRTPPayload = 6; pub const GST_RTP_PAYLOAD_LPC: GstRTPPayload = 7; pub const GST_RTP_PAYLOAD_PCMA: GstRTPPayload = 8; pub const GST_RTP_PAYLOAD_G722: GstRTPPayload = 9; pub const GST_RTP_PAYLOAD_L16_STEREO: GstRTPPayload = 10; pub const GST_RTP_PAYLOAD_L16_MONO: GstRTPPayload = 11; pub const GST_RTP_PAYLOAD_QCELP: GstRTPPayload = 12; pub const GST_RTP_PAYLOAD_CN: GstRTPPayload = 13; pub const GST_RTP_PAYLOAD_MPA: GstRTPPayload = 14; pub const GST_RTP_PAYLOAD_G728: GstRTPPayload = 15; pub const GST_RTP_PAYLOAD_DVI4_11025: GstRTPPayload = 16; pub const GST_RTP_PAYLOAD_DVI4_22050: GstRTPPayload = 17; pub const GST_RTP_PAYLOAD_G729: GstRTPPayload = 18; pub const GST_RTP_PAYLOAD_CELLB: GstRTPPayload = 25; pub const GST_RTP_PAYLOAD_JPEG: GstRTPPayload = 26; pub const GST_RTP_PAYLOAD_NV: GstRTPPayload = 28; pub const GST_RTP_PAYLOAD_H261: GstRTPPayload = 31; pub const GST_RTP_PAYLOAD_MPV: GstRTPPayload = 32; pub const GST_RTP_PAYLOAD_MP2T: GstRTPPayload = 33; pub const GST_RTP_PAYLOAD_H263: GstRTPPayload = 34; pub type GstRTPProfile = c_int; pub const GST_RTP_PROFILE_UNKNOWN: GstRTPProfile = 0; pub const GST_RTP_PROFILE_AVP: GstRTPProfile = 1; pub const GST_RTP_PROFILE_SAVP: GstRTPProfile = 2; pub const GST_RTP_PROFILE_AVPF: GstRTPProfile = 3; pub const GST_RTP_PROFILE_SAVPF: GstRTPProfile = 4; // Constants pub const GST_RTCP_MAX_BYE_SSRC_COUNT: c_int = 31; pub const GST_RTCP_MAX_RB_COUNT: c_int = 31; pub const GST_RTCP_MAX_SDES: c_int = 255; pub const GST_RTCP_MAX_SDES_ITEM_COUNT: c_int = 31; pub const GST_RTCP_REDUCED_SIZE_VALID_MASK: c_int = 57592; pub const GST_RTCP_VALID_MASK: c_int = 57598; pub const GST_RTCP_VALID_VALUE: c_int = 200; pub const GST_RTCP_VERSION: c_int = 2; pub const GST_RTP_HDREXT_BASE: *const c_char = b"urn:ietf:params:rtp-hdrext:\0" as *const u8 as *const c_char; pub const GST_RTP_HDREXT_ELEMENT_CLASS: *const c_char = b"Network/Extension/RTPHeader\0" as *const u8 as *const c_char; pub const GST_RTP_HDREXT_NTP_56: *const c_char = b"ntp-56\0" as *const u8 as *const c_char; pub const GST_RTP_HDREXT_NTP_56_SIZE: c_int = 7; pub const GST_RTP_HDREXT_NTP_64: *const c_char = b"ntp-64\0" as *const u8 as *const c_char; pub const GST_RTP_HDREXT_NTP_64_SIZE: c_int = 8; pub const GST_RTP_HEADER_EXTENSION_URI_METADATA_KEY: *const c_char = b"RTP-Header-Extension-URI\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_1016_STRING: *const c_char = b"1\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_CELLB_STRING: *const c_char = b"25\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_CN_STRING: *const c_char = b"13\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_DVI4_11025_STRING: *const c_char = b"16\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_DVI4_16000_STRING: *const c_char = b"6\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_DVI4_22050_STRING: *const c_char = b"17\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_DVI4_8000_STRING: *const c_char = b"5\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_DYNAMIC_STRING: *const c_char = b"[96, 127]\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_G721_STRING: *const c_char = b"2\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_G722_STRING: *const c_char = b"9\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_G723_53: c_int = 17; pub const GST_RTP_PAYLOAD_G723_53_STRING: *const c_char = b"17\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_G723_63: c_int = 16; pub const GST_RTP_PAYLOAD_G723_63_STRING: *const c_char = b"16\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_G723_STRING: *const c_char = b"4\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_G728_STRING: *const c_char = b"15\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_G729_STRING: *const c_char = b"18\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_GSM_STRING: *const c_char = b"3\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_H261_STRING: *const c_char = b"31\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_H263_STRING: *const c_char = b"34\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_JPEG_STRING: *const c_char = b"26\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_L16_MONO_STRING: *const c_char = b"11\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_L16_STEREO_STRING: *const c_char = b"10\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_LPC_STRING: *const c_char = b"7\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_MP2T_STRING: *const c_char = b"33\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_MPA_STRING: *const c_char = b"14\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_MPV_STRING: *const c_char = b"32\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_NV_STRING: *const c_char = b"28\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_PCMA_STRING: *const c_char = b"8\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_PCMU_STRING: *const c_char = b"0\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_QCELP_STRING: *const c_char = b"12\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_TS41: c_int = 19; pub const GST_RTP_PAYLOAD_TS41_STRING: *const c_char = b"19\0" as *const u8 as *const c_char; pub const GST_RTP_PAYLOAD_TS48: c_int = 18; pub const GST_RTP_PAYLOAD_TS48_STRING: *const c_char = b"18\0" as *const u8 as *const c_char; pub const GST_RTP_SOURCE_META_MAX_CSRC_COUNT: c_int = 15; pub const GST_RTP_VERSION: c_int = 2; // Flags pub type GstRTPBufferFlags = c_uint; pub const GST_RTP_BUFFER_FLAG_RETRANSMISSION: GstRTPBufferFlags = 1048576; pub const GST_RTP_BUFFER_FLAG_REDUNDANT: GstRTPBufferFlags = 2097152; pub const GST_RTP_BUFFER_FLAG_LAST: GstRTPBufferFlags = 268435456; pub type GstRTPBufferMapFlags = c_uint; pub const GST_RTP_BUFFER_MAP_FLAG_SKIP_PADDING: GstRTPBufferMapFlags = 65536; pub const GST_RTP_BUFFER_MAP_FLAG_LAST: GstRTPBufferMapFlags = 16777216; pub type GstRTPHeaderExtensionDirection = c_uint; pub const GST_RTP_HEADER_EXTENSION_DIRECTION_INACTIVE: GstRTPHeaderExtensionDirection = 0; pub const GST_RTP_HEADER_EXTENSION_DIRECTION_SENDONLY: GstRTPHeaderExtensionDirection = 1; pub const GST_RTP_HEADER_EXTENSION_DIRECTION_RECVONLY: GstRTPHeaderExtensionDirection = 2; pub const GST_RTP_HEADER_EXTENSION_DIRECTION_SENDRECV: GstRTPHeaderExtensionDirection = 3; pub const GST_RTP_HEADER_EXTENSION_DIRECTION_INHERITED: GstRTPHeaderExtensionDirection = 4; pub type GstRTPHeaderExtensionFlags = c_uint; pub const GST_RTP_HEADER_EXTENSION_ONE_BYTE: GstRTPHeaderExtensionFlags = 1; pub const GST_RTP_HEADER_EXTENSION_TWO_BYTE: GstRTPHeaderExtensionFlags = 2; // Records #[derive(Copy, Clone)] #[repr(C)] pub struct GstRTCPBuffer { pub buffer: *mut gst::GstBuffer, pub map: gst::GstMapInfo, } impl ::std::fmt::Debug for GstRTCPBuffer { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstRTCPBuffer @ {:p}", self)) .field("buffer", &self.buffer) .field("map", &self.map) .finish() } } #[derive(Copy, Clone)] #[repr(C)] pub struct GstRTCPPacket { pub rtcp: *mut GstRTCPBuffer, pub offset: c_uint, pub padding: gboolean, pub count: u8, pub type_: GstRTCPType, pub length: u16, pub item_offset: c_uint, pub item_count: c_uint, pub entry_offset: c_uint, } impl ::std::fmt::Debug for GstRTCPPacket { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstRTCPPacket @ {:p}", self)) .field("rtcp", &self.rtcp) .field("offset", &self.offset) .finish() } } #[derive(Copy, Clone)] #[repr(C)] pub struct GstRTPBaseAudioPayloadClass { pub parent_class: GstRTPBasePayloadClass, pub _gst_reserved: [gpointer; 4], } impl ::std::fmt::Debug for GstRTPBaseAudioPayloadClass { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstRTPBaseAudioPayloadClass @ {:p}", self)) .field("parent_class", &self.parent_class) .finish() } } #[repr(C)] pub struct _GstRTPBaseAudioPayloadPrivate { _data: [u8; 0], _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>, } pub type GstRTPBaseAudioPayloadPrivate = *mut _GstRTPBaseAudioPayloadPrivate; #[derive(Copy, Clone)] #[repr(C)] pub struct GstRTPBaseDepayloadClass { pub parent_class: gst::GstElementClass, pub set_caps: Option<unsafe extern "C" fn(*mut GstRTPBaseDepayload, *mut gst::GstCaps) -> gboolean>, pub process: Option< unsafe extern "C" fn(*mut GstRTPBaseDepayload, *mut gst::GstBuffer) -> *mut gst::GstBuffer, >, pub packet_lost: Option<unsafe extern "C" fn(*mut GstRTPBaseDepayload, *mut gst::GstEvent) -> gboolean>, pub handle_event: Option<unsafe extern "C" fn(*mut GstRTPBaseDepayload, *mut gst::GstEvent) -> gboolean>, pub process_rtp_packet: Option< unsafe extern "C" fn(*mut GstRTPBaseDepayload, *mut GstRTPBuffer) -> *mut gst::GstBuffer, >, pub _gst_reserved: [gpointer; 3], } impl ::std::fmt::Debug for GstRTPBaseDepayloadClass { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstRTPBaseDepayloadClass @ {:p}", self)) .field("parent_class", &self.parent_class) .field("set_caps", &self.set_caps) .field("process", &self.process) .field("packet_lost", &self.packet_lost) .field("handle_event", &self.handle_event) .field("process_rtp_packet", &self.process_rtp_packet) .finish() } } #[repr(C)] pub struct _GstRTPBaseDepayloadPrivate { _data: [u8; 0], _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>, } pub type GstRTPBaseDepayloadPrivate = *mut _GstRTPBaseDepayloadPrivate; #[derive(Copy, Clone)] #[repr(C)] pub struct GstRTPBasePayloadClass { pub parent_class: gst::GstElementClass, pub get_caps: Option< unsafe extern "C" fn( *mut GstRTPBasePayload, *mut gst::GstPad, *mut gst::GstCaps, ) -> *mut gst::GstCaps, >, pub set_caps: Option<unsafe extern "C" fn(*mut GstRTPBasePayload, *mut gst::GstCaps) -> gboolean>, pub handle_buffer: Option< unsafe extern "C" fn(*mut GstRTPBasePayload, *mut gst::GstBuffer) -> gst::GstFlowReturn, >, pub sink_event: Option<unsafe extern "C" fn(*mut GstRTPBasePayload, *mut gst::GstEvent) -> gboolean>, pub src_event: Option<unsafe extern "C" fn(*mut GstRTPBasePayload, *mut gst::GstEvent) -> gboolean>, pub query: Option< unsafe extern "C" fn( *mut GstRTPBasePayload, *mut gst::GstPad, *mut gst::GstQuery, ) -> gboolean, >, pub _gst_reserved: [gpointer; 4], } impl ::std::fmt::Debug for GstRTPBasePayloadClass { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstRTPBasePayloadClass @ {:p}", self)) .field("parent_class", &self.parent_class) .field("get_caps", &self.get_caps) .field("set_caps", &self.set_caps) .field("handle_buffer", &self.handle_buffer) .field("sink_event", &self.sink_event) .field("src_event", &self.src_event) .field("query", &self.query) .finish() } } #[repr(C)] pub struct _GstRTPBasePayloadPrivate { _data: [u8; 0], _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>, } pub type GstRTPBasePayloadPrivate = *mut _GstRTPBasePayloadPrivate; #[derive(Copy, Clone)] #[repr(C)] pub struct GstRTPBuffer { pub buffer: *mut gst::GstBuffer, pub state: c_uint, pub data: [gpointer; 4], pub size: [size_t; 4], pub map: [gst::GstMapInfo; 4], } impl ::std::fmt::Debug for GstRTPBuffer { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstRTPBuffer @ {:p}", self)) .field("buffer", &self.buffer) .field("state", &self.state) .field("data", &self.data) .field("size", &self.size) .field("map", &self.map) .finish() } } #[derive(Copy, Clone)] #[repr(C)] pub struct GstRTPHeaderExtensionClass { pub parent_class: gst::GstElementClass, pub get_supported_flags: Option<unsafe extern "C" fn(*mut GstRTPHeaderExtension) -> GstRTPHeaderExtensionFlags>, pub get_max_size: Option<unsafe extern "C" fn(*mut GstRTPHeaderExtension, *const gst::GstBuffer) -> size_t>, pub write: Option< unsafe extern "C" fn( *mut GstRTPHeaderExtension, *const gst::GstBuffer, GstRTPHeaderExtensionFlags, *mut gst::GstBuffer, *mut u8, size_t, ) -> ssize_t, >, pub read: Option< unsafe extern "C" fn( *mut GstRTPHeaderExtension, GstRTPHeaderExtensionFlags, *const u8, size_t, *mut gst::GstBuffer, ) -> gboolean, >, pub set_non_rtp_sink_caps: Option<unsafe extern "C" fn(*mut GstRTPHeaderExtension, *mut gst::GstCaps) -> gboolean>, pub update_non_rtp_src_caps: Option<unsafe extern "C" fn(*mut GstRTPHeaderExtension, *mut gst::GstCaps) -> gboolean>, pub set_attributes: Option< unsafe extern "C" fn( *mut GstRTPHeaderExtension, GstRTPHeaderExtensionDirection, *const c_char, ) -> gboolean, >, pub set_caps_from_attributes: Option<unsafe extern "C" fn(*mut GstRTPHeaderExtension, *mut gst::GstCaps) -> gboolean>, pub _gst_reserved: [gpointer; 4], } impl ::std::fmt::Debug for GstRTPHeaderExtensionClass { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstRTPHeaderExtensionClass @ {:p}", self)) .field("parent_class", &self.parent_class) .field("get_supported_flags", &self.get_supported_flags) .field("get_max_size", &self.get_max_size) .field("write", &self.write) .field("read", &self.read) .field("set_non_rtp_sink_caps", &self.set_non_rtp_sink_caps) .field("update_non_rtp_src_caps", &self.update_non_rtp_src_caps) .field("set_attributes", &self.set_attributes) .field("set_caps_from_attributes", &self.set_caps_from_attributes) .finish() } } #[derive(Copy, Clone)] #[repr(C)] pub struct GstRTPPayloadInfo { pub payload_type: u8, pub media: *const c_char, pub encoding_name: *const c_char, pub clock_rate: c_uint, pub encoding_parameters: *const c_char, pub bitrate: c_uint, pub _gst_reserved: [gpointer; 4], } impl ::std::fmt::Debug for GstRTPPayloadInfo { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstRTPPayloadInfo @ {:p}", self)) .field("payload_type", &self.payload_type) .field("media", &self.media) .field("encoding_name", &self.encoding_name) .field("clock_rate", &self.clock_rate) .field("encoding_parameters", &self.encoding_parameters) .field("bitrate", &self.bitrate) .finish() } } #[derive(Copy, Clone)] #[repr(C)] pub struct GstRTPSourceMeta { pub meta: gst::GstMeta, pub ssrc: u32, pub ssrc_valid: gboolean, pub csrc: [u32; 15], pub csrc_count: c_uint, } impl ::std::fmt::Debug for GstRTPSourceMeta { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstRTPSourceMeta @ {:p}", self)) .field("meta", &self.meta) .field("ssrc", &self.ssrc) .field("ssrc_valid", &self.ssrc_valid) .field("csrc", &self.csrc) .field("csrc_count", &self.csrc_count) .finish() } } // Classes #[derive(Copy, Clone)] #[repr(C)] pub struct GstRTPBaseAudioPayload { pub payload: GstRTPBasePayload, pub priv_: *mut GstRTPBaseAudioPayloadPrivate, pub base_ts: gst::GstClockTime, pub frame_size: c_int, pub frame_duration: c_int, pub sample_size: c_int, pub _gst_reserved: [gpointer; 4], } impl ::std::fmt::Debug for GstRTPBaseAudioPayload { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstRTPBaseAudioPayload @ {:p}", self)) .field("payload", &self.payload) .field("priv_", &self.priv_) .field("base_ts", &self.base_ts) .field("frame_size", &self.frame_size) .field("frame_duration", &self.frame_duration) .field("sample_size", &self.sample_size) .finish() } } #[derive(Copy, Clone)] #[repr(C)] pub struct GstRTPBaseDepayload { pub parent: gst::GstElement, pub sinkpad: *mut gst::GstPad, pub srcpad: *mut gst::GstPad, pub clock_rate: c_uint, pub segment: gst::GstSegment, pub need_newsegment: gboolean, pub priv_: *mut GstRTPBaseDepayloadPrivate, pub _gst_reserved: [gpointer; 4], } impl ::std::fmt::Debug for GstRTPBaseDepayload { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstRTPBaseDepayload @ {:p}", self)) .field("parent", &self.parent) .field("sinkpad", &self.sinkpad) .field("srcpad", &self.srcpad) .field("clock_rate", &self.clock_rate) .field("segment", &self.segment) .field("need_newsegment", &self.need_newsegment) .finish() } } #[derive(Copy, Clone)] #[repr(C)] pub struct GstRTPBasePayload { pub element: gst::GstElement, pub sinkpad: *mut gst::GstPad, pub srcpad: *mut gst::GstPad, pub ts_base: u32, pub seqnum_base: u16, pub media: *mut c_char, pub encoding_name: *mut c_char, pub dynamic: gboolean, pub clock_rate: u32, pub ts_offset: i32, pub timestamp: u32, pub seqnum_offset: i16, pub seqnum: u16, pub max_ptime: i64, pub pt: c_uint, pub ssrc: c_uint, pub current_ssrc: c_uint, pub mtu: c_uint, pub segment: gst::GstSegment, pub min_ptime: u64, pub ptime: u64, pub ptime_multiple: u64, pub priv_: *mut GstRTPBasePayloadPrivate, pub _gst_reserved: [gpointer; 4], } impl ::std::fmt::Debug for GstRTPBasePayload { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstRTPBasePayload @ {:p}", self)) .field("element", &self.element) .finish() } } #[derive(Copy, Clone)] #[repr(C)] pub struct GstRTPHeaderExtension { pub parent: gst::GstElement, pub _gst_reserved: [gpointer; 4], } impl ::std::fmt::Debug for GstRTPHeaderExtension { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_struct(&format!("GstRTPHeaderExtension @ {:p}", self)) .field("parent", &self.parent) .finish() } } #[link(name = "gstrtp-1.0")] extern "C" { //========================================================================= // GstRTCPFBType //========================================================================= pub fn gst_rtcpfb_type_get_type() -> GType; //========================================================================= // GstRTCPSDESType //========================================================================= pub fn gst_rtcpsdes_type_get_type() -> GType; //========================================================================= // GstRTCPType //========================================================================= pub fn gst_rtcp_type_get_type() -> GType; //========================================================================= // GstRTCPXRType //========================================================================= #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcpxr_type_get_type() -> GType; //========================================================================= // GstRTPPayload //========================================================================= pub fn gst_rtp_payload_get_type() -> GType; //========================================================================= // GstRTPProfile //========================================================================= pub fn gst_rtp_profile_get_type() -> GType; //========================================================================= // GstRTPBufferFlags //========================================================================= #[cfg(any(feature = "v1_10", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))] pub fn gst_rtp_buffer_flags_get_type() -> GType; //========================================================================= // GstRTPBufferMapFlags //========================================================================= pub fn gst_rtp_buffer_map_flags_get_type() -> GType; //========================================================================= // GstRTPHeaderExtensionDirection //========================================================================= #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_direction_get_type() -> GType; //========================================================================= // GstRTPHeaderExtensionFlags //========================================================================= #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_flags_get_type() -> GType; //========================================================================= // GstRTCPBuffer //========================================================================= pub fn gst_rtcp_buffer_add_packet( rtcp: *mut GstRTCPBuffer, type_: GstRTCPType, packet: *mut GstRTCPPacket, ) -> gboolean; pub fn gst_rtcp_buffer_get_first_packet( rtcp: *mut GstRTCPBuffer, packet: *mut GstRTCPPacket, ) -> gboolean; pub fn gst_rtcp_buffer_get_packet_count(rtcp: *mut GstRTCPBuffer) -> c_uint; pub fn gst_rtcp_buffer_unmap(rtcp: *mut GstRTCPBuffer) -> gboolean; pub fn gst_rtcp_buffer_map( buffer: *mut gst::GstBuffer, flags: gst::GstMapFlags, rtcp: *mut GstRTCPBuffer, ) -> gboolean; pub fn gst_rtcp_buffer_new(mtu: c_uint) -> *mut gst::GstBuffer; pub fn gst_rtcp_buffer_new_copy_data(data: gconstpointer, len: c_uint) -> *mut gst::GstBuffer; pub fn gst_rtcp_buffer_new_take_data(data: gpointer, len: c_uint) -> *mut gst::GstBuffer; pub fn gst_rtcp_buffer_validate(buffer: *mut gst::GstBuffer) -> gboolean; pub fn gst_rtcp_buffer_validate_data(data: *mut u8, len: c_uint) -> gboolean; pub fn gst_rtcp_buffer_validate_data_reduced(data: *mut u8, len: c_uint) -> gboolean; pub fn gst_rtcp_buffer_validate_reduced(buffer: *mut gst::GstBuffer) -> gboolean; //========================================================================= // GstRTCPPacket //========================================================================= #[cfg(any(feature = "v1_10", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))] pub fn gst_rtcp_packet_add_profile_specific_ext( packet: *mut GstRTCPPacket, data: *const u8, len: c_uint, ) -> gboolean; pub fn gst_rtcp_packet_add_rb( packet: *mut GstRTCPPacket, ssrc: u32, fractionlost: u8, packetslost: i32, exthighestseq: u32, jitter: u32, lsr: u32, dlsr: u32, ) -> gboolean; #[cfg(any(feature = "v1_10", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))] pub fn gst_rtcp_packet_app_get_data(packet: *mut GstRTCPPacket) -> *mut u8; #[cfg(any(feature = "v1_10", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))] pub fn gst_rtcp_packet_app_get_data_length(packet: *mut GstRTCPPacket) -> u16; #[cfg(any(feature = "v1_10", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))] pub fn gst_rtcp_packet_app_get_name(packet: *mut GstRTCPPacket) -> *const c_char; #[cfg(any(feature = "v1_10", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))] pub fn gst_rtcp_packet_app_get_ssrc(packet: *mut GstRTCPPacket) -> u32; #[cfg(any(feature = "v1_10", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))] pub fn gst_rtcp_packet_app_get_subtype(packet: *mut GstRTCPPacket) -> u8; #[cfg(any(feature = "v1_10", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))] pub fn gst_rtcp_packet_app_set_data_length( packet: *mut GstRTCPPacket, wordlen: u16, ) -> gboolean; #[cfg(any(feature = "v1_10", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))] pub fn gst_rtcp_packet_app_set_name(packet: *mut GstRTCPPacket, name: *const c_char); #[cfg(any(feature = "v1_10", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))] pub fn gst_rtcp_packet_app_set_ssrc(packet: *mut GstRTCPPacket, ssrc: u32); #[cfg(any(feature = "v1_10", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))] pub fn gst_rtcp_packet_app_set_subtype(packet: *mut GstRTCPPacket, subtype: u8); pub fn gst_rtcp_packet_bye_add_ssrc(packet: *mut GstRTCPPacket, ssrc: u32) -> gboolean; pub fn gst_rtcp_packet_bye_add_ssrcs( packet: *mut GstRTCPPacket, ssrc: *mut u32, len: c_uint, ) -> gboolean; pub fn gst_rtcp_packet_bye_get_nth_ssrc(packet: *mut GstRTCPPacket, nth: c_uint) -> u32; pub fn gst_rtcp_packet_bye_get_reason(packet: *mut GstRTCPPacket) -> *mut c_char; pub fn gst_rtcp_packet_bye_get_reason_len(packet: *mut GstRTCPPacket) -> u8; pub fn gst_rtcp_packet_bye_get_ssrc_count(packet: *mut GstRTCPPacket) -> c_uint; pub fn gst_rtcp_packet_bye_set_reason( packet: *mut GstRTCPPacket, reason: *const c_char, ) -> gboolean; #[cfg(any(feature = "v1_10", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))] pub fn gst_rtcp_packet_copy_profile_specific_ext( packet: *mut GstRTCPPacket, data: *mut *mut u8, len: *mut c_uint, ) -> gboolean; pub fn gst_rtcp_packet_fb_get_fci(packet: *mut GstRTCPPacket) -> *mut u8; pub fn gst_rtcp_packet_fb_get_fci_length(packet: *mut GstRTCPPacket) -> u16; pub fn gst_rtcp_packet_fb_get_media_ssrc(packet: *mut GstRTCPPacket) -> u32; pub fn gst_rtcp_packet_fb_get_sender_ssrc(packet: *mut GstRTCPPacket) -> u32; pub fn gst_rtcp_packet_fb_get_type(packet: *mut GstRTCPPacket) -> GstRTCPFBType; pub fn gst_rtcp_packet_fb_set_fci_length(packet: *mut GstRTCPPacket, wordlen: u16) -> gboolean; pub fn gst_rtcp_packet_fb_set_media_ssrc(packet: *mut GstRTCPPacket, ssrc: u32); pub fn gst_rtcp_packet_fb_set_sender_ssrc(packet: *mut GstRTCPPacket, ssrc: u32); pub fn gst_rtcp_packet_fb_set_type(packet: *mut GstRTCPPacket, type_: GstRTCPFBType); pub fn gst_rtcp_packet_get_count(packet: *mut GstRTCPPacket) -> u8; pub fn gst_rtcp_packet_get_length(packet: *mut GstRTCPPacket) -> u16; pub fn gst_rtcp_packet_get_padding(packet: *mut GstRTCPPacket) -> gboolean; #[cfg(any(feature = "v1_10", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))] pub fn gst_rtcp_packet_get_profile_specific_ext( packet: *mut GstRTCPPacket, data: *mut *mut u8, len: *mut c_uint, ) -> gboolean; #[cfg(any(feature = "v1_10", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_10")))] pub fn gst_rtcp_packet_get_profile_specific_ext_length(packet: *mut GstRTCPPacket) -> u16; pub fn gst_rtcp_packet_get_rb( packet: *mut GstRTCPPacket, nth: c_uint, ssrc: *mut u32, fractionlost: *mut u8, packetslost: *mut i32, exthighestseq: *mut u32, jitter: *mut u32, lsr: *mut u32, dlsr: *mut u32, ); pub fn gst_rtcp_packet_get_rb_count(packet: *mut GstRTCPPacket) -> c_uint; pub fn gst_rtcp_packet_get_type(packet: *mut GstRTCPPacket) -> GstRTCPType; pub fn gst_rtcp_packet_move_to_next(packet: *mut GstRTCPPacket) -> gboolean; pub fn gst_rtcp_packet_remove(packet: *mut GstRTCPPacket) -> gboolean; pub fn gst_rtcp_packet_rr_get_ssrc(packet: *mut GstRTCPPacket) -> u32; pub fn gst_rtcp_packet_rr_set_ssrc(packet: *mut GstRTCPPacket, ssrc: u32); pub fn gst_rtcp_packet_sdes_add_entry( packet: *mut GstRTCPPacket, type_: GstRTCPSDESType, len: u8, data: *const u8, ) -> gboolean; pub fn gst_rtcp_packet_sdes_add_item(packet: *mut GstRTCPPacket, ssrc: u32) -> gboolean; pub fn gst_rtcp_packet_sdes_copy_entry( packet: *mut GstRTCPPacket, type_: *mut GstRTCPSDESType, len: *mut u8, data: *mut *mut u8, ) -> gboolean; pub fn gst_rtcp_packet_sdes_first_entry(packet: *mut GstRTCPPacket) -> gboolean; pub fn gst_rtcp_packet_sdes_first_item(packet: *mut GstRTCPPacket) -> gboolean; pub fn gst_rtcp_packet_sdes_get_entry( packet: *mut GstRTCPPacket, type_: *mut GstRTCPSDESType, len: *mut u8, data: *mut *mut u8, ) -> gboolean; pub fn gst_rtcp_packet_sdes_get_item_count(packet: *mut GstRTCPPacket) -> c_uint; pub fn gst_rtcp_packet_sdes_get_ssrc(packet: *mut GstRTCPPacket) -> u32; pub fn gst_rtcp_packet_sdes_next_entry(packet: *mut GstRTCPPacket) -> gboolean; pub fn gst_rtcp_packet_sdes_next_item(packet: *mut GstRTCPPacket) -> gboolean; pub fn gst_rtcp_packet_set_rb( packet: *mut GstRTCPPacket, nth: c_uint, ssrc: u32, fractionlost: u8, packetslost: i32, exthighestseq: u32, jitter: u32, lsr: u32, dlsr: u32, ); pub fn gst_rtcp_packet_sr_get_sender_info( packet: *mut GstRTCPPacket, ssrc: *mut u32, ntptime: *mut u64, rtptime: *mut u32, packet_count: *mut u32, octet_count: *mut u32, ); pub fn gst_rtcp_packet_sr_set_sender_info( packet: *mut GstRTCPPacket, ssrc: u32, ntptime: u64, rtptime: u32, packet_count: u32, octet_count: u32, ); #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_first_rb(packet: *mut GstRTCPPacket) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_block_length(packet: *mut GstRTCPPacket) -> u16; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_block_type(packet: *mut GstRTCPPacket) -> GstRTCPXRType; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_dlrr_block( packet: *mut GstRTCPPacket, nth: c_uint, ssrc: *mut u32, last_rr: *mut u32, delay: *mut u32, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_prt_by_seq( packet: *mut GstRTCPPacket, seq: u16, receipt_time: *mut u32, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_prt_info( packet: *mut GstRTCPPacket, ssrc: *mut u32, thinning: *mut u8, begin_seq: *mut u16, end_seq: *mut u16, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_rle_info( packet: *mut GstRTCPPacket, ssrc: *mut u32, thinning: *mut u8, begin_seq: *mut u16, end_seq: *mut u16, chunk_count: *mut u32, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_rle_nth_chunk( packet: *mut GstRTCPPacket, nth: c_uint, chunk: *mut u16, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_rrt(packet: *mut GstRTCPPacket, timestamp: *mut u64) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_ssrc(packet: *mut GstRTCPPacket) -> u32; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_summary_info( packet: *mut GstRTCPPacket, ssrc: *mut u32, begin_seq: *mut u16, end_seq: *mut u16, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_summary_jitter( packet: *mut GstRTCPPacket, min_jitter: *mut u32, max_jitter: *mut u32, mean_jitter: *mut u32, dev_jitter: *mut u32, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_summary_pkt( packet: *mut GstRTCPPacket, lost_packets: *mut u32, dup_packets: *mut u32, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_summary_ttl( packet: *mut GstRTCPPacket, is_ipv4: *mut gboolean, min_ttl: *mut u8, max_ttl: *mut u8, mean_ttl: *mut u8, dev_ttl: *mut u8, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_voip_burst_metrics( packet: *mut GstRTCPPacket, burst_density: *mut u8, gap_density: *mut u8, burst_duration: *mut u16, gap_duration: *mut u16, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_voip_configuration_params( packet: *mut GstRTCPPacket, gmin: *mut u8, rx_config: *mut u8, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_voip_delay_metrics( packet: *mut GstRTCPPacket, roundtrip_delay: *mut u16, end_system_delay: *mut u16, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_voip_jitter_buffer_params( packet: *mut GstRTCPPacket, jb_nominal: *mut u16, jb_maximum: *mut u16, jb_abs_max: *mut u16, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_voip_metrics_ssrc( packet: *mut GstRTCPPacket, ssrc: *mut u32, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_voip_packet_metrics( packet: *mut GstRTCPPacket, loss_rate: *mut u8, discard_rate: *mut u8, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_voip_quality_metrics( packet: *mut GstRTCPPacket, r_factor: *mut u8, ext_r_factor: *mut u8, mos_lq: *mut u8, mos_cq: *mut u8, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_get_voip_signal_metrics( packet: *mut GstRTCPPacket, signal_level: *mut u8, noise_level: *mut u8, rerl: *mut u8, gmin: *mut u8, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtcp_packet_xr_next_rb(packet: *mut GstRTCPPacket) -> gboolean; //========================================================================= // GstRTPBuffer //========================================================================= pub fn gst_rtp_buffer_add_extension_onebyte_header( rtp: *mut GstRTPBuffer, id: u8, data: gconstpointer, size: c_uint, ) -> gboolean; pub fn gst_rtp_buffer_add_extension_twobytes_header( rtp: *mut GstRTPBuffer, appbits: u8, id: u8, data: gconstpointer, size: c_uint, ) -> gboolean; pub fn gst_rtp_buffer_get_csrc(rtp: *mut GstRTPBuffer, idx: u8) -> u32; pub fn gst_rtp_buffer_get_csrc_count(rtp: *mut GstRTPBuffer) -> u8; pub fn gst_rtp_buffer_get_extension(rtp: *mut GstRTPBuffer) -> gboolean; pub fn gst_rtp_buffer_get_extension_bytes( rtp: *mut GstRTPBuffer, bits: *mut u16, ) -> *mut glib::GBytes; pub fn gst_rtp_buffer_get_extension_data( rtp: *mut GstRTPBuffer, bits: *mut u16, data: *mut u8, wordlen: *mut c_uint, ) -> gboolean; pub fn gst_rtp_buffer_get_extension_onebyte_header( rtp: *mut GstRTPBuffer, id: u8, nth: c_uint, data: *mut u8, size: *mut c_uint, ) -> gboolean; pub fn gst_rtp_buffer_get_extension_twobytes_header( rtp: *mut GstRTPBuffer, appbits: *mut u8, id: u8, nth: c_uint, data: *mut u8, size: *mut c_uint, ) -> gboolean; pub fn gst_rtp_buffer_get_header_len(rtp: *mut GstRTPBuffer) -> c_uint; pub fn gst_rtp_buffer_get_marker(rtp: *mut GstRTPBuffer) -> gboolean; pub fn gst_rtp_buffer_get_packet_len(rtp: *mut GstRTPBuffer) -> c_uint; pub fn gst_rtp_buffer_get_padding(rtp: *mut GstRTPBuffer) -> gboolean; pub fn gst_rtp_buffer_get_payload(rtp: *mut GstRTPBuffer) -> gpointer; pub fn gst_rtp_buffer_get_payload_buffer(rtp: *mut GstRTPBuffer) -> *mut gst::GstBuffer; pub fn gst_rtp_buffer_get_payload_bytes(rtp: *mut GstRTPBuffer) -> *mut glib::GBytes; pub fn gst_rtp_buffer_get_payload_len(rtp: *mut GstRTPBuffer) -> c_uint; pub fn gst_rtp_buffer_get_payload_subbuffer( rtp: *mut GstRTPBuffer, offset: c_uint, len: c_uint, ) -> *mut gst::GstBuffer; pub fn gst_rtp_buffer_get_payload_type(rtp: *mut GstRTPBuffer) -> u8; pub fn gst_rtp_buffer_get_seq(rtp: *mut GstRTPBuffer) -> u16; pub fn gst_rtp_buffer_get_ssrc(rtp: *mut GstRTPBuffer) -> u32; pub fn gst_rtp_buffer_get_timestamp(rtp: *mut GstRTPBuffer) -> u32; pub fn gst_rtp_buffer_get_version(rtp: *mut GstRTPBuffer) -> u8; pub fn gst_rtp_buffer_pad_to(rtp: *mut GstRTPBuffer, len: c_uint); #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_buffer_remove_extension_data(rtp: *mut GstRTPBuffer); pub fn gst_rtp_buffer_set_csrc(rtp: *mut GstRTPBuffer, idx: u8, csrc: u32); pub fn gst_rtp_buffer_set_extension(rtp: *mut GstRTPBuffer, extension: gboolean); pub fn gst_rtp_buffer_set_extension_data( rtp: *mut GstRTPBuffer, bits: u16, length: u16, ) -> gboolean; pub fn gst_rtp_buffer_set_marker(rtp: *mut GstRTPBuffer, marker: gboolean); pub fn gst_rtp_buffer_set_packet_len(rtp: *mut GstRTPBuffer, len: c_uint); pub fn gst_rtp_buffer_set_padding(rtp: *mut GstRTPBuffer, padding: gboolean); pub fn gst_rtp_buffer_set_payload_type(rtp: *mut GstRTPBuffer, payload_type: u8); pub fn gst_rtp_buffer_set_seq(rtp: *mut GstRTPBuffer, seq: u16); pub fn gst_rtp_buffer_set_ssrc(rtp: *mut GstRTPBuffer, ssrc: u32); pub fn gst_rtp_buffer_set_timestamp(rtp: *mut GstRTPBuffer, timestamp: u32); pub fn gst_rtp_buffer_set_version(rtp: *mut GstRTPBuffer, version: u8); pub fn gst_rtp_buffer_unmap(rtp: *mut GstRTPBuffer); pub fn gst_rtp_buffer_allocate_data( buffer: *mut gst::GstBuffer, payload_len: c_uint, pad_len: u8, csrc_count: u8, ); pub fn gst_rtp_buffer_calc_header_len(csrc_count: u8) -> c_uint; pub fn gst_rtp_buffer_calc_packet_len( payload_len: c_uint, pad_len: u8, csrc_count: u8, ) -> c_uint; pub fn gst_rtp_buffer_calc_payload_len( packet_len: c_uint, pad_len: u8, csrc_count: u8, ) -> c_uint; pub fn gst_rtp_buffer_compare_seqnum(seqnum1: u16, seqnum2: u16) -> c_int; pub fn gst_rtp_buffer_default_clock_rate(payload_type: u8) -> u32; pub fn gst_rtp_buffer_ext_timestamp(exttimestamp: *mut u64, timestamp: u32) -> u64; #[cfg(any(feature = "v1_18", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_18")))] pub fn gst_rtp_buffer_get_extension_onebyte_header_from_bytes( bytes: *mut glib::GBytes, bit_pattern: u16, id: u8, nth: c_uint, data: *mut u8, size: *mut c_uint, ) -> gboolean; pub fn gst_rtp_buffer_map( buffer: *mut gst::GstBuffer, flags: gst::GstMapFlags, rtp: *mut GstRTPBuffer, ) -> gboolean; pub fn gst_rtp_buffer_new_allocate( payload_len: c_uint, pad_len: u8, csrc_count: u8, ) -> *mut gst::GstBuffer; pub fn gst_rtp_buffer_new_allocate_len( packet_len: c_uint, pad_len: u8, csrc_count: u8, ) -> *mut gst::GstBuffer; pub fn gst_rtp_buffer_new_copy_data(data: gconstpointer, len: size_t) -> *mut gst::GstBuffer; pub fn gst_rtp_buffer_new_take_data(data: gpointer, len: size_t) -> *mut gst::GstBuffer; //========================================================================= // GstRTPHeaderExtensionClass //========================================================================= #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_class_set_uri( klass: *mut GstRTPHeaderExtensionClass, uri: *const c_char, ); //========================================================================= // GstRTPPayloadInfo //========================================================================= pub fn gst_rtp_payload_info_for_name( media: *const c_char, encoding_name: *const c_char, ) -> *const GstRTPPayloadInfo; pub fn gst_rtp_payload_info_for_pt(payload_type: u8) -> *const GstRTPPayloadInfo; //========================================================================= // GstRTPSourceMeta //========================================================================= #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtp_source_meta_append_csrc( meta: *mut GstRTPSourceMeta, csrc: *const u32, csrc_count: c_uint, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtp_source_meta_get_source_count(meta: *const GstRTPSourceMeta) -> c_uint; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtp_source_meta_set_ssrc(meta: *mut GstRTPSourceMeta, ssrc: *mut u32) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtp_source_meta_get_info() -> *const gst::GstMetaInfo; //========================================================================= // GstRTPBaseAudioPayload //========================================================================= pub fn gst_rtp_base_audio_payload_get_type() -> GType; pub fn gst_rtp_base_audio_payload_flush( baseaudiopayload: *mut GstRTPBaseAudioPayload, payload_len: c_uint, timestamp: gst::GstClockTime, ) -> gst::GstFlowReturn; pub fn gst_rtp_base_audio_payload_get_adapter( rtpbaseaudiopayload: *mut GstRTPBaseAudioPayload, ) -> *mut gst_base::GstAdapter; pub fn gst_rtp_base_audio_payload_push( baseaudiopayload: *mut GstRTPBaseAudioPayload, data: *const u8, payload_len: c_uint, timestamp: gst::GstClockTime, ) -> gst::GstFlowReturn; pub fn gst_rtp_base_audio_payload_set_frame_based( rtpbaseaudiopayload: *mut GstRTPBaseAudioPayload, ); pub fn gst_rtp_base_audio_payload_set_frame_options( rtpbaseaudiopayload: *mut GstRTPBaseAudioPayload, frame_duration: c_int, frame_size: c_int, ); pub fn gst_rtp_base_audio_payload_set_sample_based( rtpbaseaudiopayload: *mut GstRTPBaseAudioPayload, ); pub fn gst_rtp_base_audio_payload_set_sample_options( rtpbaseaudiopayload: *mut GstRTPBaseAudioPayload, sample_size: c_int, ); pub fn gst_rtp_base_audio_payload_set_samplebits_options( rtpbaseaudiopayload: *mut GstRTPBaseAudioPayload, sample_size: c_int, ); //========================================================================= // GstRTPBaseDepayload //========================================================================= pub fn gst_rtp_base_depayload_get_type() -> GType; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtp_base_depayload_is_source_info_enabled( depayload: *mut GstRTPBaseDepayload, ) -> gboolean; pub fn gst_rtp_base_depayload_push( filter: *mut GstRTPBaseDepayload, out_buf: *mut gst::GstBuffer, ) -> gst::GstFlowReturn; pub fn gst_rtp_base_depayload_push_list( filter: *mut GstRTPBaseDepayload, out_list: *mut gst::GstBufferList, ) -> gst::GstFlowReturn; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtp_base_depayload_set_source_info_enabled( depayload: *mut GstRTPBaseDepayload, enable: gboolean, ); //========================================================================= // GstRTPBasePayload //========================================================================= pub fn gst_rtp_base_payload_get_type() -> GType; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtp_base_payload_allocate_output_buffer( payload: *mut GstRTPBasePayload, payload_len: c_uint, pad_len: u8, csrc_count: u8, ) -> *mut gst::GstBuffer; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtp_base_payload_get_source_count( payload: *mut GstRTPBasePayload, buffer: *mut gst::GstBuffer, ) -> c_uint; pub fn gst_rtp_base_payload_is_filled( payload: *mut GstRTPBasePayload, size: c_uint, duration: gst::GstClockTime, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtp_base_payload_is_source_info_enabled(payload: *mut GstRTPBasePayload) -> gboolean; pub fn gst_rtp_base_payload_push( payload: *mut GstRTPBasePayload, buffer: *mut gst::GstBuffer, ) -> gst::GstFlowReturn; pub fn gst_rtp_base_payload_push_list( payload: *mut GstRTPBasePayload, list: *mut gst::GstBufferList, ) -> gst::GstFlowReturn; pub fn gst_rtp_base_payload_set_options( payload: *mut GstRTPBasePayload, media: *const c_char, dynamic: gboolean, encoding_name: *const c_char, clock_rate: u32, ); pub fn gst_rtp_base_payload_set_outcaps( payload: *mut GstRTPBasePayload, fieldname: *const c_char, ... ) -> gboolean; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_base_payload_set_outcaps_structure( payload: *mut GstRTPBasePayload, s: *mut gst::GstStructure, ) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtp_base_payload_set_source_info_enabled( payload: *mut GstRTPBasePayload, enable: gboolean, ); //========================================================================= // GstRTPHeaderExtension //========================================================================= #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_get_type() -> GType; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_create_from_uri( uri: *const c_char, ) -> *mut GstRTPHeaderExtension; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_get_direction( ext: *mut GstRTPHeaderExtension, ) -> GstRTPHeaderExtensionDirection; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_get_id(ext: *mut GstRTPHeaderExtension) -> c_uint; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_get_max_size( ext: *mut GstRTPHeaderExtension, input_meta: *const gst::GstBuffer, ) -> size_t; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_get_sdp_caps_field_name( ext: *mut GstRTPHeaderExtension, ) -> *mut c_char; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_get_supported_flags( ext: *mut GstRTPHeaderExtension, ) -> GstRTPHeaderExtensionFlags; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_get_uri(ext: *mut GstRTPHeaderExtension) -> *const c_char; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_read( ext: *mut GstRTPHeaderExtension, read_flags: GstRTPHeaderExtensionFlags, data: *const u8, size: size_t, buffer: *mut gst::GstBuffer, ) -> gboolean; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_set_attributes_from_caps( ext: *mut GstRTPHeaderExtension, caps: *const gst::GstCaps, ) -> gboolean; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_set_caps_from_attributes( ext: *mut GstRTPHeaderExtension, caps: *mut gst::GstCaps, ) -> gboolean; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_set_caps_from_attributes_helper( ext: *mut GstRTPHeaderExtension, caps: *mut gst::GstCaps, attributes: *const c_char, ) -> gboolean; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_set_direction( ext: *mut GstRTPHeaderExtension, direction: GstRTPHeaderExtensionDirection, ); #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_set_id(ext: *mut GstRTPHeaderExtension, ext_id: c_uint); #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_set_non_rtp_sink_caps( ext: *mut GstRTPHeaderExtension, caps: *const gst::GstCaps, ) -> gboolean; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_set_wants_update_non_rtp_src_caps( ext: *mut GstRTPHeaderExtension, state: gboolean, ); #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_update_non_rtp_src_caps( ext: *mut GstRTPHeaderExtension, caps: *mut gst::GstCaps, ) -> gboolean; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_wants_update_non_rtp_src_caps( ext: *mut GstRTPHeaderExtension, ) -> gboolean; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_header_extension_write( ext: *mut GstRTPHeaderExtension, input_meta: *const gst::GstBuffer, write_flags: GstRTPHeaderExtensionFlags, output: *mut gst::GstBuffer, data: *mut u8, size: size_t, ) -> ssize_t; //========================================================================= // Other functions //========================================================================= #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_buffer_add_rtp_source_meta( buffer: *mut gst::GstBuffer, ssrc: *const u32, csrc: *const u32, csrc_count: c_uint, ) -> *mut GstRTPSourceMeta; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_buffer_get_rtp_source_meta(buffer: *mut gst::GstBuffer) -> *mut GstRTPSourceMeta; pub fn gst_rtcp_ntp_to_unix(ntptime: u64) -> u64; pub fn gst_rtcp_sdes_name_to_type(name: *const c_char) -> GstRTCPSDESType; pub fn gst_rtcp_sdes_type_to_name(type_: GstRTCPSDESType) -> *const c_char; pub fn gst_rtcp_unix_to_ntp(unixtime: u64) -> u64; #[cfg(any(feature = "v1_20", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_20")))] pub fn gst_rtp_get_header_extension_list() -> *mut glib::GList; pub fn gst_rtp_hdrext_get_ntp_56(data: gpointer, size: c_uint, ntptime: *mut u64) -> gboolean; pub fn gst_rtp_hdrext_get_ntp_64(data: gpointer, size: c_uint, ntptime: *mut u64) -> gboolean; pub fn gst_rtp_hdrext_set_ntp_56(data: gpointer, size: c_uint, ntptime: u64) -> gboolean; pub fn gst_rtp_hdrext_set_ntp_64(data: gpointer, size: c_uint, ntptime: u64) -> gboolean; #[cfg(any(feature = "v1_16", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v1_16")))] pub fn gst_rtp_source_meta_api_get_type() -> GType; }
42.850663
99
0.631431
1a23039fc9d9adce74f3084679736f60755e98f1
275
fn main() { env_logger::init_from_env(env_logger::Env::default().filter_or("WAIT_LOGGER_LEVEL", "debug")); let mut sleep = wait::sleeper::new(); wait::wait(&mut sleep, &wait::config_from_env(), &mut on_timeout); } fn on_timeout() { std::process::exit(1); }
25
98
0.654545
232d3ef53851078ca455023433f3b0e6260b1a74
30,492
#[doc = "Reader of register PCR3"] pub type R = crate::R<u32, super::PCR3>; #[doc = "Writer for register PCR3"] pub type W = crate::W<u32, super::PCR3>; #[doc = "Register PCR3 `reset()`'s with value 0x0743"] impl crate::ResetValue for super::PCR3 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0743 } } #[doc = "Pull Select\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PS_A { #[doc = "0: Internal pulldown resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set."] _0 = 0, #[doc = "1: Internal pullup resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set."] _1 = 1, } impl From<PS_A> for bool { #[inline(always)] fn from(variant: PS_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PS`"] pub type PS_R = crate::R<bool, PS_A>; impl PS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PS_A { match self.bits { false => PS_A::_0, true => PS_A::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline(always)] pub fn is_0(&self) -> bool { *self == PS_A::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline(always)] pub fn is_1(&self) -> bool { *self == PS_A::_1 } } #[doc = "Write proxy for field `PS`"] pub struct PS_W<'a> { w: &'a mut W, } impl<'a> PS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PS_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Internal pulldown resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set."] #[inline(always)] pub fn _0(self) -> &'a mut W { self.variant(PS_A::_0) } #[doc = "Internal pullup resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set."] #[inline(always)] pub fn _1(self) -> &'a mut W { self.variant(PS_A::_1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Pull Enable\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PE_A { #[doc = "0: Internal pullup or pulldown resistor is not enabled on the corresponding pin."] _0 = 0, #[doc = "1: Internal pullup or pulldown resistor is enabled on the corresponding pin, if the pin is configured as a digital input."] _1 = 1, } impl From<PE_A> for bool { #[inline(always)] fn from(variant: PE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PE`"] pub type PE_R = crate::R<bool, PE_A>; impl PE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PE_A { match self.bits { false => PE_A::_0, true => PE_A::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline(always)] pub fn is_0(&self) -> bool { *self == PE_A::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline(always)] pub fn is_1(&self) -> bool { *self == PE_A::_1 } } #[doc = "Write proxy for field `PE`"] pub struct PE_W<'a> { w: &'a mut W, } impl<'a> PE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Internal pullup or pulldown resistor is not enabled on the corresponding pin."] #[inline(always)] pub fn _0(self) -> &'a mut W { self.variant(PE_A::_0) } #[doc = "Internal pullup or pulldown resistor is enabled on the corresponding pin, if the pin is configured as a digital input."] #[inline(always)] pub fn _1(self) -> &'a mut W { self.variant(PE_A::_1) } #[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 = "Slew Rate Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SRE_A { #[doc = "0: Fast slew rate is configured on the corresponding pin, if the pin is configured as a digital output."] _0 = 0, #[doc = "1: Slow slew rate is configured on the corresponding pin, if the pin is configured as a digital output."] _1 = 1, } impl From<SRE_A> for bool { #[inline(always)] fn from(variant: SRE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `SRE`"] pub type SRE_R = crate::R<bool, SRE_A>; impl SRE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SRE_A { match self.bits { false => SRE_A::_0, true => SRE_A::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline(always)] pub fn is_0(&self) -> bool { *self == SRE_A::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline(always)] pub fn is_1(&self) -> bool { *self == SRE_A::_1 } } #[doc = "Write proxy for field `SRE`"] pub struct SRE_W<'a> { w: &'a mut W, } impl<'a> SRE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SRE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Fast slew rate is configured on the corresponding pin, if the pin is configured as a digital output."] #[inline(always)] pub fn _0(self) -> &'a mut W { self.variant(SRE_A::_0) } #[doc = "Slow slew rate is configured on the corresponding pin, if the pin is configured as a digital output."] #[inline(always)] pub fn _1(self) -> &'a mut W { self.variant(SRE_A::_1) } #[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 = "Passive Filter Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PFE_A { #[doc = "0: Passive input filter is disabled on the corresponding pin."] _0 = 0, #[doc = "1: Passive input filter is enabled on the corresponding pin, if the pin is configured as a digital input. Refer to the device data sheet for filter characteristics."] _1 = 1, } impl From<PFE_A> for bool { #[inline(always)] fn from(variant: PFE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `PFE`"] pub type PFE_R = crate::R<bool, PFE_A>; impl PFE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PFE_A { match self.bits { false => PFE_A::_0, true => PFE_A::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline(always)] pub fn is_0(&self) -> bool { *self == PFE_A::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline(always)] pub fn is_1(&self) -> bool { *self == PFE_A::_1 } } #[doc = "Write proxy for field `PFE`"] pub struct PFE_W<'a> { w: &'a mut W, } impl<'a> PFE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PFE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Passive input filter is disabled on the corresponding pin."] #[inline(always)] pub fn _0(self) -> &'a mut W { self.variant(PFE_A::_0) } #[doc = "Passive input filter is enabled on the corresponding pin, if the pin is configured as a digital input. Refer to the device data sheet for filter characteristics."] #[inline(always)] pub fn _1(self) -> &'a mut W { self.variant(PFE_A::_1) } #[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 = "Open Drain Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ODE_A { #[doc = "0: Open drain output is disabled on the corresponding pin."] _0 = 0, #[doc = "1: Open drain output is enabled on the corresponding pin, if the pin is configured as a digital output."] _1 = 1, } impl From<ODE_A> for bool { #[inline(always)] fn from(variant: ODE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ODE`"] pub type ODE_R = crate::R<bool, ODE_A>; impl ODE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ODE_A { match self.bits { false => ODE_A::_0, true => ODE_A::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline(always)] pub fn is_0(&self) -> bool { *self == ODE_A::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline(always)] pub fn is_1(&self) -> bool { *self == ODE_A::_1 } } #[doc = "Write proxy for field `ODE`"] pub struct ODE_W<'a> { w: &'a mut W, } impl<'a> ODE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ODE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Open drain output is disabled on the corresponding pin."] #[inline(always)] pub fn _0(self) -> &'a mut W { self.variant(ODE_A::_0) } #[doc = "Open drain output is enabled on the corresponding pin, if the pin is configured as a digital output."] #[inline(always)] pub fn _1(self) -> &'a mut W { self.variant(ODE_A::_1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Drive Strength Enable\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DSE_A { #[doc = "0: Low drive strength is configured on the corresponding pin, if pin is configured as a digital output."] _0 = 0, #[doc = "1: High drive strength is configured on the corresponding pin, if pin is configured as a digital output."] _1 = 1, } impl From<DSE_A> for bool { #[inline(always)] fn from(variant: DSE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `DSE`"] pub type DSE_R = crate::R<bool, DSE_A>; impl DSE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DSE_A { match self.bits { false => DSE_A::_0, true => DSE_A::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline(always)] pub fn is_0(&self) -> bool { *self == DSE_A::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline(always)] pub fn is_1(&self) -> bool { *self == DSE_A::_1 } } #[doc = "Write proxy for field `DSE`"] pub struct DSE_W<'a> { w: &'a mut W, } impl<'a> DSE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DSE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Low drive strength is configured on the corresponding pin, if pin is configured as a digital output."] #[inline(always)] pub fn _0(self) -> &'a mut W { self.variant(DSE_A::_0) } #[doc = "High drive strength is configured on the corresponding pin, if pin is configured as a digital output."] #[inline(always)] pub fn _1(self) -> &'a mut W { self.variant(DSE_A::_1) } #[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 = "Pin Mux Control\n\nValue on reset: 7"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum MUX_A { #[doc = "0: Pin disabled (analog)."] _000 = 0, #[doc = "1: Alternative 1 (GPIO)."] _001 = 1, #[doc = "2: Alternative 2 (chip-specific)."] _010 = 2, #[doc = "3: Alternative 3 (chip-specific)."] _011 = 3, #[doc = "4: Alternative 4 (chip-specific)."] _100 = 4, #[doc = "5: Alternative 5 (chip-specific)."] _101 = 5, #[doc = "6: Alternative 6 (chip-specific)."] _110 = 6, #[doc = "7: Alternative 7 (chip-specific)."] _111 = 7, } impl From<MUX_A> for u8 { #[inline(always)] fn from(variant: MUX_A) -> Self { variant as _ } } #[doc = "Reader of field `MUX`"] pub type MUX_R = crate::R<u8, MUX_A>; impl MUX_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MUX_A { match self.bits { 0 => MUX_A::_000, 1 => MUX_A::_001, 2 => MUX_A::_010, 3 => MUX_A::_011, 4 => MUX_A::_100, 5 => MUX_A::_101, 6 => MUX_A::_110, 7 => MUX_A::_111, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `_000`"] #[inline(always)] pub fn is_000(&self) -> bool { *self == MUX_A::_000 } #[doc = "Checks if the value of the field is `_001`"] #[inline(always)] pub fn is_001(&self) -> bool { *self == MUX_A::_001 } #[doc = "Checks if the value of the field is `_010`"] #[inline(always)] pub fn is_010(&self) -> bool { *self == MUX_A::_010 } #[doc = "Checks if the value of the field is `_011`"] #[inline(always)] pub fn is_011(&self) -> bool { *self == MUX_A::_011 } #[doc = "Checks if the value of the field is `_100`"] #[inline(always)] pub fn is_100(&self) -> bool { *self == MUX_A::_100 } #[doc = "Checks if the value of the field is `_101`"] #[inline(always)] pub fn is_101(&self) -> bool { *self == MUX_A::_101 } #[doc = "Checks if the value of the field is `_110`"] #[inline(always)] pub fn is_110(&self) -> bool { *self == MUX_A::_110 } #[doc = "Checks if the value of the field is `_111`"] #[inline(always)] pub fn is_111(&self) -> bool { *self == MUX_A::_111 } } #[doc = "Write proxy for field `MUX`"] pub struct MUX_W<'a> { w: &'a mut W, } impl<'a> MUX_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MUX_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "Pin disabled (analog)."] #[inline(always)] pub fn _000(self) -> &'a mut W { self.variant(MUX_A::_000) } #[doc = "Alternative 1 (GPIO)."] #[inline(always)] pub fn _001(self) -> &'a mut W { self.variant(MUX_A::_001) } #[doc = "Alternative 2 (chip-specific)."] #[inline(always)] pub fn _010(self) -> &'a mut W { self.variant(MUX_A::_010) } #[doc = "Alternative 3 (chip-specific)."] #[inline(always)] pub fn _011(self) -> &'a mut W { self.variant(MUX_A::_011) } #[doc = "Alternative 4 (chip-specific)."] #[inline(always)] pub fn _100(self) -> &'a mut W { self.variant(MUX_A::_100) } #[doc = "Alternative 5 (chip-specific)."] #[inline(always)] pub fn _101(self) -> &'a mut W { self.variant(MUX_A::_101) } #[doc = "Alternative 6 (chip-specific)."] #[inline(always)] pub fn _110(self) -> &'a mut W { self.variant(MUX_A::_110) } #[doc = "Alternative 7 (chip-specific)."] #[inline(always)] pub fn _111(self) -> &'a mut W { self.variant(MUX_A::_111) } #[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 & !(0x07 << 8)) | (((value as u32) & 0x07) << 8); self.w } } #[doc = "Lock Register\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LK_A { #[doc = "0: Pin Control Register fields \\[15:0\\] are not locked."] _0 = 0, #[doc = "1: Pin Control Register fields \\[15:0\\] are locked and cannot be updated until the next system reset."] _1 = 1, } impl From<LK_A> for bool { #[inline(always)] fn from(variant: LK_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LK`"] pub type LK_R = crate::R<bool, LK_A>; impl LK_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LK_A { match self.bits { false => LK_A::_0, true => LK_A::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline(always)] pub fn is_0(&self) -> bool { *self == LK_A::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline(always)] pub fn is_1(&self) -> bool { *self == LK_A::_1 } } #[doc = "Write proxy for field `LK`"] pub struct LK_W<'a> { w: &'a mut W, } impl<'a> LK_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LK_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Pin Control Register fields \\[15:0\\] are not locked."] #[inline(always)] pub fn _0(self) -> &'a mut W { self.variant(LK_A::_0) } #[doc = "Pin Control Register fields \\[15:0\\] are locked and cannot be updated until the next system reset."] #[inline(always)] pub fn _1(self) -> &'a mut W { self.variant(LK_A::_1) } #[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 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Interrupt Configuration\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum IRQC_A { #[doc = "0: Interrupt/DMA request disabled."] _0000 = 0, #[doc = "1: DMA request on rising edge."] _0001 = 1, #[doc = "2: DMA request on falling edge."] _0010 = 2, #[doc = "3: DMA request on either edge."] _0011 = 3, #[doc = "8: Interrupt when logic zero."] _1000 = 8, #[doc = "9: Interrupt on rising edge."] _1001 = 9, #[doc = "10: Interrupt on falling edge."] _1010 = 10, #[doc = "11: Interrupt on either edge."] _1011 = 11, #[doc = "12: Interrupt when logic one."] _1100 = 12, } impl From<IRQC_A> for u8 { #[inline(always)] fn from(variant: IRQC_A) -> Self { variant as _ } } #[doc = "Reader of field `IRQC`"] pub type IRQC_R = crate::R<u8, IRQC_A>; impl IRQC_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, IRQC_A> { use crate::Variant::*; match self.bits { 0 => Val(IRQC_A::_0000), 1 => Val(IRQC_A::_0001), 2 => Val(IRQC_A::_0010), 3 => Val(IRQC_A::_0011), 8 => Val(IRQC_A::_1000), 9 => Val(IRQC_A::_1001), 10 => Val(IRQC_A::_1010), 11 => Val(IRQC_A::_1011), 12 => Val(IRQC_A::_1100), i => Res(i), } } #[doc = "Checks if the value of the field is `_0000`"] #[inline(always)] pub fn is_0000(&self) -> bool { *self == IRQC_A::_0000 } #[doc = "Checks if the value of the field is `_0001`"] #[inline(always)] pub fn is_0001(&self) -> bool { *self == IRQC_A::_0001 } #[doc = "Checks if the value of the field is `_0010`"] #[inline(always)] pub fn is_0010(&self) -> bool { *self == IRQC_A::_0010 } #[doc = "Checks if the value of the field is `_0011`"] #[inline(always)] pub fn is_0011(&self) -> bool { *self == IRQC_A::_0011 } #[doc = "Checks if the value of the field is `_1000`"] #[inline(always)] pub fn is_1000(&self) -> bool { *self == IRQC_A::_1000 } #[doc = "Checks if the value of the field is `_1001`"] #[inline(always)] pub fn is_1001(&self) -> bool { *self == IRQC_A::_1001 } #[doc = "Checks if the value of the field is `_1010`"] #[inline(always)] pub fn is_1010(&self) -> bool { *self == IRQC_A::_1010 } #[doc = "Checks if the value of the field is `_1011`"] #[inline(always)] pub fn is_1011(&self) -> bool { *self == IRQC_A::_1011 } #[doc = "Checks if the value of the field is `_1100`"] #[inline(always)] pub fn is_1100(&self) -> bool { *self == IRQC_A::_1100 } } #[doc = "Write proxy for field `IRQC`"] pub struct IRQC_W<'a> { w: &'a mut W, } impl<'a> IRQC_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: IRQC_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "Interrupt/DMA request disabled."] #[inline(always)] pub fn _0000(self) -> &'a mut W { self.variant(IRQC_A::_0000) } #[doc = "DMA request on rising edge."] #[inline(always)] pub fn _0001(self) -> &'a mut W { self.variant(IRQC_A::_0001) } #[doc = "DMA request on falling edge."] #[inline(always)] pub fn _0010(self) -> &'a mut W { self.variant(IRQC_A::_0010) } #[doc = "DMA request on either edge."] #[inline(always)] pub fn _0011(self) -> &'a mut W { self.variant(IRQC_A::_0011) } #[doc = "Interrupt when logic zero."] #[inline(always)] pub fn _1000(self) -> &'a mut W { self.variant(IRQC_A::_1000) } #[doc = "Interrupt on rising edge."] #[inline(always)] pub fn _1001(self) -> &'a mut W { self.variant(IRQC_A::_1001) } #[doc = "Interrupt on falling edge."] #[inline(always)] pub fn _1010(self) -> &'a mut W { self.variant(IRQC_A::_1010) } #[doc = "Interrupt on either edge."] #[inline(always)] pub fn _1011(self) -> &'a mut W { self.variant(IRQC_A::_1011) } #[doc = "Interrupt when logic one."] #[inline(always)] pub fn _1100(self) -> &'a mut W { self.variant(IRQC_A::_1100) } #[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 = "Interrupt Status Flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ISF_A { #[doc = "0: Configured interrupt is not detected."] _0 = 0, #[doc = "1: Configured interrupt is detected. If the pin is configured to generate a DMA request, then the corresponding flag will be cleared automatically at the completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to the flag. If the pin is configured for a level sensitive interrupt and the pin remains asserted, then the flag is set again immediately after it is cleared."] _1 = 1, } impl From<ISF_A> for bool { #[inline(always)] fn from(variant: ISF_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ISF`"] pub type ISF_R = crate::R<bool, ISF_A>; impl ISF_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ISF_A { match self.bits { false => ISF_A::_0, true => ISF_A::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline(always)] pub fn is_0(&self) -> bool { *self == ISF_A::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline(always)] pub fn is_1(&self) -> bool { *self == ISF_A::_1 } } #[doc = "Write proxy for field `ISF`"] pub struct ISF_W<'a> { w: &'a mut W, } impl<'a> ISF_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ISF_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Configured interrupt is not detected."] #[inline(always)] pub fn _0(self) -> &'a mut W { self.variant(ISF_A::_0) } #[doc = "Configured interrupt is detected. If the pin is configured to generate a DMA request, then the corresponding flag will be cleared automatically at the completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to the flag. If the pin is configured for a level sensitive interrupt and the pin remains asserted, then the flag is set again immediately after it is cleared."] #[inline(always)] pub fn _1(self) -> &'a mut W { self.variant(ISF_A::_1) } #[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 << 24)) | (((value as u32) & 0x01) << 24); self.w } } impl R { #[doc = "Bit 0 - Pull Select"] #[inline(always)] pub fn ps(&self) -> PS_R { PS_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Pull Enable"] #[inline(always)] pub fn pe(&self) -> PE_R { PE_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Slew Rate Enable"] #[inline(always)] pub fn sre(&self) -> SRE_R { SRE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 4 - Passive Filter Enable"] #[inline(always)] pub fn pfe(&self) -> PFE_R { PFE_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - Open Drain Enable"] #[inline(always)] pub fn ode(&self) -> ODE_R { ODE_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - Drive Strength Enable"] #[inline(always)] pub fn dse(&self) -> DSE_R { DSE_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bits 8:10 - Pin Mux Control"] #[inline(always)] pub fn mux(&self) -> MUX_R { MUX_R::new(((self.bits >> 8) & 0x07) as u8) } #[doc = "Bit 15 - Lock Register"] #[inline(always)] pub fn lk(&self) -> LK_R { LK_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bits 16:19 - Interrupt Configuration"] #[inline(always)] pub fn irqc(&self) -> IRQC_R { IRQC_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bit 24 - Interrupt Status Flag"] #[inline(always)] pub fn isf(&self) -> ISF_R { ISF_R::new(((self.bits >> 24) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Pull Select"] #[inline(always)] pub fn ps(&mut self) -> PS_W { PS_W { w: self } } #[doc = "Bit 1 - Pull Enable"] #[inline(always)] pub fn pe(&mut self) -> PE_W { PE_W { w: self } } #[doc = "Bit 2 - Slew Rate Enable"] #[inline(always)] pub fn sre(&mut self) -> SRE_W { SRE_W { w: self } } #[doc = "Bit 4 - Passive Filter Enable"] #[inline(always)] pub fn pfe(&mut self) -> PFE_W { PFE_W { w: self } } #[doc = "Bit 5 - Open Drain Enable"] #[inline(always)] pub fn ode(&mut self) -> ODE_W { ODE_W { w: self } } #[doc = "Bit 6 - Drive Strength Enable"] #[inline(always)] pub fn dse(&mut self) -> DSE_W { DSE_W { w: self } } #[doc = "Bits 8:10 - Pin Mux Control"] #[inline(always)] pub fn mux(&mut self) -> MUX_W { MUX_W { w: self } } #[doc = "Bit 15 - Lock Register"] #[inline(always)] pub fn lk(&mut self) -> LK_W { LK_W { w: self } } #[doc = "Bits 16:19 - Interrupt Configuration"] #[inline(always)] pub fn irqc(&mut self) -> IRQC_W { IRQC_W { w: self } } #[doc = "Bit 24 - Interrupt Status Flag"] #[inline(always)] pub fn isf(&mut self) -> ISF_W { ISF_W { w: self } } }
29.806452
431
0.543684
33edd77900d1de2cdfbeb562663cc3f88a1399a6
765
use crate::lexer::SyntaxKind; use num_traits::{FromPrimitive, ToPrimitive}; #[derive(Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Clone, Copy)] pub(crate) enum ShakespeareProgrammingLanguage {} impl rowan::Language for ShakespeareProgrammingLanguage { type Kind = SyntaxKind; fn kind_from_raw(raw: rowan::SyntaxKind) -> Self::Kind { Self::Kind::from_u16(raw.0).unwrap() } fn kind_to_raw(kind: Self::Kind) -> rowan::SyntaxKind { rowan::SyntaxKind(kind.to_u16().unwrap()) } } pub(crate) type SyntaxNode = rowan::SyntaxNode<ShakespeareProgrammingLanguage>; pub(crate) type SyntaxElement = rowan::SyntaxElement<ShakespeareProgrammingLanguage>; pub(crate) type SyntaxToken = rowan::SyntaxToken<ShakespeareProgrammingLanguage>;
31.875
85
0.738562
1a5ffd93701c65bd0f81e90ccfe084679380854d
4,140
use super::ObjectSafetyViolation; use crate::infer::InferCtxt; use rustc_data_structures::fx::FxHashSet; use rustc_errors::{struct_span_err, DiagnosticBuilder}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::ty::TyCtxt; use rustc_span::{MultiSpan, Span}; use std::fmt; use std::iter; impl<'a, 'tcx> InferCtxt<'a, 'tcx> { pub fn report_extra_impl_obligation( &self, error_span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId, requirement: &dyn fmt::Display, ) -> DiagnosticBuilder<'tcx> { let msg = "impl has stricter requirements than trait"; let sp = self.tcx.sess.source_map().guess_head_span(error_span); let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg); if let Some(trait_item_span) = self.tcx.hir().span_if_local(trait_item_def_id) { let span = self.tcx.sess.source_map().guess_head_span(trait_item_span); let item_name = self.tcx.item_name(impl_item_def_id); err.span_label(span, format!("definition of `{}` from trait", item_name)); } err.span_label(sp, format!("impl has extra requirement {}", requirement)); err } } pub fn report_object_safety_error<'tcx>( tcx: TyCtxt<'tcx>, span: Span, trait_def_id: DefId, violations: &[ObjectSafetyViolation], ) -> DiagnosticBuilder<'tcx> { let trait_str = tcx.def_path_str(trait_def_id); let trait_span = tcx.hir().get_if_local(trait_def_id).and_then(|node| match node { hir::Node::Item(item) => Some(item.ident.span), _ => None, }); let span = tcx.sess.source_map().guess_head_span(span); let mut err = struct_span_err!( tcx.sess, span, E0038, "the trait `{}` cannot be made into an object", trait_str ); err.span_label(span, format!("`{}` cannot be made into an object", trait_str)); let mut reported_violations = FxHashSet::default(); let mut multi_span = vec![]; let mut messages = vec![]; for violation in violations { if let ObjectSafetyViolation::SizedSelf(sp) = &violation { if !sp.is_empty() { // Do not report `SizedSelf` without spans pointing at `SizedSelf` obligations // with a `Span`. reported_violations.insert(ObjectSafetyViolation::SizedSelf(vec![].into())); } } if reported_violations.insert(violation.clone()) { let spans = violation.spans(); let msg = if trait_span.is_none() || spans.is_empty() { format!("the trait cannot be made into an object because {}", violation.error_msg()) } else { format!("...because {}", violation.error_msg()) }; if spans.is_empty() { err.note(&msg); } else { for span in spans { multi_span.push(span); messages.push(msg.clone()); } } } } let has_multi_span = !multi_span.is_empty(); let mut note_span = MultiSpan::from_spans(multi_span.clone()); if let (Some(trait_span), true) = (trait_span, has_multi_span) { note_span .push_span_label(trait_span, "this trait cannot be made into an object...".to_string()); } for (span, msg) in iter::zip(multi_span, messages) { note_span.push_span_label(span, msg); } err.span_note( note_span, "for a trait to be \"object safe\" it needs to allow building a vtable to allow the call \ to be resolvable dynamically; for more information visit \ <https://doc.rust-lang.org/reference/items/traits.html#object-safety>", ); if trait_span.is_some() { let mut reported_violations: Vec<_> = reported_violations.into_iter().collect(); reported_violations.sort(); for violation in reported_violations { // Only provide the help if its a local trait, otherwise it's not actionable. violation.solution(&mut err); } } err }
36.964286
100
0.608213
d6aaf53f10246a3b1cd80d85ef5d6170f730f04f
14,636
use hir::HasSource; use ra_syntax::{ ast::{ self, edit::{self, AstNodeEdit, IndentLevel}, make, AstNode, NameOwner, }, SmolStr, }; use crate::{ assist_context::{AssistContext, Assists}, ast_transform::{self, AstTransform, QualifyPaths, SubstituteTypeParams}, utils::{get_missing_assoc_items, render_snippet, resolve_target_trait, Cursor}, AssistId, AssistKind, }; #[derive(PartialEq)] enum AddMissingImplMembersMode { DefaultMethodsOnly, NoDefaultMethods, } // Assist: add_impl_missing_members // // Adds scaffold for required impl members. // // ``` // trait Trait<T> { // Type X; // fn foo(&self) -> T; // fn bar(&self) {} // } // // impl Trait<u32> for () {<|> // // } // ``` // -> // ``` // trait Trait<T> { // Type X; // fn foo(&self) -> T; // fn bar(&self) {} // } // // impl Trait<u32> for () { // fn foo(&self) -> u32 { // ${0:todo!()} // } // // } // ``` pub(crate) fn add_missing_impl_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { add_missing_impl_members_inner( acc, ctx, AddMissingImplMembersMode::NoDefaultMethods, "add_impl_missing_members", "Implement missing members", ) } // Assist: add_impl_default_members // // Adds scaffold for overriding default impl members. // // ``` // trait Trait { // Type X; // fn foo(&self); // fn bar(&self) {} // } // // impl Trait for () { // Type X = (); // fn foo(&self) {}<|> // // } // ``` // -> // ``` // trait Trait { // Type X; // fn foo(&self); // fn bar(&self) {} // } // // impl Trait for () { // Type X = (); // fn foo(&self) {} // $0fn bar(&self) {} // // } // ``` pub(crate) fn add_missing_default_members(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { add_missing_impl_members_inner( acc, ctx, AddMissingImplMembersMode::DefaultMethodsOnly, "add_impl_default_members", "Implement default members", ) } fn add_missing_impl_members_inner( acc: &mut Assists, ctx: &AssistContext, mode: AddMissingImplMembersMode, assist_id: &'static str, label: &'static str, ) -> Option<()> { let _p = ra_prof::profile("add_missing_impl_members_inner"); let impl_def = ctx.find_node_at_offset::<ast::ImplDef>()?; let impl_item_list = impl_def.item_list()?; let trait_ = resolve_target_trait(&ctx.sema, &impl_def)?; let def_name = |item: &ast::AssocItem| -> Option<SmolStr> { match item { ast::AssocItem::FnDef(def) => def.name(), ast::AssocItem::TypeAliasDef(def) => def.name(), ast::AssocItem::ConstDef(def) => def.name(), } .map(|it| it.text().clone()) }; let missing_items = get_missing_assoc_items(&ctx.sema, &impl_def) .iter() .map(|i| match i { hir::AssocItem::Function(i) => ast::AssocItem::FnDef(i.source(ctx.db()).value), hir::AssocItem::TypeAlias(i) => ast::AssocItem::TypeAliasDef(i.source(ctx.db()).value), hir::AssocItem::Const(i) => ast::AssocItem::ConstDef(i.source(ctx.db()).value), }) .filter(|t| def_name(&t).is_some()) .filter(|t| match t { ast::AssocItem::FnDef(def) => match mode { AddMissingImplMembersMode::DefaultMethodsOnly => def.body().is_some(), AddMissingImplMembersMode::NoDefaultMethods => def.body().is_none(), }, _ => mode == AddMissingImplMembersMode::NoDefaultMethods, }) .collect::<Vec<_>>(); if missing_items.is_empty() { return None; } let target = impl_def.syntax().text_range(); acc.add(AssistId(assist_id, AssistKind::QuickFix), label, target, |builder| { let n_existing_items = impl_item_list.assoc_items().count(); let source_scope = ctx.sema.scope_for_def(trait_); let target_scope = ctx.sema.scope(impl_item_list.syntax()); let ast_transform = QualifyPaths::new(&target_scope, &source_scope) .or(SubstituteTypeParams::for_trait_impl(&source_scope, trait_, impl_def)); let items = missing_items .into_iter() .map(|it| ast_transform::apply(&*ast_transform, it)) .map(|it| match it { ast::AssocItem::FnDef(def) => ast::AssocItem::FnDef(add_body(def)), _ => it, }) .map(|it| edit::remove_attrs_and_docs(&it)); let new_impl_item_list = impl_item_list.append_items(items); let first_new_item = new_impl_item_list.assoc_items().nth(n_existing_items).unwrap(); let original_range = impl_item_list.syntax().text_range(); match ctx.config.snippet_cap { None => builder.replace(original_range, new_impl_item_list.to_string()), Some(cap) => { let mut cursor = Cursor::Before(first_new_item.syntax()); let placeholder; if let ast::AssocItem::FnDef(func) = &first_new_item { if let Some(m) = func.syntax().descendants().find_map(ast::MacroCall::cast) { if m.syntax().text() == "todo!()" { placeholder = m; cursor = Cursor::Replace(placeholder.syntax()); } } } builder.replace_snippet( cap, original_range, render_snippet(cap, new_impl_item_list.syntax(), cursor), ) } }; }) } fn add_body(fn_def: ast::FnDef) -> ast::FnDef { if fn_def.body().is_some() { return fn_def; } let body = make::block_expr(None, Some(make::expr_todo())).indent(IndentLevel(1)); fn_def.with_body(body) } #[cfg(test)] mod tests { use crate::tests::{check_assist, check_assist_not_applicable}; use super::*; #[test] fn test_add_missing_impl_members() { check_assist( add_missing_impl_members, r#" trait Foo { type Output; const CONST: usize = 42; fn foo(&self); fn bar(&self); fn baz(&self); } struct S; impl Foo for S { fn bar(&self) {} <|> }"#, r#" trait Foo { type Output; const CONST: usize = 42; fn foo(&self); fn bar(&self); fn baz(&self); } struct S; impl Foo for S { fn bar(&self) {} $0type Output; const CONST: usize = 42; fn foo(&self) { todo!() } fn baz(&self) { todo!() } }"#, ); } #[test] fn test_copied_overriden_members() { check_assist( add_missing_impl_members, r#" trait Foo { fn foo(&self); fn bar(&self) -> bool { true } fn baz(&self) -> u32 { 42 } } struct S; impl Foo for S { fn bar(&self) {} <|> }"#, r#" trait Foo { fn foo(&self); fn bar(&self) -> bool { true } fn baz(&self) -> u32 { 42 } } struct S; impl Foo for S { fn bar(&self) {} fn foo(&self) { ${0:todo!()} } }"#, ); } #[test] fn test_empty_impl_def() { check_assist( add_missing_impl_members, r#" trait Foo { fn foo(&self); } struct S; impl Foo for S { <|> }"#, r#" trait Foo { fn foo(&self); } struct S; impl Foo for S { fn foo(&self) { ${0:todo!()} } }"#, ); } #[test] fn fill_in_type_params_1() { check_assist( add_missing_impl_members, r#" trait Foo<T> { fn foo(&self, t: T) -> &T; } struct S; impl Foo<u32> for S { <|> }"#, r#" trait Foo<T> { fn foo(&self, t: T) -> &T; } struct S; impl Foo<u32> for S { fn foo(&self, t: u32) -> &u32 { ${0:todo!()} } }"#, ); } #[test] fn fill_in_type_params_2() { check_assist( add_missing_impl_members, r#" trait Foo<T> { fn foo(&self, t: T) -> &T; } struct S; impl<U> Foo<U> for S { <|> }"#, r#" trait Foo<T> { fn foo(&self, t: T) -> &T; } struct S; impl<U> Foo<U> for S { fn foo(&self, t: U) -> &U { ${0:todo!()} } }"#, ); } #[test] fn test_cursor_after_empty_impl_def() { check_assist( add_missing_impl_members, r#" trait Foo { fn foo(&self); } struct S; impl Foo for S {}<|>"#, r#" trait Foo { fn foo(&self); } struct S; impl Foo for S { fn foo(&self) { ${0:todo!()} } }"#, ) } #[test] fn test_qualify_path_1() { check_assist( add_missing_impl_members, r#" mod foo { pub struct Bar; trait Foo { fn foo(&self, bar: Bar); } } struct S; impl foo::Foo for S { <|> }"#, r#" mod foo { pub struct Bar; trait Foo { fn foo(&self, bar: Bar); } } struct S; impl foo::Foo for S { fn foo(&self, bar: foo::Bar) { ${0:todo!()} } }"#, ); } #[test] fn test_qualify_path_generic() { check_assist( add_missing_impl_members, r#" mod foo { pub struct Bar<T>; trait Foo { fn foo(&self, bar: Bar<u32>); } } struct S; impl foo::Foo for S { <|> }"#, r#" mod foo { pub struct Bar<T>; trait Foo { fn foo(&self, bar: Bar<u32>); } } struct S; impl foo::Foo for S { fn foo(&self, bar: foo::Bar<u32>) { ${0:todo!()} } }"#, ); } #[test] fn test_qualify_path_and_substitute_param() { check_assist( add_missing_impl_members, r#" mod foo { pub struct Bar<T>; trait Foo<T> { fn foo(&self, bar: Bar<T>); } } struct S; impl foo::Foo<u32> for S { <|> }"#, r#" mod foo { pub struct Bar<T>; trait Foo<T> { fn foo(&self, bar: Bar<T>); } } struct S; impl foo::Foo<u32> for S { fn foo(&self, bar: foo::Bar<u32>) { ${0:todo!()} } }"#, ); } #[test] fn test_substitute_param_no_qualify() { // when substituting params, the substituted param should not be qualified! check_assist( add_missing_impl_members, r#" mod foo { trait Foo<T> { fn foo(&self, bar: T); } pub struct Param; } struct Param; struct S; impl foo::Foo<Param> for S { <|> }"#, r#" mod foo { trait Foo<T> { fn foo(&self, bar: T); } pub struct Param; } struct Param; struct S; impl foo::Foo<Param> for S { fn foo(&self, bar: Param) { ${0:todo!()} } }"#, ); } #[test] fn test_qualify_path_associated_item() { check_assist( add_missing_impl_members, r#" mod foo { pub struct Bar<T>; impl Bar<T> { type Assoc = u32; } trait Foo { fn foo(&self, bar: Bar<u32>::Assoc); } } struct S; impl foo::Foo for S { <|> }"#, r#" mod foo { pub struct Bar<T>; impl Bar<T> { type Assoc = u32; } trait Foo { fn foo(&self, bar: Bar<u32>::Assoc); } } struct S; impl foo::Foo for S { fn foo(&self, bar: foo::Bar<u32>::Assoc) { ${0:todo!()} } }"#, ); } #[test] fn test_qualify_path_nested() { check_assist( add_missing_impl_members, r#" mod foo { pub struct Bar<T>; pub struct Baz; trait Foo { fn foo(&self, bar: Bar<Baz>); } } struct S; impl foo::Foo for S { <|> }"#, r#" mod foo { pub struct Bar<T>; pub struct Baz; trait Foo { fn foo(&self, bar: Bar<Baz>); } } struct S; impl foo::Foo for S { fn foo(&self, bar: foo::Bar<foo::Baz>) { ${0:todo!()} } }"#, ); } #[test] fn test_qualify_path_fn_trait_notation() { check_assist( add_missing_impl_members, r#" mod foo { pub trait Fn<Args> { type Output; } trait Foo { fn foo(&self, bar: dyn Fn(u32) -> i32); } } struct S; impl foo::Foo for S { <|> }"#, r#" mod foo { pub trait Fn<Args> { type Output; } trait Foo { fn foo(&self, bar: dyn Fn(u32) -> i32); } } struct S; impl foo::Foo for S { fn foo(&self, bar: dyn Fn(u32) -> i32) { ${0:todo!()} } }"#, ); } #[test] fn test_empty_trait() { check_assist_not_applicable( add_missing_impl_members, r#" trait Foo; struct S; impl Foo for S { <|> }"#, ) } #[test] fn test_ignore_unnamed_trait_members_and_default_methods() { check_assist_not_applicable( add_missing_impl_members, r#" trait Foo { fn (arg: u32); fn valid(some: u32) -> bool { false } } struct S; impl Foo for S { <|> }"#, ) } #[test] fn test_with_docstring_and_attrs() { check_assist( add_missing_impl_members, r#" #[doc(alias = "test alias")] trait Foo { /// doc string type Output; #[must_use] fn foo(&self); } struct S; impl Foo for S {}<|>"#, r#" #[doc(alias = "test alias")] trait Foo { /// doc string type Output; #[must_use] fn foo(&self); } struct S; impl Foo for S { $0type Output; fn foo(&self) { todo!() } }"#, ) } #[test] fn test_default_methods() { check_assist( add_missing_default_members, r#" trait Foo { type Output; const CONST: usize = 42; fn valid(some: u32) -> bool { false } fn foo(some: u32) -> bool; } struct S; impl Foo for S { <|> }"#, r#" trait Foo { type Output; const CONST: usize = 42; fn valid(some: u32) -> bool { false } fn foo(some: u32) -> bool; } struct S; impl Foo for S { $0fn valid(some: u32) -> bool { false } }"#, ) } #[test] fn test_generic_single_default_parameter() { check_assist( add_missing_impl_members, r#" trait Foo<T = Self> { fn bar(&self, other: &T); } struct S; impl Foo for S { <|> }"#, r#" trait Foo<T = Self> { fn bar(&self, other: &T); } struct S; impl Foo for S { fn bar(&self, other: &Self) { ${0:todo!()} } }"#, ) } #[test] fn test_generic_default_parameter_is_second() { check_assist( add_missing_impl_members, r#" trait Foo<T1, T2 = Self> { fn bar(&self, this: &T1, that: &T2); } struct S<T>; impl Foo<T> for S<T> { <|> }"#, r#" trait Foo<T1, T2 = Self> { fn bar(&self, this: &T1, that: &T2); } struct S<T>; impl Foo<T> for S<T> { fn bar(&self, this: &T, that: &Self) { ${0:todo!()} } }"#, ) } }
21.273256
99
0.519268