text
stringlengths
8
4.13M
use actix_web::HttpResponse; pub async fn get_version() -> HttpResponse { HttpResponse::Ok().json(json!({"version": "1.0.0"})) } pub async fn get_health() -> HttpResponse { HttpResponse::Ok().json(json!({})) }
// 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 fidl_fuchsia_bluetooth_avdtp::PeerManagerControlHandle; /// State for storing the control handle for PeerManager /// We need this to reply back to bt-avdtp-tool /// The control handle reply only happens after a peer has been connected /// (ProfileEvent::OnPeerConnected) /// The control handle is created when we create the PeerManager listener /// TODO(fxb/37089): Save the control_handle for each peer so that the channel will shutdown /// when a peer disconnects from a2dp. Clients can then listen to this and clean up state. #[derive(Debug)] pub struct ControlHandleManager { pub handle: Option<PeerManagerControlHandle>, } impl ControlHandleManager { pub fn new() -> Self { Self { handle: None } } pub fn insert(&mut self, handle: PeerManagerControlHandle) { if self.handle.is_none() { self.handle = Some(handle); } } }
use regex_automata::util::prefilter::{self, Candidate, Prefilter}; #[derive(Clone, Debug)] pub struct SubstringPrefilter(bstr::Finder<'static>); impl SubstringPrefilter { pub fn new<B: AsRef<[u8]>>(needle: B) -> SubstringPrefilter { SubstringPrefilter(bstr::Finder::new(needle.as_ref()).into_owned()) } } impl Prefilter for SubstringPrefilter { #[inline] fn next_candidate( &self, state: &mut prefilter::State, haystack: &[u8], at: usize, ) -> Candidate { self.0 .find(&haystack[at..]) .map(|i| Candidate::PossibleStartOfMatch(at + i)) .unwrap_or(Candidate::None) } fn heap_bytes(&self) -> usize { self.0.needle().len() } } /// A prefilter that always returns `Candidate::None`, even if it's a false /// negative. This is useful for confirming that a prefilter is actually /// active by asserting an incorrect result. #[derive(Clone, Debug)] pub struct BunkPrefilter(()); impl BunkPrefilter { pub fn new() -> BunkPrefilter { BunkPrefilter(()) } } impl Prefilter for BunkPrefilter { #[inline] fn next_candidate( &self, _state: &mut prefilter::State, _haystack: &[u8], _at: usize, ) -> Candidate { Candidate::None } fn heap_bytes(&self) -> usize { 0 } }
extern crate arrow; extern crate parquet; use std::error::Error; use std::fs::File; use std::sync::Arc; use arrow::array::{ArrayRef, Int32Array, Int8Array}; use arrow::compute::{add, cast}; use arrow::datatypes::{DataType, Field, Schema}; use arrow::record_batch::RecordBatch; // Scenario - add two columns of different types and write the 3 to csv and parquet // // where // - xs: i32 array // - ys: i8 array // - zs: xs + ys // // outputs // - out/simple.csv // - out/parquet.csv // // improvements // - can we keep a reference to the primitive arrays? // - use error libraries to see how it goes with arrow and remove unwraps/excepts // fn main() -> Result<(), Box<dyn Error>> { // a simple definition of a i32 and i8 arrays let xs: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])); let ys: ArrayRef = Arc::new(Int8Array::from(vec![ Some(1), None, Some(3), Some(4), Some(5), ])); // compute xs + cast(ys, i32) let zs = { let b = cast(&ys, &DataType::Int32).unwrap(); let c = b.as_any().downcast_ref::<Int32Array>().unwrap().to_owned(); Arc::new(add(xs.as_any().downcast_ref::<Int32Array>().unwrap(), c).unwrap()) }; // define the schema let schema = Arc::new(Schema::new(vec![ Field::new("x", DataType::Int32, false), Field::new("y", DataType::Int8, true), Field::new("z", DataType::Int32, true), ])); // create a record batch let record_batch = RecordBatch::try_new(schema.clone(), vec![xs, ys, zs]).unwrap(); // write csv { let output_csv_file = File::create("out/simple.csv").unwrap(); arrow::csv::WriterBuilder::new() .has_headers(true) .with_delimiter(',' as u8) .build(output_csv_file) .write(&record_batch) .expect("failed to write csv"); } // write parquet { let output_parquet_file = File::create("out/simple.par").unwrap(); parquet::arrow::ArrowWriter::try_new(output_parquet_file, schema.clone(), None) .unwrap() .write(&record_batch) .expect("failed to write parquet"); } Ok(()) }
use super::context::{Ctx, PineRuntimeError, RVRunner, Runner, RunnerForFunc, RunnerForObj}; pub use crate::ast::stat_expr_types::{ Condition, DataType, Exp, FunctionCall, PrefixExp, RVVarName, RefCall, Statement, TypeCast, VarIndex, }; use crate::ast::syntax_type::{FunctionType, SimpleSyntaxType, SyntaxType}; use crate::types::{ downcast_pf, downcast_pf_mut, Bool, CallObjEval, Callable, CallableEvaluate, CallableFactory, CallableObject, Color, DataType as FirstType, Evaluate, EvaluateFactory, Float, Int, Object, PineFrom, PineRef, PineStaticType, PineType, PineVar, RefData, RuntimeErr, SecondType, Series, SimpleCallableObject, Tuple, NA, }; use std::fmt::Debug; // Invoke evaluate variable for eval factory variable. pub fn call_eval_factory<'a>( context: &mut dyn Ctx<'a>, eval_id: i32, s: PineRef<'a>, ) -> Result<PineRef<'a>, RuntimeErr> { // Get evaluate instance from context let mut eval_instance = context.move_fun_instance(eval_id); if eval_instance.is_none() { let eval_val = match s.get_type().0 { FirstType::CallableEvaluate => { let eval_factory = downcast_pf::<CallableEvaluate>(s.clone()).unwrap(); eval_factory.create_eval() } FirstType::CallableObjectEvaluate => { let eval_factory = downcast_pf::<CallObjEval>(s.clone()).unwrap(); eval_factory.create_eval() } _ => { let factory = downcast_pf::<EvaluateFactory>(s.clone()).unwrap(); factory.create() } }; // let factory = downcast_pf::<EvaluateFactory>(s.clone()).unwrap(); context.create_fun_instance(eval_id, PineRef::new_rc(eval_val)); eval_instance = context.move_fun_instance(eval_id); } let mut eval_val = downcast_pf::<Evaluate>(eval_instance.unwrap()).unwrap(); let result = eval_val.call(context); context.create_fun_instance(eval_id, RefData::clone(&eval_val).into_pf()); context.create_runnable(RefData::clone(&eval_val).into_rc()); result } pub fn call_func_factory<'a>( context: &mut dyn Ctx<'a>, func_id: i32, s: PineRef<'a>, pos_args: Vec<PineRef<'a>>, dict_args: Vec<(&'a str, PineRef<'a>)>, func_type: FunctionType<'a>, ) -> Result<PineRef<'a>, RuntimeErr> { let mut opt_instance = context.move_fun_instance(func_id); if opt_instance.is_none() { let func_val = match s.get_type().0 { FirstType::CallableFactory => { let factory = downcast_pf::<CallableFactory>(s).unwrap(); factory.create() } FirstType::CallableObject => { let factory = downcast_pf::<CallableObject>(s).unwrap(); factory.create() } FirstType::SimpleCallableObject => { let factory = downcast_pf::<SimpleCallableObject>(s).unwrap(); factory.create() } FirstType::CallableEvaluate => { let factory = downcast_pf::<CallableEvaluate>(s).unwrap(); factory.create() } FirstType::CallableObjectEvaluate => { let factory = downcast_pf::<CallObjEval>(s).unwrap(); factory.create() } _ => unreachable!(), }; context.create_fun_instance(func_id, PineRef::new_rc(func_val)); opt_instance = context.move_fun_instance(func_id); } let mut callable = downcast_pf::<Callable>(opt_instance.unwrap()).unwrap(); let result = callable.call(context, pos_args, dict_args, func_type); context.create_fun_instance(func_id, RefData::clone(&callable).into_pf()); context.create_runnable(callable.into_rc()); result } pub fn type_cast_custom<'a>( context: &mut dyn Ctx<'a>, cast_index: VarIndex, func_index: i32, result: PineRef<'a>, ) -> Result<PineRef<'a>, RuntimeErr> { match context.move_var(cast_index) { None => Err(RuntimeErr::VarNotFound), Some(s) => { let func_type = FunctionType::new(( vec![("x", SyntaxType::Simple(SimpleSyntaxType::Na))], SyntaxType::Any, )); let result = call_func_factory( context, func_index, s.copy(), vec![result], vec![], func_type, ); context.update_var(cast_index, s); result } } }
use crate::{ bls::{SecretKey, SIG_SIZE}, cli::Opts, rpc::Rpc, }; use crossbeam_channel::{bounded, RecvTimeoutError, Sender}; use hashbrown::HashMap; use log::{debug, info, trace, warn}; use meroxidizer::utils::difficulty_to_max_hash; use parking_lot::RwLock; use randomx::{Cache, HASH_SIZE}; use std::{ collections::VecDeque, sync::{ atomic::{self, AtomicUsize}, Arc, }, thread::JoinHandle, time::Duration, }; pub type Nonce = u32; pub struct BlockTemplate { pub seq: usize, pub header: Vec<u8>, pub randomx_cache: Arc<Cache>, pub max_hash: [u8; 32], pub height: usize, id: i64, } pub struct RpcInfo { pub miner_key: SecretKey, pub latest_template: RwLock<Arc<BlockTemplate>>, pub latest_seq: AtomicUsize, /// Channel of (seq, nonce) pub publish_channel: Sender<(usize, Nonce, [u8; SIG_SIZE], [u8; HASH_SIZE])>, /// Measured in units of `HASH_BATCH_SIZE` pub num_hashes_rec: AtomicUsize, } const GET_TEMPLATE_INTERVAL: Duration = Duration::from_secs(1); const RETAIN_SEQS: usize = 5; pub fn start(opts: Opts) -> (Arc<RpcInfo>, JoinHandle<()>) { let mut rpc = Rpc::connect(opts.clone()); let miner_key = match std::env::var("MEROS_MINER_KEY") { Ok(s) => hex::decode(s).expect("Failed to decode MEROS_MINER_KEY env var"), Err(std::env::VarError::NotPresent) => { match rpc.single_request::<_, String>("personal_getMiner", [(); 0]) { Ok(miner) => hex::decode(&miner).expect("Failed to decode miner key from RPC"), Err(err) => panic!("Failed to get miner key from RPC: {}", err), } } Err(err) => { panic!( "Failed to get MEROS_MINER_KEY environment variable: {}", err, ); } }; let miner_key = SecretKey::new(&miner_key).expect("Invalid miner key specified"); // TODO: remove reference and cast once we update our minimum rust version enough let miner_pubkey = hex::encode_upper(&miner_key.get_public_key() as &[u8]); let height = rpc.get_height(); let target = rpc.get_mining_target(&miner_pubkey); info!("loaded miner public key {}", miner_pubkey); info!("initializing RandomX.."); let cache = Cache::new( opts.get_randomx_flags(), &target.key, opts.randomx_init_threads, ) .unwrap(); info!("initialized RandomX"); let (publish_send, publish_recv) = bounded(64); let mut last_template = Arc::new(BlockTemplate { seq: 0, header: target.header, randomx_cache: Arc::new(cache), max_hash: difficulty_to_max_hash(target.difficulty), height, id: target.id, }); debug!( "got first block template with seq {}, id {}, and header {}", 0, last_template.id, hex::encode_upper(&last_template.header), ); let rpc_info = Arc::new(RpcInfo { miner_key, latest_template: RwLock::new(last_template.clone()), latest_seq: AtomicUsize::new(0), publish_channel: publish_send, num_hashes_rec: AtomicUsize::new(0), }); let mut recent_seqs = VecDeque::new(); recent_seqs.push_back(0); let mut last_seq = 0; let mut seqs_to_templates = HashMap::new(); seqs_to_templates.insert(0, last_template.clone()); let mut last_randomx_key = target.key; let rpc_info2 = rpc_info.clone(); let background = std::thread::spawn(move || loop { match publish_recv.recv_timeout(GET_TEMPLATE_INTERVAL) { Ok((seq, nonce, signature, hash)) => { if let Some(template) = seqs_to_templates.get(&seq) { info!("found block! hash: {}", hex::encode_upper(hash)); let mut contents = template.header.clone(); contents.extend(&nonce.to_le_bytes()); // TODO: remove cast once we update our minimum rust version enough contents.extend(&signature as &[u8]); let params = (template.id, hex::encode_upper(contents)); debug!("attempting to publish block with params {:?}", params); let res: Result<bool, _> = rpc.single_request("merit_publishBlock", params); match res { Ok(true) => debug!("successfully published block :)"), Ok(false) => warn!("failed to publish block for unknown reason :("), Err(err) => warn!("failed to publish block :( error: {}", err), } // Empty publish channel as previous blocks aren't useful while publish_recv.try_recv().is_ok() {} } else { warn!("found block with expired seq :("); continue; } } Err(RecvTimeoutError::Timeout) => {} Err(RecvTimeoutError::Disconnected) => return, } let height = rpc.get_height(); if height > last_template.height { recent_seqs.clear(); seqs_to_templates.clear(); } let target = rpc.get_mining_target(&miner_pubkey); last_seq += 1; let mut template = BlockTemplate { seq: last_seq, header: target.header, randomx_cache: last_template.randomx_cache.clone(), max_hash: difficulty_to_max_hash(target.difficulty), height, id: target.id, }; debug!( "got new block template with seq {}, id {}, and header {}", last_seq, template.id, hex::encode_upper(&template.header), ); if target.key != last_randomx_key { last_randomx_key = target.key; if opts.randomx_stop_for_rekey { let mut template_lock = rpc_info2.latest_template.write(); rpc_info2 .latest_seq .store(template.seq, atomic::Ordering::Relaxed); info!("new RandomX key! waiting for mining threads to pause.."); drop(last_template); drop(template.randomx_cache); recent_seqs.clear(); seqs_to_templates.clear(); let mut last_counts = (0, 0); loop { if let Some(cache) = Arc::get_mut(&mut template_lock) .and_then(|t| Arc::get_mut(&mut t.randomx_cache)) { info!("reinitializing RandomX.."); cache .set_key(&target.key, opts.randomx_init_threads) .unwrap(); info!("reinitialized RandomX"); break; } else { if log::log_enabled!(log::Level::Trace) { let new_counts = ( Arc::strong_count(&template_lock), Arc::strong_count(&template_lock.randomx_cache), ); if last_counts != new_counts { trace!("current refcounts: {} {}", new_counts.0, new_counts.1); last_counts = new_counts; } } std::thread::yield_now(); } } template.randomx_cache = template_lock.randomx_cache.clone(); last_template = Arc::new(template); *template_lock = last_template.clone(); } else { info!("new key! reinitializing RandomX.."); template.randomx_cache = Arc::new( Cache::new( opts.get_randomx_flags(), &target.key, opts.randomx_init_threads, ) .unwrap(), ); info!("reinitialized RandomX"); last_template = Arc::new(template); *rpc_info2.latest_template.write() = last_template.clone(); rpc_info2 .latest_seq .store(last_template.seq, atomic::Ordering::Relaxed); } } else { last_template = Arc::new(template); *rpc_info2.latest_template.write() = last_template.clone(); rpc_info2 .latest_seq .store(last_template.seq, atomic::Ordering::Relaxed); } seqs_to_templates.insert(last_seq, last_template.clone()); recent_seqs.push_back(last_seq); if recent_seqs.len() > RETAIN_SEQS { seqs_to_templates.remove(&recent_seqs.pop_front().unwrap()); } }); (rpc_info, background) }
use midi_message::MidiMessage; use color_strip::ColorStrip; use effects::effect::Effect; use rainbow::get_rainbow_color; pub struct Push { color_strip: ColorStrip, } impl Push { pub fn new(led_count: usize) -> Push { Push { color_strip: ColorStrip::new(led_count), } } } impl Effect for Push { fn paint(&mut self, color_strip: &mut ColorStrip) { color_strip.blit(&self.color_strip); } fn tick(&mut self) {} fn on_midi_message(&mut self, midi_message: MidiMessage) { if let MidiMessage::NoteOn(_, note, _) = midi_message { self.color_strip.insert(get_rainbow_color(note)); } } }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use std::time::Duration; use std::time::Instant; use anyerror::AnyError; use backon::BackoffBuilder; use backon::ExponentialBuilder; use common_base::base::tokio::time::sleep; use common_base::containers::ItemManager; use common_base::containers::Pool; use common_meta_sled_store::openraft; use common_meta_sled_store::openraft::error::NetworkError; use common_meta_sled_store::openraft::MessageSummary; use common_meta_sled_store::openraft::RaftNetworkFactory; use common_meta_types::protobuf::RaftRequest; use common_meta_types::AppendEntriesRequest; use common_meta_types::AppendEntriesResponse; use common_meta_types::InstallSnapshotError; use common_meta_types::InstallSnapshotRequest; use common_meta_types::InstallSnapshotResponse; use common_meta_types::MembershipNode; use common_meta_types::MetaNetworkError; use common_meta_types::NodeId; use common_meta_types::RPCError; use common_meta_types::RaftError; use common_meta_types::TypeConfig; use common_meta_types::VoteRequest; use common_meta_types::VoteResponse; use openraft::async_trait::async_trait; use openraft::RaftNetwork; use tonic::client::GrpcService; use tonic::transport::channel::Channel; use tracing::debug; use tracing::info; use crate::metrics::raft_metrics; use crate::raft_client::RaftClient; use crate::raft_client::RaftClientApi; use crate::store::RaftStore; #[derive(Debug)] struct ChannelManager {} #[async_trait] impl ItemManager for ChannelManager { type Key = String; type Item = Channel; type Error = tonic::transport::Error; #[tracing::instrument(level = "info", err(Debug))] async fn build(&self, addr: &Self::Key) -> Result<Channel, tonic::transport::Error> { tonic::transport::Endpoint::new(addr.clone())? .connect() .await } #[tracing::instrument(level = "debug", err(Debug))] async fn check(&self, mut ch: Channel) -> Result<Channel, tonic::transport::Error> { futures::future::poll_fn(|cx| ch.poll_ready(cx)).await?; Ok(ch) } } #[derive(Debug, Clone)] pub(crate) struct Backoff { /// delay increase ratio of meta /// /// should be not little than 1.0 back_off_ratio: f32, /// min delay duration of back off back_off_min_delay: Duration, /// max delay duration of back off back_off_max_delay: Duration, /// chances of back off back_off_chances: u64, } impl Backoff { /// Set exponential back off policy for meta service /// /// - `ratio`: delay increase ratio of meta /// /// should be not smaller than 1.0 /// - `min_delay`: minimum back off duration, where the backoff duration vary starts from /// - `max_delay`: maximum back off duration, if the backoff duration is larger than this, no backoff will be raised /// - `chances`: maximum back off times, chances off backoff #[allow(dead_code)] pub fn with_back_off_policy( mut self, ratio: f32, min_delay: Duration, max_delay: Duration, chances: u64, ) -> Self { self.back_off_ratio = ratio; self.back_off_min_delay = min_delay; self.back_off_max_delay = max_delay; self.back_off_chances = chances; self } } impl Default for Backoff { fn default() -> Self { Self { back_off_ratio: 2.0, back_off_min_delay: Duration::from_secs(1), back_off_max_delay: Duration::from_secs(60), back_off_chances: 3, } } } #[derive(Clone)] pub struct Network { sto: RaftStore, conn_pool: Arc<Pool<ChannelManager>>, backoff: Backoff, } impl Network { pub fn new(sto: RaftStore) -> Network { let mgr = ChannelManager {}; Network { sto, conn_pool: Arc::new(Pool::new(mgr, Duration::from_millis(50))), backoff: Backoff::default(), } } fn incr_meta_metrics_sent_bytes_to_peer(target: &NodeId, message: &RaftRequest) { let bytes = message.data.len() as u64; raft_metrics::network::incr_sent_bytes_to_peer(target, bytes); } } pub struct NetworkConnection { id: NodeId, target: NodeId, // TODO: this will be used when learners is upgrade to be stored in Membership #[allow(dead_code)] target_node: MembershipNode, sto: RaftStore, conn_pool: Arc<Pool<ChannelManager>>, backoff: Backoff, } impl NetworkConnection { #[tracing::instrument(level = "debug", skip_all, fields(id=self.id), err(Debug))] pub async fn make_client(&self) -> Result<RaftClient, MetaNetworkError> { let target = self.target; let endpoint = self .sto .get_node_endpoint(&target) .await .map_err(|e| MetaNetworkError::GetNodeAddrError(e.to_string()))?; let addr = format!("http://{}", endpoint); debug!("connect: target={}: {}", target, addr); match self.conn_pool.get(&addr).await { Ok(channel) => { let client = RaftClientApi::new(target, endpoint, channel); debug!("connected: target={}: {}", target, addr); Ok(client) } Err(err) => { raft_metrics::network::incr_fail_connections_to_peer( &target, &endpoint.to_string(), ); Err(err.into()) } } } pub(crate) fn back_off(&self) -> impl Iterator<Item = Duration> { let policy = ExponentialBuilder::default() .with_factor(self.backoff.back_off_ratio) .with_min_delay(self.backoff.back_off_min_delay) .with_max_delay(self.backoff.back_off_max_delay) .with_max_times(self.backoff.back_off_chances as usize) .build(); // the last period of back off should be zero // so the longest back off will not be wasted let zero = vec![Duration::default()].into_iter(); policy.chain(zero) } } #[async_trait] impl RaftNetwork<TypeConfig> for NetworkConnection { #[tracing::instrument(level = "debug", skip_all, fields(id=self.id, target=self.target), err(Debug))] async fn send_append_entries( &mut self, rpc: AppendEntriesRequest, ) -> Result<AppendEntriesResponse, RPCError<RaftError>> { debug!( "send_append_entries target: {}, rpc: {}", self.target, rpc.summary() ); let mut client = self .make_client() .await .map_err(|e| RPCError::Network(NetworkError::new(&e)))?; let mut last_err = None; for back_off in self.back_off() { let req = common_tracing::inject_span_to_tonic_request(&rpc); Network::incr_meta_metrics_sent_bytes_to_peer(&self.target, req.get_ref()); let resp = client.append_entries(req).await; debug!( "append_entries resp from: target={}: {:?}", self.target, resp ); match resp { Ok(resp) => { let mes = resp.into_inner(); match serde_json::from_str(&mes.data) { Ok(resp) => return Ok(resp), Err(e) => { // parsing error, won't increase send failures last_err = Some(openraft::error::NetworkError::new( &AnyError::new(&e).add_context(|| "send_append_entries"), )); // backoff and retry sending sleep(back_off).await; } } } Err(e) => { raft_metrics::network::incr_sent_failure_to_peer(&self.target); last_err = Some(openraft::error::NetworkError::new( &AnyError::new(&e).add_context(|| "send_append_entries"), )); // backoff and retry sending sleep(back_off).await; } } } if let Some(net_err) = last_err { Err(RPCError::Network(net_err)) } else { Err(RPCError::Network(NetworkError::new(&AnyError::error( "backoff does not send send_append_entries RPC", )))) } } #[tracing::instrument(level = "debug", skip_all, fields(id=self.id, target=self.target), err(Debug))] async fn send_install_snapshot( &mut self, rpc: InstallSnapshotRequest, ) -> Result<InstallSnapshotResponse, RPCError<RaftError<InstallSnapshotError>>> { info!( "send_install_snapshot target: {}, rpc: {}", self.target, rpc.summary() ); let start = Instant::now(); let mut client = self .make_client() .await .map_err(|e| RPCError::Network(NetworkError::new(&e)))?; let mut last_err = None; for back_off in self.back_off() { let req = common_tracing::inject_span_to_tonic_request(&rpc); Network::incr_meta_metrics_sent_bytes_to_peer(&self.target, req.get_ref()); raft_metrics::network::incr_snapshot_send_inflights_to_peer(&self.target, 1); let resp = client.install_snapshot(req).await; info!( "install_snapshot resp from: target={}: {:?}", self.target, resp ); match resp { Ok(resp) => { raft_metrics::network::incr_snapshot_send_inflights_to_peer(&self.target, -1); raft_metrics::network::incr_snapshot_send_success_to_peer(&self.target); let mes = resp.into_inner(); match serde_json::from_str(&mes.data) { Ok(resp) => { raft_metrics::network::sample_snapshot_sent( &self.target, start.elapsed().as_secs() as f64, ); return Ok(resp); } Err(e) => { // parsing error, won't increase sending failures last_err = Some(openraft::error::NetworkError::new( &AnyError::new(&e).add_context(|| "send_install_snapshot"), )); // back off and retry sending sleep(back_off).await; } } } Err(e) => { raft_metrics::network::incr_sent_failure_to_peer(&self.target); raft_metrics::network::incr_snapshot_send_failures_to_peer(&self.target); last_err = Some(openraft::error::NetworkError::new( &AnyError::new(&e).add_context(|| "send_install_snapshot"), )); // back off and retry sending sleep(back_off).await; } } } if let Some(net_err) = last_err { Err(RPCError::Network(net_err)) } else { Err(RPCError::Network(NetworkError::new(&AnyError::error( "backoff does not send send_install_snapshot RPC", )))) } } #[tracing::instrument(level = "debug", skip_all, fields(id=self.id, target=self.target), err(Debug))] async fn send_vote(&mut self, rpc: VoteRequest) -> Result<VoteResponse, RPCError<RaftError>> { info!("send_vote: target: {} rpc: {}", self.target, rpc.summary()); let mut client = self .make_client() .await .map_err(|e| RPCError::Network(NetworkError::new(&e)))?; let mut last_err = None; for back_off in self.back_off() { let req = common_tracing::inject_span_to_tonic_request(&rpc); Network::incr_meta_metrics_sent_bytes_to_peer(&self.target, req.get_ref()); let resp = client.vote(req).await; info!("vote: resp from target={} {:?}", self.target, resp); match resp { Ok(resp) => { let mes = resp.into_inner(); match serde_json::from_str(&mes.data) { Ok(resp) => return Ok(resp), Err(e) => { // parsing error, won't increase sending errors last_err = Some(openraft::error::NetworkError::new( &AnyError::new(&e).add_context(|| "send_vote"), )); // back off and retry sleep(back_off).await; } } } Err(e) => { raft_metrics::network::incr_sent_failure_to_peer(&self.target); last_err = Some(openraft::error::NetworkError::new( &AnyError::new(&e).add_context(|| "send_vote"), )); // back off and retry sleep(back_off).await; } } } if let Some(net_err) = last_err { Err(RPCError::Network(net_err)) } else { Err(RPCError::Network(NetworkError::new(&AnyError::error( "backoff does not send send_vote RPC", )))) } } } #[async_trait] impl RaftNetworkFactory<TypeConfig> for Network { type Network = NetworkConnection; async fn new_client( self: &mut Network, target: NodeId, node: &MembershipNode, ) -> Self::Network { tracing::info!( "new raft communication client: id:{}, target:{}, node:{}", self.sto.id, target, node ); NetworkConnection { id: self.sto.id, target, target_node: node.clone(), sto: self.sto.clone(), conn_pool: self.conn_pool.clone(), backoff: self.backoff.clone(), } } }
use crate::pac::ccu::{ Ahb1Apb1Config, Ahb2Config, Apb2Config, BusClockGating0, BusClockGating1, BusClockGating2, BusClockGating3, BusSoftReset0, BusSoftReset1, BusSoftReset4, PllCpuXControl, PllDeControl, PllPeriph0Control, PllVideo0Control, CCU, }; use cortex_a::asm; use embedded_time::rate::Hertz; pub trait CcuExt { fn constrain(self) -> Ccu; } impl CcuExt for CCU { fn constrain(self) -> Ccu { Ccu { bcg0: BCG0 { _0: () }, bcg1: BCG1 { _0: () }, bcg2: BCG2 { _0: () }, bcg3: BCG3 { _0: () }, bsr0: BSR0 { _0: () }, bsr1: BSR1 { _0: () }, bsr4: BSR4 { _0: () }, } } } #[derive(Debug, Copy, Clone, PartialEq, PartialOrd)] pub struct Clocks { pll_periph0_1x: Hertz, pll_periph0_2x: Hertz, cpu: Hertz, ahb1: Hertz, ahb2: Hertz, apb1: Hertz, apb2: Hertz, } impl Clocks { pub const OSC_24M_FREQ: Hertz = Hertz(24_000_000); pub const OSC_32K_FREQ: Hertz = Hertz(32_768); //const OSC_I16M_FREQ: usize = 16_000_000; pub fn read() -> Self { // TODO - check that the locks have stabilized let ccu = unsafe { &mut *CCU::mut_ptr() }; // PLL output = (24MHz * N * K) / (M * P) let pll_cpu_m = 1 + ccu .pll_cpu_ctrl .get_field(PllCpuXControl::FactorM::Read) .unwrap() .val(); let pll_cpu_k = 1 + ccu .pll_cpu_ctrl .get_field(PllCpuXControl::FactorK::Read) .unwrap() .val(); let pll_cpu_n = 1 + ccu .pll_cpu_ctrl .get_field(PllCpuXControl::FactorN::Read) .unwrap() .val(); let pll_cpu_div_p_field = ccu .pll_cpu_ctrl .get_field(PllCpuXControl::PllOutExtDivP::Read) .unwrap(); let pll_cpu_div_p = if pll_cpu_div_p_field == PllCpuXControl::PllOutExtDivP::Divide1 { 1 } else if pll_cpu_div_p_field == PllCpuXControl::PllOutExtDivP::Divide2 { 2 } else if pll_cpu_div_p_field == PllCpuXControl::PllOutExtDivP::Divide4 { 4 } else { 8 }; let pll_cpu = (Self::OSC_24M_FREQ.0 * pll_cpu_n * pll_cpu_k) / (pll_cpu_m * pll_cpu_div_p); let pll_p0_k = 1 + ccu .pll_periph0 .get_field(PllPeriph0Control::FactorK::Read) .unwrap() .val(); let pll_p0_n = 1 + ccu .pll_periph0 .get_field(PllPeriph0Control::FactorN::Read) .unwrap() .val(); // PLL_PERIPH0(1X) = 24MHz * N * K/2 let pll_periph0_1x = Self::OSC_24M_FREQ.0 * pll_p0_n * (pll_p0_k / 2); // PLL_PERIPH0(2X) = 24MHz * N * K let pll_periph0_2x = Self::OSC_24M_FREQ.0 * pll_p0_n * pll_p0_k; // AHB1 let ahb1_pre_div = 1 + ccu .ahb1_apb1_cfg .get_field(Ahb1Apb1Config::Ahb1PreDiv::Read) .unwrap() .val(); let ahb1_clk_src = ccu .ahb1_apb1_cfg .get_field(Ahb1Apb1Config::Ahb1ClockSrcSel::Read) .unwrap(); let ahb1_clk = if ahb1_clk_src == Ahb1Apb1Config::Ahb1ClockSrcSel::PllPeriph01x { pll_periph0_1x / ahb1_pre_div } else { unimplemented!() }; // AHB2 let ahb2_clk_src = ccu .ahb2_cfg .get_field(Ahb2Config::ClockConfig::Read) .unwrap(); let ahb2_clk = if ahb2_clk_src == Ahb2Config::ClockConfig::PllPeriph01xD2 { pll_periph0_1x / 2 } else { unimplemented!() }; // APB1 let apb1_clk_ratio = ccu .ahb1_apb1_cfg .get_field(Ahb1Apb1Config::Apb1ClockDivRatio::Read) .unwrap(); let apb1_clk = if apb1_clk_ratio == Ahb1Apb1Config::Apb1ClockDivRatio::Divide2 { ahb1_clk / 2 } else { unimplemented!() }; // APB2 let apb2_clk_src = ccu .apb2_cfg .get_field(Apb2Config::ClockSrcSel::Read) .unwrap(); let apb2_clk = if apb2_clk_src == Apb2Config::ClockSrcSel::Osc24M { Self::OSC_24M_FREQ } else { unimplemented!() }; Clocks { pll_periph0_1x: Hertz::new(pll_periph0_1x), pll_periph0_2x: Hertz::new(pll_periph0_2x), cpu: Hertz::new(pll_cpu), ahb1: Hertz::new(ahb1_clk), ahb2: Hertz::new(ahb2_clk), apb1: Hertz::new(apb1_clk), apb2: Hertz::new(apb2_clk.0), } } pub fn cpu(&self) -> Hertz { self.cpu } pub fn ahb1(&self) -> Hertz { self.ahb1 } pub fn ahb2(&self) -> Hertz { self.ahb2 } pub fn apb1(&self) -> Hertz { self.apb1 } pub fn apb2(&self) -> Hertz { self.apb2 } } pub struct Ccu { pub bcg0: BCG0, pub bcg1: BCG1, pub bcg2: BCG2, pub bcg3: BCG3, // bsr0: AHB1 Reset 0 // bsr1: AHB1 Reset 1 // bsr2: AHB1 Reset 2 // bsr3: APB1 Reset // bsr4: APB2 Reset pub bsr0: BSR0, pub bsr1: BSR1, pub bsr4: BSR4, } // TODO - rename the wrappers // - BSR4 -> APB2 pub struct BCG0 { _0: (), } impl BCG0 { pub(crate) fn enr(&mut self) -> &mut BusClockGating0::Register { unsafe { &mut (*CCU::mut_ptr()).bcg0 } } } pub struct BCG1 { _0: (), } impl BCG1 { pub(crate) fn enr(&mut self) -> &mut BusClockGating1::Register { unsafe { &mut (*CCU::mut_ptr()).bcg1 } } } pub struct BCG2 { _0: (), } impl BCG2 { pub(crate) fn enr(&mut self) -> &mut BusClockGating2::Register { unsafe { &mut (*CCU::mut_ptr()).bcg2 } } } pub struct BCG3 { _0: (), } impl BCG3 { pub(crate) fn enr(&mut self) -> &mut BusClockGating3::Register { unsafe { &mut (*CCU::mut_ptr()).bcg3 } } } pub struct BSR0 { _0: (), } impl BSR0 { pub(crate) fn rstr(&mut self) -> &mut BusSoftReset0::Register { unsafe { &mut (*CCU::mut_ptr()).bsr0 } } } pub struct BSR1 { _0: (), } impl BSR1 { pub(crate) fn rstr(&mut self) -> &mut BusSoftReset1::Register { unsafe { &mut (*CCU::mut_ptr()).bsr1 } } } pub struct BSR4 { _0: (), } impl BSR4 { pub(crate) fn rstr(&mut self) -> &mut BusSoftReset4::Register { unsafe { &mut (*CCU::mut_ptr()).bsr4 } } } impl Ccu { pub(crate) fn pll_video0(&self) -> Hertz { let ccu = unsafe { &*CCU::ptr() }; let n = 1 + ccu .pll_video0 .get_field(PllVideo0Control::FactorN::Read) .unwrap() .val(); let m = 1 + ccu .pll_video0 .get_field(PllVideo0Control::PreDivM::Read) .unwrap() .val(); let f = (24000 * n / m) * 1000; Hertz::new(f) } pub(crate) fn set_pll_video0(&mut self, clk: Hertz) { let ccu = unsafe { &mut *CCU::mut_ptr() }; // 6 MHz steps to allow higher frequency for DE2 let m = 4; if clk.0 == 0 { ccu.pll_video0.modify(PllVideo0Control::Enable::Clear); } else { let n = clk.0 / (Clocks::OSC_24M_FREQ.0 / m); let factor_n = n - 1; let factor_m = m - 1; // PLL3 rate = 24000000 * n / m ccu.pll_video0.modify( PllVideo0Control::Enable::Set + PllVideo0Control::Mode::Integer + PllVideo0Control::FactorN::Field::new(factor_n).unwrap() + PllVideo0Control::PreDivM::Field::new(factor_m).unwrap(), ); while !ccu.pll_video0.is_set(PllVideo0Control::Lock::Read) { asm::nop(); } } } pub(crate) fn set_pll_video0_factors(&mut self, m: u32, n: u32) { let ccu = unsafe { &mut *CCU::mut_ptr() }; // TODO - these are trip'n ... //assert_ne!(m & !0xFF, 0); //assert_ne!(n & !0xFF, 0); // PLL3 rate = 24000000 * n / m let factor_n = n - 1; let factor_m = m - 1; ccu.pll_video0.modify( PllVideo0Control::Enable::Set + PllVideo0Control::Mode::Integer + PllVideo0Control::FactorN::Field::new(factor_n).unwrap() + PllVideo0Control::PreDivM::Field::new(factor_m).unwrap(), ); while !ccu.pll_video0.is_set(PllVideo0Control::Lock::Read) { asm::nop(); } } pub(crate) fn set_pll_de(&mut self, clk: Hertz) { let ccu = unsafe { &mut *CCU::mut_ptr() }; // 12 MHz steps let m = 2; if clk.0 == 0 { ccu.pll_de.modify(PllDeControl::Enable::Clear); } else { let n = clk.0 / (Clocks::OSC_24M_FREQ.0 / m); let factor_n = n - 1; let factor_m = m - 1; // PLL10 rate = 24000000 * n / m ccu.pll_de.modify( PllDeControl::Enable::Set + PllDeControl::Mode::Integer + PllDeControl::FactorN::Field::new(factor_n).unwrap() + PllDeControl::PreDivM::Field::new(factor_m).unwrap(), ); while !ccu.pll_de.is_set(PllDeControl::Lock::Read) { asm::nop(); } } } }
use super::lane_type::LaneType; use super::skill_type::SkillType; #[derive(Clone, Debug, Eq, PartialEq)] pub struct Message { pub lane: LaneType, pub skill_to_learn: SkillType, pub raw_message: Vec<i8>, }
pub type SymbolId = String;
use std::{sync::{Arc, Mutex, mpsc::{self, Receiver, Sender}}, thread::{self, JoinHandle}}; use std::{time::{Duration, SystemTime}}; use chrono::{Local, Timelike}; use rand::Rng; use crate::{Config, DEFAULT_CONFIG_PATH, DEFAULT_DOWNLOAD_PATH, Hour, download_photo, get_weather, make_unsplash_client, search_photos, set_wallpaper}; const MAXIMUM_ATTEMPTS: i32 = 5; const WAIT_SECS: u64 = 60; #[derive(Debug)] pub enum Message { Redownload, Stop } pub enum MetaMessage { Start, Quit } pub enum State { Idle, Running, Stopped } pub struct Worker { thread: Option<JoinHandle<()>>, sender: Sender<Message>, meta_sender: Sender<MetaMessage>, pub state: Arc<Mutex<State>> } impl Worker { pub fn new() -> Worker { let (tx, rx) = mpsc::channel(); let (sender, receiver) = mpsc::channel(); let state = Arc::new(Mutex::new(State::Stopped)); let state_thread = state.clone(); let thread = thread::spawn(move || { loop { let mut state = state_thread.lock().unwrap(); *state = State::Stopped; drop(state); match rx.recv().unwrap() { MetaMessage::Start => {}, MetaMessage::Quit => break } Worker::work(&receiver, state_thread.clone()); } }); let worker = Worker { thread: Some(thread), sender, meta_sender: tx, state }; worker } fn work(receiver: &Receiver<Message>, state: Arc<Mutex<State>>) { let config = match Config::from_path(DEFAULT_CONFIG_PATH) { Ok(config) => config, Err(e) => { eprintln!("Failed to read config: {}", e); return; } }; let client = match make_unsplash_client(&config) { Ok(client) => client, Err(_) => { eprintln!("\ Looks like this is the first time you use AWC. You need to do a few things first - otherwise AWC won't run. A `config.json` has been generated under the cwd, please modify it to your heart's content, especially the `unsplash_access_key`. I can't download wallpapers without it. You can apply for one here: https://unsplash.com/join If you also want the wallpaper to (poorly) resemble your current weather, you can apply an OpenWeather API here: openweathermap.org you will also need to change the city you are in. Otherwise, you can just leave it as it is. WARNING: weather messes up with the query term, and you might get wallpapers in the wrong time. `repeat_secs` is the interval before I download another wallpaper - it is one hour by default. The quality is splitted into 5 levels, as the Unsplash API states: Raw, Full, Regular, Small and Thumb. Run the program again after you've updated the configs accordingly. Have a lot of fun..."); return; } }; let mut attempts = 0; let mut last_instant: Option<SystemTime> = None; let mut last_path: Option<String> = None; if config.disable_cache { match std::fs::remove_dir_all(DEFAULT_DOWNLOAD_PATH) { Ok(_) => { println!("Image cache directory has been cleaned up"); } Err(_) => {} } } loop { match receiver.try_recv() { Ok(msg) => { match msg { Message::Stop => return, Message::Redownload => last_instant = None } } Err(_) => {} } let now = Local::now(); let this_instant = SystemTime::now(); let mut state_mut = state.lock().unwrap(); *state_mut = State::Idle; if last_instant.is_some() && this_instant.duration_since( (&last_instant.unwrap()).clone()) .unwrap().as_secs() <= config.update_interval { drop(state_mut); thread::sleep(Duration::from_secs(config.repeat_secs)); continue; } *state_mut = State::Running; drop(state_mut); let mut query = Hour(now.hour()).to_string(); match &config.openweather_access_key { Some(x) => match get_weather(x, &config.city_weather) { Ok(x) => { query.push(' '); query.push_str(&x); }, Err(e) => { eprintln!("Failed to get weather information: {} Skipping...", e); } }, None => {} }; println!("Trying to search from unsplash with: {}", query); let results = match search_photos(&client, &query) { Ok(results) => { results }, Err(e) => { attempts += 1; if attempts >= MAXIMUM_ATTEMPTS { eprintln!("Failed to get photo list: {}. Too many retries. Stopping...", e); break; } else { eprintln!("Failed to get photo list: {}, Trying again in {} seconds...", e, WAIT_SECS); thread::sleep(Duration::from_secs(WAIT_SECS)); } continue; } }; let choice = rand::thread_rng().gen_range(0..results.results.len()); let choice = &results.results[choice]; let path = match download_photo(&client, choice, config.quality.clone()) { Ok(path) => path, Err(e) => { attempts += 1; if attempts >= MAXIMUM_ATTEMPTS { eprintln!("Download failed: {}. Too many retries. Stopping...", e); break; } else { eprintln!("Download failed: {}. Trying again in {} seconds...", e, WAIT_SECS); thread::sleep(Duration::from_secs(WAIT_SECS)); } continue; } }; attempts = 0; last_instant = Some(this_instant); if config.disable_cache { if let Some(last_path) = last_path { if path != last_path { match std::fs::remove_file(last_path) { Ok(_) => {} Err(e) => { eprintln!("Could not removed cached image for some reason: {}. Skipping...", e); } } } } } last_path = Some(path.clone()); println!("New photo downloaded at: {}. Setting wallpaper...", path); match set_wallpaper(&path) { Ok(_) => {} Err(e) => { eprintln!("Failed to set wallpaper: {}. Stopping...", e); return; } } thread::sleep(Duration::from_secs(config.repeat_secs)); } } pub fn send(&self, msg: Message) { self.sender.send(msg).unwrap(); } pub fn meta_send(&self, msg: MetaMessage) { self.meta_sender.send(msg).unwrap(); } } impl Drop for Worker { fn drop(&mut self) { println!("Gracefully shutting down worker thread..."); self.send(Message::Stop); self.meta_send(MetaMessage::Quit); self.thread.take().unwrap().join().unwrap(); } }
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn iter<'a>(data: &'a [usize]) -> impl Iterator<Item = usize> + 'a { data.iter() .map( |x| x // fn(&'a usize) -> &'(ReScope) usize ) .map( |x| *x // fn(&'(ReScope) usize) -> usize ) } fn main() { }
#![feature(test)] extern crate futures; extern crate test; use futures::{Async, Poll}; use futures::executor; use futures::executor::{Notify, NotifyHandle}; use futures::sync::BiLock; use futures::sync::BiLockAcquire; use futures::sync::BiLockAcquired; use futures::future::Future; use futures::stream::Stream; use test::Bencher; fn notify_noop() -> NotifyHandle { struct Noop; impl Notify for Noop { fn notify(&self, _id: usize) {} } const NOOP : &'static Noop = &Noop; NotifyHandle::from(NOOP) } /// Pseudo-stream which simply calls `lock.poll()` on `poll` struct LockStream { lock: BiLockAcquire<u32>, } impl LockStream { fn new(lock: BiLock<u32>) -> LockStream { LockStream { lock: lock.lock() } } /// Release a lock after it was acquired in `poll`, /// so `poll` could be called again. fn release_lock(&mut self, guard: BiLockAcquired<u32>) { self.lock = guard.unlock().lock() } } impl Stream for LockStream { type Item = BiLockAcquired<u32>; type Error = (); fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { self.lock.poll().map(|a| match a { Async::Ready(a) => Async::Ready(Some(a)), Async::NotReady => Async::NotReady, }) } } #[bench] fn contended(b: &mut Bencher) { b.iter(|| { let (x, y) = BiLock::new(1); let mut x = executor::spawn(LockStream::new(x)); let mut y = executor::spawn(LockStream::new(y)); for _ in 0..1000 { let x_guard = match x.poll_stream_notify(&notify_noop(), 11) { Ok(Async::Ready(Some(guard))) => guard, _ => panic!(), }; // Try poll second lock while first lock still holds the lock match y.poll_stream_notify(&notify_noop(), 11) { Ok(Async::NotReady) => (), _ => panic!(), }; x.get_mut().release_lock(x_guard); let y_guard = match y.poll_stream_notify(&notify_noop(), 11) { Ok(Async::Ready(Some(guard))) => guard, _ => panic!(), }; y.get_mut().release_lock(y_guard); } (x, y) }); } #[bench] fn lock_unlock(b: &mut Bencher) { b.iter(|| { let (x, y) = BiLock::new(1); let mut x = executor::spawn(LockStream::new(x)); let mut y = executor::spawn(LockStream::new(y)); for _ in 0..1000 { let x_guard = match x.poll_stream_notify(&notify_noop(), 11) { Ok(Async::Ready(Some(guard))) => guard, _ => panic!(), }; x.get_mut().release_lock(x_guard); let y_guard = match y.poll_stream_notify(&notify_noop(), 11) { Ok(Async::Ready(Some(guard))) => guard, _ => panic!(), }; y.get_mut().release_lock(y_guard); } (x, y) }) }
extern crate bit_vec; use std::mem::size_of; use std::option::Option; use bit_vec::BitVec; const PAGE_SIZE: usize = 4096; struct BranchNode<T> { branches: Vec<Node<T>>, valid: BitVec } struct LeafNode<T> { data: Vec<T>, valid: BitVec, marked: BitVec, } enum Node<T> { Branch(BranchNode<T>), Leaf(LeafNode<T>), Empty } struct Trie<T> { root: Node<T> } impl <T> LeafNode<T> { fn new() -> LeafNode<T> { let page_capacity = PAGE_SIZE / size_of::<usize>(); LeafNode{data: Vec::with_capacity(page_capacity), valid: BitVec::with_capacity(page_capacity), marked: BitVec::with_capacity(page_capacity)} } fn index(&self, key: usize) -> usize { let word_size = size_of::<usize>(); let page_capacity = PAGE_SIZE / word_size; let mask = (0xFFF << word_size) & 0xFFF; (key & mask) >> word_size } fn insert(&mut self, key: usize, value: T) { let nth = self.index(key); self.data[nth] = value; self.valid.set(nth, true); } fn get_mut(&mut self, key: usize) -> Option<&mut T> { let nth = self.index(key); if let Some(_) = self.valid.get(nth) { Option::None } else { self.data.get_mut(nth) } } } impl <T> BranchNode<T> { fn new() -> BranchNode<T> { BranchNode{branches: Vec::with_capacity(1), valid: BitVec::with_capacity(1)} } } impl <T> Trie<T> { fn new() -> Trie<T> { Trie{root: Node::Empty} } } fn main() { let mut t: LeafNode<String> = LeafNode::new(); t.insert(0xFFFF0, "foo".to_string()); }
use crate::Part; use regex::Regex; use std::collections::HashMap; struct Entry(HashMap<String, String>); pub fn run(part: Part, input_str: &str) { let re = Regex::new(r"(?P<field>[a-z]+):(?P<value>\S+)").unwrap(); let mut entries = Vec::new(); for passport in input_str.split("\n\n") { let mut hash = HashMap::new(); for cap in re.captures_iter(passport) { hash.insert(cap["field"].to_string(), cap["value"].to_string()); } entries.push(Entry(hash)) } match part { Part::First => part1(&entries), Part::Second => part2(&entries), Part::All => { part1(&entries); part2(&entries); }, } } fn part1(entries: &[Entry]) { let required_fields = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]; let num_valid = entries.iter().filter(|Entry(m)| { required_fields.iter().all(|field| m.contains_key(&field.to_string())) }).count(); println!("{}", num_valid); } fn part2(entries: &[Entry]) { let hcl_re = Regex::new(r"^#[0-9a-f]{6}$").unwrap(); let hgt_re = Regex::new(r"^(?P<height>\d+)(?P<unit>cm|in)$").unwrap(); let ecl_re = Regex::new(r"^(amb|blu|brn|gry|grn|hzl|oth)$").unwrap(); let pid_re = Regex::new(r"^[0-9]{9}$").unwrap(); let num_valid = entries.iter().filter(|Entry(m)| { let checks = [ m.get("byr").map_or(false, |y| y.parse::<u32>().map_or(false, |y| 1920 <= y && y <= 2002)), m.get("iyr").map_or(false, |y| y.parse::<u32>().map_or(false, |y| 2010 <= y && y <= 2020)), m.get("eyr").map_or(false, |y| y.parse::<u32>().map_or(false, |y| 2020 <= y && y <= 2030)), {if let Some(hgt) = m.get("hgt") { hgt_re.captures(hgt).map_or(false, |cap| { let x = cap["height"].parse::<u32>().unwrap(); if &cap["unit"] == "cm" { 150 <= x && x <= 193 } else { 59 <= x && x <= 76 } }) } else { false }}, m.get("hcl").map_or(false, |c| hcl_re.is_match(c)), m.get("ecl").map_or(false, |c| ecl_re.is_match(c)), m.get("pid").map_or(false, |pid| pid_re.is_match(pid)), ]; checks.iter().all(|&b| b) }).count(); println!("{}", num_valid); }
use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; pub type PythonScripts = BTreeMap<String, PythonScript>; #[derive(Clone, Debug, Serialize, Deserialize)] pub struct PythonScript { pub name: String, pub source: String, } impl PartialEq for PythonScript { fn eq(&self, other: &Self) -> bool { self.name.eq(&other.name) } }
#[macro_use] extern crate log; extern crate term; extern crate getopts; extern crate openssl; extern crate mqtt3; extern crate netopt; extern crate mqttc; pub mod client;
use failure::{bail, Fallible}; use std::process::Command; pub(crate) trait CommandRunExt { fn run(&mut self) -> Fallible<()>; } impl CommandRunExt for Command { fn run(&mut self) -> Fallible<()> { let r = self.status()?; if !r.success() { bail!("Child [{:?}] exited: {}", self, r); } Ok(()) } }
#[doc = "Reader of register ASCR2"] pub type R = crate::R<u32, super::ASCR2>; #[doc = "Writer for register ASCR2"] pub type W = crate::W<u32, super::ASCR2>; #[doc = "Register ASCR2 `reset()`'s with value 0"] impl crate::ResetValue for super::ASCR2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `GR5_4`"] pub type GR5_4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR5_4`"] pub struct GR5_4_W<'a> { w: &'a mut W, } impl<'a> GR5_4_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "Reader of field `GR6_4`"] pub type GR6_4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR6_4`"] pub struct GR6_4_W<'a> { w: &'a mut W, } impl<'a> GR6_4_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "Reader of field `GR6_3`"] pub type GR6_3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR6_3`"] pub struct GR6_3_W<'a> { w: &'a mut W, } impl<'a> GR6_3_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "Reader of field `GR7_7`"] pub type GR7_7_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR7_7`"] pub struct GR7_7_W<'a> { w: &'a mut W, } impl<'a> GR7_7_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `GR7_6`"] pub type GR7_6_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR7_6`"] pub struct GR7_6_W<'a> { w: &'a mut W, } impl<'a> GR7_6_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25); self.w } } #[doc = "Reader of field `GR7_5`"] pub type GR7_5_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR7_5`"] pub struct GR7_5_W<'a> { w: &'a mut W, } impl<'a> GR7_5_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `GR2_5`"] pub type GR2_5_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR2_5`"] pub struct GR2_5_W<'a> { w: &'a mut W, } impl<'a> GR2_5_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "Reader of field `GR2_4`"] pub type GR2_4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR2_4`"] pub struct GR2_4_W<'a> { w: &'a mut W, } impl<'a> GR2_4_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "Reader of field `GR2_3`"] pub type GR2_3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR2_3`"] pub struct GR2_3_W<'a> { w: &'a mut W, } impl<'a> GR2_3_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "Reader of field `GR9_4`"] pub type GR9_4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR9_4`"] pub struct GR9_4_W<'a> { w: &'a mut W, } impl<'a> GR9_4_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `GR9_3`"] pub type GR9_3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR9_3`"] pub struct GR9_3_W<'a> { w: &'a mut W, } impl<'a> GR9_3_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `GR3_5`"] pub type GR3_5_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR3_5`"] pub struct GR3_5_W<'a> { w: &'a mut W, } impl<'a> GR3_5_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `GR3_4`"] pub type GR3_4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR3_4`"] pub struct GR3_4_W<'a> { w: &'a mut W, } impl<'a> GR3_4_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `GR3_3`"] pub type GR3_3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR3_3`"] pub struct GR3_3_W<'a> { w: &'a mut W, } impl<'a> GR3_3_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `GR4_3`"] pub type GR4_3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR4_3`"] pub struct GR4_3_W<'a> { w: &'a mut W, } impl<'a> GR4_3_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `GR4_2`"] pub type GR4_2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR4_2`"] pub struct GR4_2_W<'a> { w: &'a mut W, } impl<'a> GR4_2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `GR4_1`"] pub type GR4_1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR4_1`"] pub struct GR4_1_W<'a> { w: &'a mut W, } impl<'a> GR4_1_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `GR5_3`"] pub type GR5_3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR5_3`"] pub struct GR5_3_W<'a> { w: &'a mut W, } impl<'a> GR5_3_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `GR5_2`"] pub type GR5_2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR5_2`"] pub struct GR5_2_W<'a> { w: &'a mut W, } impl<'a> GR5_2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `GR5_1`"] pub type GR5_1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR5_1`"] pub struct GR5_1_W<'a> { w: &'a mut W, } impl<'a> GR5_1_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `GR6_2`"] pub type GR6_2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR6_2`"] pub struct GR6_2_W<'a> { w: &'a mut W, } impl<'a> GR6_2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `GR6_1`"] pub type GR6_1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR6_1`"] pub struct GR6_1_W<'a> { w: &'a mut W, } impl<'a> GR6_1_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `GR10_4`"] pub type GR10_4_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR10_4`"] pub struct GR10_4_W<'a> { w: &'a mut W, } impl<'a> GR10_4_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Reader of field `GR10_3`"] pub type GR10_3_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR10_3`"] pub struct GR10_3_W<'a> { w: &'a mut W, } impl<'a> GR10_3_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `GR10_2`"] pub type GR10_2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR10_2`"] pub struct GR10_2_W<'a> { w: &'a mut W, } impl<'a> GR10_2_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `GR10_1`"] pub type GR10_1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GR10_1`"] pub struct GR10_1_W<'a> { w: &'a mut W, } impl<'a> GR10_1_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bit 29 - GR5_4 analog switch control"] #[inline(always)] pub fn gr5_4(&self) -> GR5_4_R { GR5_4_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 28 - GR6_4 analog switch control"] #[inline(always)] pub fn gr6_4(&self) -> GR6_4_R { GR6_4_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 27 - GR6_3 analog switch control"] #[inline(always)] pub fn gr6_3(&self) -> GR6_3_R { GR6_3_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 26 - GR7_7 analog switch control"] #[inline(always)] pub fn gr7_7(&self) -> GR7_7_R { GR7_7_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 25 - GR7_6 analog switch control"] #[inline(always)] pub fn gr7_6(&self) -> GR7_6_R { GR7_6_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 24 - GR7_5 analog switch control"] #[inline(always)] pub fn gr7_5(&self) -> GR7_5_R { GR7_5_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 23 - GR2_5 analog switch control"] #[inline(always)] pub fn gr2_5(&self) -> GR2_5_R { GR2_5_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 22 - GR2_4 analog switch control"] #[inline(always)] pub fn gr2_4(&self) -> GR2_4_R { GR2_4_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 21 - GR2_3 analog switch control"] #[inline(always)] pub fn gr2_3(&self) -> GR2_3_R { GR2_3_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 20 - GR9_4 analog switch control"] #[inline(always)] pub fn gr9_4(&self) -> GR9_4_R { GR9_4_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 19 - GR9_3 analog switch control"] #[inline(always)] pub fn gr9_3(&self) -> GR9_3_R { GR9_3_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 18 - GR3_5 analog switch control"] #[inline(always)] pub fn gr3_5(&self) -> GR3_5_R { GR3_5_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 17 - GR3_4 analog switch control"] #[inline(always)] pub fn gr3_4(&self) -> GR3_4_R { GR3_4_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - GR3_3 analog switch control"] #[inline(always)] pub fn gr3_3(&self) -> GR3_3_R { GR3_3_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 11 - GR4_3 analog switch control"] #[inline(always)] pub fn gr4_3(&self) -> GR4_3_R { GR4_3_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 10 - GR4_2 analog switch control"] #[inline(always)] pub fn gr4_2(&self) -> GR4_2_R { GR4_2_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 9 - GR4_1 analog switch control"] #[inline(always)] pub fn gr4_1(&self) -> GR4_1_R { GR4_1_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 8 - GR5_3 analog switch control"] #[inline(always)] pub fn gr5_3(&self) -> GR5_3_R { GR5_3_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 7 - GR5_2 analog switch control"] #[inline(always)] pub fn gr5_2(&self) -> GR5_2_R { GR5_2_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 6 - GR5_1 analog switch control"] #[inline(always)] pub fn gr5_1(&self) -> GR5_1_R { GR5_1_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 5 - GR6_2 analog switch control"] #[inline(always)] pub fn gr6_2(&self) -> GR6_2_R { GR6_2_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4 - GR6_1 analog switch control"] #[inline(always)] pub fn gr6_1(&self) -> GR6_1_R { GR6_1_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - GR10_4 analog switch control"] #[inline(always)] pub fn gr10_4(&self) -> GR10_4_R { GR10_4_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - GR10_3 analog switch control"] #[inline(always)] pub fn gr10_3(&self) -> GR10_3_R { GR10_3_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - GR10_2 analog switch control"] #[inline(always)] pub fn gr10_2(&self) -> GR10_2_R { GR10_2_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - GR10_1 analog switch control"] #[inline(always)] pub fn gr10_1(&self) -> GR10_1_R { GR10_1_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 29 - GR5_4 analog switch control"] #[inline(always)] pub fn gr5_4(&mut self) -> GR5_4_W { GR5_4_W { w: self } } #[doc = "Bit 28 - GR6_4 analog switch control"] #[inline(always)] pub fn gr6_4(&mut self) -> GR6_4_W { GR6_4_W { w: self } } #[doc = "Bit 27 - GR6_3 analog switch control"] #[inline(always)] pub fn gr6_3(&mut self) -> GR6_3_W { GR6_3_W { w: self } } #[doc = "Bit 26 - GR7_7 analog switch control"] #[inline(always)] pub fn gr7_7(&mut self) -> GR7_7_W { GR7_7_W { w: self } } #[doc = "Bit 25 - GR7_6 analog switch control"] #[inline(always)] pub fn gr7_6(&mut self) -> GR7_6_W { GR7_6_W { w: self } } #[doc = "Bit 24 - GR7_5 analog switch control"] #[inline(always)] pub fn gr7_5(&mut self) -> GR7_5_W { GR7_5_W { w: self } } #[doc = "Bit 23 - GR2_5 analog switch control"] #[inline(always)] pub fn gr2_5(&mut self) -> GR2_5_W { GR2_5_W { w: self } } #[doc = "Bit 22 - GR2_4 analog switch control"] #[inline(always)] pub fn gr2_4(&mut self) -> GR2_4_W { GR2_4_W { w: self } } #[doc = "Bit 21 - GR2_3 analog switch control"] #[inline(always)] pub fn gr2_3(&mut self) -> GR2_3_W { GR2_3_W { w: self } } #[doc = "Bit 20 - GR9_4 analog switch control"] #[inline(always)] pub fn gr9_4(&mut self) -> GR9_4_W { GR9_4_W { w: self } } #[doc = "Bit 19 - GR9_3 analog switch control"] #[inline(always)] pub fn gr9_3(&mut self) -> GR9_3_W { GR9_3_W { w: self } } #[doc = "Bit 18 - GR3_5 analog switch control"] #[inline(always)] pub fn gr3_5(&mut self) -> GR3_5_W { GR3_5_W { w: self } } #[doc = "Bit 17 - GR3_4 analog switch control"] #[inline(always)] pub fn gr3_4(&mut self) -> GR3_4_W { GR3_4_W { w: self } } #[doc = "Bit 16 - GR3_3 analog switch control"] #[inline(always)] pub fn gr3_3(&mut self) -> GR3_3_W { GR3_3_W { w: self } } #[doc = "Bit 11 - GR4_3 analog switch control"] #[inline(always)] pub fn gr4_3(&mut self) -> GR4_3_W { GR4_3_W { w: self } } #[doc = "Bit 10 - GR4_2 analog switch control"] #[inline(always)] pub fn gr4_2(&mut self) -> GR4_2_W { GR4_2_W { w: self } } #[doc = "Bit 9 - GR4_1 analog switch control"] #[inline(always)] pub fn gr4_1(&mut self) -> GR4_1_W { GR4_1_W { w: self } } #[doc = "Bit 8 - GR5_3 analog switch control"] #[inline(always)] pub fn gr5_3(&mut self) -> GR5_3_W { GR5_3_W { w: self } } #[doc = "Bit 7 - GR5_2 analog switch control"] #[inline(always)] pub fn gr5_2(&mut self) -> GR5_2_W { GR5_2_W { w: self } } #[doc = "Bit 6 - GR5_1 analog switch control"] #[inline(always)] pub fn gr5_1(&mut self) -> GR5_1_W { GR5_1_W { w: self } } #[doc = "Bit 5 - GR6_2 analog switch control"] #[inline(always)] pub fn gr6_2(&mut self) -> GR6_2_W { GR6_2_W { w: self } } #[doc = "Bit 4 - GR6_1 analog switch control"] #[inline(always)] pub fn gr6_1(&mut self) -> GR6_1_W { GR6_1_W { w: self } } #[doc = "Bit 3 - GR10_4 analog switch control"] #[inline(always)] pub fn gr10_4(&mut self) -> GR10_4_W { GR10_4_W { w: self } } #[doc = "Bit 2 - GR10_3 analog switch control"] #[inline(always)] pub fn gr10_3(&mut self) -> GR10_3_W { GR10_3_W { w: self } } #[doc = "Bit 1 - GR10_2 analog switch control"] #[inline(always)] pub fn gr10_2(&mut self) -> GR10_2_W { GR10_2_W { w: self } } #[doc = "Bit 0 - GR10_1 analog switch control"] #[inline(always)] pub fn gr10_1(&mut self) -> GR10_1_W { GR10_1_W { w: self } } }
// Copyright 2018 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. // Regression test for #48551. Covers a case where duplicate candidates // arose during associated type projection. use std::ops::{Mul, MulAssign}; pub trait ClosedMul<Right>: Sized + Mul<Right, Output = Self> + MulAssign<Right> {} impl<T, Right> ClosedMul<Right> for T where T: Mul<Right, Output = T> + MulAssign<Right>, { } pub trait InnerSpace: ClosedMul<<Self as InnerSpace>::Real> { type Real; } pub trait FiniteDimVectorSpace: ClosedMul<<Self as FiniteDimVectorSpace>::Field> { type Field; } pub trait FiniteDimInnerSpace : InnerSpace + FiniteDimVectorSpace<Field = <Self as InnerSpace>::Real> { } pub trait EuclideanSpace: ClosedMul<<Self as EuclideanSpace>::Real> { type Coordinates: FiniteDimInnerSpace<Real = Self::Real> + Mul<Self::Real, Output = Self::Coordinates> + MulAssign<Self::Real>; type Real; } fn main() {}
#[cfg(test)] mod test { use crate::data_structures::linked_list::{LinkedList}; #[test] fn basic() { let mut foo: LinkedList<i32> = LinkedList::new(); foo.push(1); foo.push(2); foo.push(3); foo.push(4); assert_eq!(foo.pop(), Some(4)); assert_eq!(*foo.peek().unwrap(), 3); //assert_eq!(foo.get(3), Some(1)); } #[test] fn into_iter() { let mut list: LinkedList<i32> = LinkedList::new(); list.push(1); list.push(2); list.push(3); list.push(4); let mut iter = list.into_iter(); assert_eq!(iter.next(), Some(4)); assert_eq!(iter.next(), Some(3)); assert_eq!(iter.next(), Some(2)); assert_eq!(iter.next(), Some(1)); assert_eq!(iter.next(), None); } #[test] fn iter() { let mut list = LinkedList::new(); list.push(1); list.push(2); list.push(3); let mut iter = list.iter(); assert_eq!(iter.next(), Some(&3)); assert_eq!(iter.next(), Some(&2)); assert_eq!(iter.next(), Some(&1)); } #[test] fn iter_mut() { let mut list = LinkedList::new(); list.push(1); list.push(2); list.push(3); let mut iter = list.iter_mut(); assert_eq!(iter.next(), Some(&mut 3)); assert_eq!(iter.next(), Some(&mut 2)); assert_eq!(iter.next(), Some(&mut 1)); } }
// Implementation derived from `weak` in Rust's // library/std/src/sys/unix/weak.rs at revision // fd0cb0cdc21dd9c06025277d772108f8d42cb25f. // // Ideally we should update to a newer version which doesn't need `dlsym`, // however that depends on the `extern_weak` feature which is currently // unstable. #![cfg_attr(linux_raw, allow(unsafe_code))] //! Support for "weak linkage" to symbols on Unix //! //! Some I/O operations we do in libstd require newer versions of OSes but we //! need to maintain binary compatibility with older releases for now. In order //! to use the new functionality when available we use this module for //! detection. //! //! One option to use here is weak linkage, but that is unfortunately only //! really workable on Linux. Hence, use dlsym to get the symbol value at //! runtime. This is also done for compatibility with older versions of glibc, //! and to avoid creating dependencies on `GLIBC_PRIVATE` symbols. It assumes //! that we've been dynamically linked to the library the symbol comes from, //! but that is currently always the case for things like libpthread/libc. //! //! A long time ago this used weak linkage for the `__pthread_get_minstack` //! symbol, but that caused Debian to detect an unnecessarily strict versioned //! dependency on libc6 (#23628). // There are a variety of `#[cfg]`s controlling which targets are involved in // each instance of `weak!` and `syscall!`. Rather than trying to unify all of // that, we'll just allow that some unix targets don't use this module at all. #![allow(dead_code, unused_macros)] #![allow(clippy::doc_markdown)] use crate::ffi::CStr; use core::ffi::c_void; use core::ptr::null_mut; use core::sync::atomic::{self, AtomicPtr, Ordering}; use core::{marker, mem}; const NULL: *mut c_void = null_mut(); const INVALID: *mut c_void = 1 as *mut c_void; macro_rules! weak { ($vis:vis fn $name:ident($($t:ty),*) -> $ret:ty) => ( #[allow(non_upper_case_globals)] $vis static $name: $crate::weak::Weak<unsafe extern fn($($t),*) -> $ret> = $crate::weak::Weak::new(concat!(stringify!($name), '\0')); ) } pub(crate) struct Weak<F> { name: &'static str, addr: AtomicPtr<c_void>, _marker: marker::PhantomData<F>, } impl<F> Weak<F> { pub(crate) const fn new(name: &'static str) -> Self { Self { name, addr: AtomicPtr::new(INVALID), _marker: marker::PhantomData, } } pub(crate) fn get(&self) -> Option<F> { assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>()); unsafe { // Relaxed is fine here because we fence before reading through the // pointer (see the comment below). match self.addr.load(Ordering::Relaxed) { INVALID => self.initialize(), NULL => None, addr => { let func = mem::transmute_copy::<*mut c_void, F>(&addr); // The caller is presumably going to read through this value // (by calling the function we've dlsymed). This means we'd // need to have loaded it with at least C11's consume // ordering in order to be guaranteed that the data we read // from the pointer isn't from before the pointer was // stored. Rust has no equivalent to memory_order_consume, // so we use an acquire fence (sorry, ARM). // // Now, in practice this likely isn't needed even on CPUs // where relaxed and consume mean different things. The // symbols we're loading are probably present (or not) at // init, and even if they aren't the runtime dynamic loader // is extremely likely have sufficient barriers internally // (possibly implicitly, for example the ones provided by // invoking `mprotect`). // // That said, none of that's *guaranteed*, and so we fence. atomic::fence(Ordering::Acquire); Some(func) } } } } // Cold because it should only happen during first-time initialization. #[cold] unsafe fn initialize(&self) -> Option<F> { let val = fetch(self.name); // This synchronizes with the acquire fence in `get`. self.addr.store(val, Ordering::Release); match val { NULL => None, addr => Some(mem::transmute_copy::<*mut c_void, F>(&addr)), } } } // To avoid having the `linux_raw` backend depend on the libc crate, just // declare the few things we need in a module called `libc` so that `fetch` // uses it. #[cfg(linux_raw)] mod libc { use core::ptr; use linux_raw_sys::ctypes::{c_char, c_void}; #[cfg(all(target_os = "android", target_pointer_width = "32"))] pub(super) const RTLD_DEFAULT: *mut c_void = -1isize as *mut c_void; #[cfg(not(all(target_os = "android", target_pointer_width = "32")))] pub(super) const RTLD_DEFAULT: *mut c_void = ptr::null_mut(); extern "C" { pub(super) fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void; } #[test] fn test_abi() { assert_eq!(self::RTLD_DEFAULT, ::libc::RTLD_DEFAULT); } } unsafe fn fetch(name: &str) -> *mut c_void { let name = match CStr::from_bytes_with_nul(name.as_bytes()) { Ok(c_str) => c_str, Err(..) => return null_mut(), }; libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr().cast()) } #[cfg(not(linux_kernel))] macro_rules! syscall { (fn $name:ident($($arg_name:ident: $t:ty),*) via $_sys_name:ident -> $ret:ty) => ( unsafe fn $name($($arg_name: $t),*) -> $ret { weak! { fn $name($($t),*) -> $ret } if let Some(fun) = $name.get() { fun($($arg_name),*) } else { libc_errno::set_errno(libc_errno::Errno(libc::ENOSYS)); -1 } } ) } #[cfg(linux_kernel)] macro_rules! syscall { (fn $name:ident($($arg_name:ident: $t:ty),*) via $sys_name:ident -> $ret:ty) => ( unsafe fn $name($($arg_name:$t),*) -> $ret { // This looks like a hack, but `concat_idents` only accepts idents // (not paths). use libc::*; trait AsSyscallArg { type SyscallArgType; fn into_syscall_arg(self) -> Self::SyscallArgType; } // Pass pointer types as pointers, to preserve provenance. impl<T> AsSyscallArg for *mut T { type SyscallArgType = *mut T; fn into_syscall_arg(self) -> Self::SyscallArgType { self } } impl<T> AsSyscallArg for *const T { type SyscallArgType = *const T; fn into_syscall_arg(self) -> Self::SyscallArgType { self } } // Pass `BorrowedFd` values as the integer value. impl AsSyscallArg for $crate::fd::BorrowedFd<'_> { type SyscallArgType = ::libc::c_long; fn into_syscall_arg(self) -> Self::SyscallArgType { $crate::fd::AsRawFd::as_raw_fd(&self) as _ } } // Coerce integer values into `c_long`. impl AsSyscallArg for i8 { type SyscallArgType = ::libc::c_long; fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ } } impl AsSyscallArg for u8 { type SyscallArgType = ::libc::c_long; fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ } } impl AsSyscallArg for i16 { type SyscallArgType = ::libc::c_long; fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ } } impl AsSyscallArg for u16 { type SyscallArgType = ::libc::c_long; fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ } } impl AsSyscallArg for i32 { type SyscallArgType = ::libc::c_long; fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ } } impl AsSyscallArg for u32 { type SyscallArgType = ::libc::c_long; fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ } } impl AsSyscallArg for usize { type SyscallArgType = ::libc::c_long; fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ } } // On 64-bit platforms, also coerce `i64` and `u64` since `c_long` // is 64-bit and can hold those values. #[cfg(target_pointer_width = "64")] impl AsSyscallArg for i64 { type SyscallArgType = ::libc::c_long; fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ } } #[cfg(target_pointer_width = "64")] impl AsSyscallArg for u64 { type SyscallArgType = ::libc::c_long; fn into_syscall_arg(self) -> Self::SyscallArgType { self as _ } } // `concat_idents` is [unstable], so we take an extra `sys_name` // parameter and have our users do the concat for us for now. // // [unstable]: https://github.com/rust-lang/rust/issues/29599 /* syscall( concat_idents!(SYS_, $name), $($arg_name.into_syscall_arg()),* ) as $ret */ syscall($sys_name, $($arg_name.into_syscall_arg()),*) as $ret } ) } macro_rules! weakcall { ($vis:vis fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => ( $vis unsafe fn $name($($arg_name: $t),*) -> $ret { weak! { fn $name($($t),*) -> $ret } // Use a weak symbol from libc when possible, allowing `LD_PRELOAD` // interposition, but if it's not found just fail. if let Some(fun) = $name.get() { fun($($arg_name),*) } else { libc_errno::set_errno(libc_errno::Errno(libc::ENOSYS)); -1 } } ) } /// A combination of `weakcall` and `syscall`. Use the libc function if it's /// available, and fall back to `libc::syscall` otherwise. macro_rules! weak_or_syscall { ($vis:vis fn $name:ident($($arg_name:ident: $t:ty),*) via $sys_name:ident -> $ret:ty) => ( $vis unsafe fn $name($($arg_name: $t),*) -> $ret { weak! { fn $name($($t),*) -> $ret } // Use a weak symbol from libc when possible, allowing `LD_PRELOAD` // interposition, but if it's not found just fail. if let Some(fun) = $name.get() { fun($($arg_name),*) } else { syscall! { fn $name($($arg_name: $t),*) via $sys_name -> $ret } $name($($arg_name),*) } } ) }
use bevy::{diagnostic::FrameTimeDiagnosticsPlugin, diagnostic::PrintDiagnosticsPlugin, prelude::*}; // use collision_rays::CollisionRay; use components::DarkSkyComponentRegistry; // use main_2d_camera::Main2dCamera; use main_3d_camera::Main3dCamera; // use meshie_ship_test::MeshieShipTest; // use motion_test::MotionTest; // use player_ship::PlayerShip; use sectors::Sectors; use starmap::StarMap; mod collision_rays; mod components; mod equations_of_motion; mod main_2d_camera; mod main_3d_camera; mod main_menu; mod material; mod meshie_ship_test; mod motion_test; mod player_ship; mod sectors; mod starmap; mod movement_debug; fn main() { App::build() .add_resource(Msaa { samples: 4 }) .add_resource(ClearColor(Color::BLACK)) .add_default_plugins() .add_plugin(FrameTimeDiagnosticsPlugin::default()) .add_plugin(PrintDiagnosticsPlugin::default()) // .add_plugin(Main2dCamera) .add_plugin(Main3dCamera) .add_plugin(DarkSkyComponentRegistry) .add_plugin(StarMap) .add_plugin(movement_debug::MovementDebug) // .add_plugin(Sectors) // .add_plugin(PlayerShip) // .add_plugin(MeshieShipTest) // .add_plugin(MotionTest) // .add_plugin(CollisionRay) // .add_plugin(main_menu::MainMenu) .run(); }
use std::io; use std::convert; #[derive(Fail, Debug)] pub enum Error { #[fail(display = "parser cmd fail : {}", _0)] ParseCmdFailError(String), #[fail(display = "I/O error")] Io(#[cause] ::std::io::Error), } impl convert::From<io::Error> for Error { fn from(error: io::Error) -> Self { Error::Io(error) } } pub type Result<T> = ::std::result::Result<T, Error>;
use juniper::graphql_interface; #[graphql_interface] trait Character { fn id(&self) -> &str; #[graphql(name = "id")] fn id2(&self) -> &str; } fn main() {}
use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use beerxml::hop; #[test] fn hops_file_read() { let file = File::open("tests/beerxml/data/hops.xml").unwrap(); let mut buf_reader = BufReader::new(file); let mut contents = String::new(); buf_reader.read_to_string(&mut contents).unwrap(); let parsed_record: hop::Hops = serde_xml_rs::from_str(&contents).unwrap(); assert_eq!(parsed_record.hop.len(), 5); }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; /// Defines API to convert from/to protobuf meta type. pub trait FromToProto { /// The corresponding protobuf defined type. type PB; /// Get the version encoded in a protobuf message. fn get_pb_ver(p: &Self::PB) -> u64; /// Convert to rust type from protobuf type. fn from_pb(p: Self::PB) -> Result<Self, Incompatible> where Self: Sized; /// Convert from rust type to protobuf type. fn to_pb(&self) -> Result<Self::PB, Incompatible>; } #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] #[error("Incompatible: {reason}")] pub struct Incompatible { pub reason: String, } impl<T> FromToProto for Arc<T> where T: FromToProto { type PB = T::PB; fn get_pb_ver(p: &Self::PB) -> u64 { T::get_pb_ver(p) } fn from_pb(p: Self::PB) -> Result<Self, Incompatible> where Self: Sized { Ok(Arc::new(T::from_pb(p)?)) } fn to_pb(&self) -> Result<T::PB, Incompatible> { let s = self.as_ref(); s.to_pb() } }
import foo::bar; mod foo { import zed::bar; export bar; mod zed { fn bar() { log "foo"; } } } fn main(args: vec[str]) { bar(); }
//! Core for ATmega88PA. use crate::{modules, RegisterBits, Register}; #[allow(non_camel_case_types)] pub struct EXTENDED; impl EXTENDED { pub const BOOTSZ: RegisterBits<Self> = RegisterBits::new(0x6); pub const BOOTSZ0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const BOOTSZ1: RegisterBits<Self> = RegisterBits::new(1<<2); pub const BOOTRST: RegisterBits<Self> = RegisterBits::new(0x1); pub const BOOTRST0: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for EXTENDED { type T = u8; const ADDRESS: *mut u8 = 0x2 as *mut u8; } #[allow(non_camel_case_types)] pub struct HIGH; impl HIGH { pub const RSTDISBL: RegisterBits<Self> = RegisterBits::new(0x80); pub const RSTDISBL0: RegisterBits<Self> = RegisterBits::new(1<<7); pub const DWEN: RegisterBits<Self> = RegisterBits::new(0x40); pub const DWEN0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const SPIEN: RegisterBits<Self> = RegisterBits::new(0x20); pub const SPIEN0: RegisterBits<Self> = RegisterBits::new(1<<5); pub const WDTON: RegisterBits<Self> = RegisterBits::new(0x10); pub const WDTON0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const EESAVE: RegisterBits<Self> = RegisterBits::new(0x8); pub const EESAVE0: RegisterBits<Self> = RegisterBits::new(1<<3); pub const BODLEVEL: RegisterBits<Self> = RegisterBits::new(0x7); pub const BODLEVEL0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const BODLEVEL1: RegisterBits<Self> = RegisterBits::new(1<<1); pub const BODLEVEL2: RegisterBits<Self> = RegisterBits::new(1<<2); } impl Register for HIGH { type T = u8; const ADDRESS: *mut u8 = 0x1 as *mut u8; } #[allow(non_camel_case_types)] pub struct LOW; impl LOW { pub const CKDIV8: RegisterBits<Self> = RegisterBits::new(0x80); pub const CKDIV80: RegisterBits<Self> = RegisterBits::new(1<<7); pub const CKOUT: RegisterBits<Self> = RegisterBits::new(0x40); pub const CKOUT0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const SUT_CKSEL: RegisterBits<Self> = RegisterBits::new(0x3f); pub const SUT_CKSEL0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const SUT_CKSEL1: RegisterBits<Self> = RegisterBits::new(1<<1); pub const SUT_CKSEL2: RegisterBits<Self> = RegisterBits::new(1<<2); pub const SUT_CKSEL3: RegisterBits<Self> = RegisterBits::new(1<<3); pub const SUT_CKSEL4: RegisterBits<Self> = RegisterBits::new(1<<4); pub const SUT_CKSEL5: RegisterBits<Self> = RegisterBits::new(1<<5); } impl Register for LOW { type T = u8; const ADDRESS: *mut u8 = 0x0 as *mut u8; } #[allow(non_camel_case_types)] pub struct LOCKBIT; impl LOCKBIT { pub const LB: RegisterBits<Self> = RegisterBits::new(0x3); pub const LB0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const LB1: RegisterBits<Self> = RegisterBits::new(1<<1); pub const BLB0: RegisterBits<Self> = RegisterBits::new(0xc); pub const BLB00: RegisterBits<Self> = RegisterBits::new(1<<2); pub const BLB01: RegisterBits<Self> = RegisterBits::new(1<<3); pub const BLB1: RegisterBits<Self> = RegisterBits::new(0x30); pub const BLB10: RegisterBits<Self> = RegisterBits::new(1<<4); pub const BLB11: RegisterBits<Self> = RegisterBits::new(1<<5); } impl Register for LOCKBIT { type T = u8; const ADDRESS: *mut u8 = 0x0 as *mut u8; } #[allow(non_camel_case_types)] pub struct UDR0; impl UDR0 { } impl Register for UDR0 { type T = u8; const ADDRESS: *mut u8 = 0xc6 as *mut u8; } #[allow(non_camel_case_types)] pub struct UCSR0A; impl UCSR0A { pub const RXC0: RegisterBits<Self> = RegisterBits::new(0x80); pub const RXC00: RegisterBits<Self> = RegisterBits::new(1<<7); pub const TXC0: RegisterBits<Self> = RegisterBits::new(0x40); pub const TXC00: RegisterBits<Self> = RegisterBits::new(1<<6); pub const UDRE0: RegisterBits<Self> = RegisterBits::new(0x20); pub const UDRE00: RegisterBits<Self> = RegisterBits::new(1<<5); pub const FE0: RegisterBits<Self> = RegisterBits::new(0x10); pub const FE00: RegisterBits<Self> = RegisterBits::new(1<<4); pub const DOR0: RegisterBits<Self> = RegisterBits::new(0x8); pub const DOR00: RegisterBits<Self> = RegisterBits::new(1<<3); pub const UPE0: RegisterBits<Self> = RegisterBits::new(0x4); pub const UPE00: RegisterBits<Self> = RegisterBits::new(1<<2); pub const U2X0: RegisterBits<Self> = RegisterBits::new(0x2); pub const U2X00: RegisterBits<Self> = RegisterBits::new(1<<1); pub const MPCM0: RegisterBits<Self> = RegisterBits::new(0x1); pub const MPCM00: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for UCSR0A { type T = u8; const ADDRESS: *mut u8 = 0xc0 as *mut u8; } #[allow(non_camel_case_types)] pub struct UCSR0B; impl UCSR0B { pub const RXCIE0: RegisterBits<Self> = RegisterBits::new(0x80); pub const RXCIE00: RegisterBits<Self> = RegisterBits::new(1<<7); pub const TXCIE0: RegisterBits<Self> = RegisterBits::new(0x40); pub const TXCIE00: RegisterBits<Self> = RegisterBits::new(1<<6); pub const UDRIE0: RegisterBits<Self> = RegisterBits::new(0x20); pub const UDRIE00: RegisterBits<Self> = RegisterBits::new(1<<5); pub const RXEN0: RegisterBits<Self> = RegisterBits::new(0x10); pub const RXEN00: RegisterBits<Self> = RegisterBits::new(1<<4); pub const TXEN0: RegisterBits<Self> = RegisterBits::new(0x8); pub const TXEN00: RegisterBits<Self> = RegisterBits::new(1<<3); pub const UCSZ02: RegisterBits<Self> = RegisterBits::new(0x4); pub const UCSZ020: RegisterBits<Self> = RegisterBits::new(1<<2); pub const RXB80: RegisterBits<Self> = RegisterBits::new(0x2); pub const RXB800: RegisterBits<Self> = RegisterBits::new(1<<1); pub const TXB80: RegisterBits<Self> = RegisterBits::new(0x1); pub const TXB800: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for UCSR0B { type T = u8; const ADDRESS: *mut u8 = 0xc1 as *mut u8; } #[allow(non_camel_case_types)] pub struct UCSR0C; impl UCSR0C { pub const UMSEL0: RegisterBits<Self> = RegisterBits::new(0xc0); pub const UMSEL00: RegisterBits<Self> = RegisterBits::new(1<<6); pub const UMSEL01: RegisterBits<Self> = RegisterBits::new(1<<7); pub const UPM0: RegisterBits<Self> = RegisterBits::new(0x30); pub const UPM00: RegisterBits<Self> = RegisterBits::new(1<<4); pub const UPM01: RegisterBits<Self> = RegisterBits::new(1<<5); pub const USBS0: RegisterBits<Self> = RegisterBits::new(0x8); pub const USBS00: RegisterBits<Self> = RegisterBits::new(1<<3); pub const UCSZ0: RegisterBits<Self> = RegisterBits::new(0x6); pub const UCSZ00: RegisterBits<Self> = RegisterBits::new(1<<1); pub const UCSZ01: RegisterBits<Self> = RegisterBits::new(1<<2); pub const UCPOL0: RegisterBits<Self> = RegisterBits::new(0x1); pub const UCPOL00: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for UCSR0C { type T = u8; const ADDRESS: *mut u8 = 0xc2 as *mut u8; } #[allow(non_camel_case_types)] pub struct UBRR0; impl UBRR0 { } impl Register for UBRR0 { type T = u16; const ADDRESS: *mut u16 = 0xc4 as *mut u16; } #[allow(non_camel_case_types)] pub struct TWAMR; impl TWAMR { pub const TWAM: RegisterBits<Self> = RegisterBits::new(0xfe); pub const TWAM0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const TWAM1: RegisterBits<Self> = RegisterBits::new(1<<2); pub const TWAM2: RegisterBits<Self> = RegisterBits::new(1<<3); pub const TWAM3: RegisterBits<Self> = RegisterBits::new(1<<4); pub const TWAM4: RegisterBits<Self> = RegisterBits::new(1<<5); pub const TWAM5: RegisterBits<Self> = RegisterBits::new(1<<6); pub const TWAM6: RegisterBits<Self> = RegisterBits::new(1<<7); } impl Register for TWAMR { type T = u8; const ADDRESS: *mut u8 = 0xbd as *mut u8; } #[allow(non_camel_case_types)] pub struct TWBR; impl TWBR { } impl Register for TWBR { type T = u8; const ADDRESS: *mut u8 = 0xb8 as *mut u8; } #[allow(non_camel_case_types)] pub struct TWCR; impl TWCR { pub const TWINT: RegisterBits<Self> = RegisterBits::new(0x80); pub const TWINT0: RegisterBits<Self> = RegisterBits::new(1<<7); pub const TWEA: RegisterBits<Self> = RegisterBits::new(0x40); pub const TWEA0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const TWSTA: RegisterBits<Self> = RegisterBits::new(0x20); pub const TWSTA0: RegisterBits<Self> = RegisterBits::new(1<<5); pub const TWSTO: RegisterBits<Self> = RegisterBits::new(0x10); pub const TWSTO0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const TWWC: RegisterBits<Self> = RegisterBits::new(0x8); pub const TWWC0: RegisterBits<Self> = RegisterBits::new(1<<3); pub const TWEN: RegisterBits<Self> = RegisterBits::new(0x4); pub const TWEN0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const TWIE: RegisterBits<Self> = RegisterBits::new(0x1); pub const TWIE0: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for TWCR { type T = u8; const ADDRESS: *mut u8 = 0xbc as *mut u8; } #[allow(non_camel_case_types)] pub struct TWSR; impl TWSR { pub const TWS: RegisterBits<Self> = RegisterBits::new(0xf8); pub const TWS0: RegisterBits<Self> = RegisterBits::new(1<<3); pub const TWS1: RegisterBits<Self> = RegisterBits::new(1<<4); pub const TWS2: RegisterBits<Self> = RegisterBits::new(1<<5); pub const TWS3: RegisterBits<Self> = RegisterBits::new(1<<6); pub const TWS4: RegisterBits<Self> = RegisterBits::new(1<<7); pub const TWPS: RegisterBits<Self> = RegisterBits::new(0x3); pub const TWPS0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const TWPS1: RegisterBits<Self> = RegisterBits::new(1<<1); } impl Register for TWSR { type T = u8; const ADDRESS: *mut u8 = 0xb9 as *mut u8; } #[allow(non_camel_case_types)] pub struct TWDR; impl TWDR { } impl Register for TWDR { type T = u8; const ADDRESS: *mut u8 = 0xbb as *mut u8; } #[allow(non_camel_case_types)] pub struct TWAR; impl TWAR { pub const TWA: RegisterBits<Self> = RegisterBits::new(0xfe); pub const TWA0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const TWA1: RegisterBits<Self> = RegisterBits::new(1<<2); pub const TWA2: RegisterBits<Self> = RegisterBits::new(1<<3); pub const TWA3: RegisterBits<Self> = RegisterBits::new(1<<4); pub const TWA4: RegisterBits<Self> = RegisterBits::new(1<<5); pub const TWA5: RegisterBits<Self> = RegisterBits::new(1<<6); pub const TWA6: RegisterBits<Self> = RegisterBits::new(1<<7); pub const TWGCE: RegisterBits<Self> = RegisterBits::new(0x1); pub const TWGCE0: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for TWAR { type T = u8; const ADDRESS: *mut u8 = 0xba as *mut u8; } #[allow(non_camel_case_types)] pub struct TIMSK1; impl TIMSK1 { pub const ICIE1: RegisterBits<Self> = RegisterBits::new(0x20); pub const ICIE10: RegisterBits<Self> = RegisterBits::new(1<<5); pub const OCIE1B: RegisterBits<Self> = RegisterBits::new(0x4); pub const OCIE1B0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const OCIE1A: RegisterBits<Self> = RegisterBits::new(0x2); pub const OCIE1A0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const TOIE1: RegisterBits<Self> = RegisterBits::new(0x1); pub const TOIE10: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for TIMSK1 { type T = u8; const ADDRESS: *mut u8 = 0x6f as *mut u8; } #[allow(non_camel_case_types)] pub struct TIFR1; impl TIFR1 { pub const ICF1: RegisterBits<Self> = RegisterBits::new(0x20); pub const ICF10: RegisterBits<Self> = RegisterBits::new(1<<5); pub const OCF1B: RegisterBits<Self> = RegisterBits::new(0x4); pub const OCF1B0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const OCF1A: RegisterBits<Self> = RegisterBits::new(0x2); pub const OCF1A0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const TOV1: RegisterBits<Self> = RegisterBits::new(0x1); pub const TOV10: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for TIFR1 { type T = u8; const ADDRESS: *mut u8 = 0x36 as *mut u8; } #[allow(non_camel_case_types)] pub struct TCCR1A; impl TCCR1A { pub const COM1A: RegisterBits<Self> = RegisterBits::new(0xc0); pub const COM1A0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const COM1A1: RegisterBits<Self> = RegisterBits::new(1<<7); pub const COM1B: RegisterBits<Self> = RegisterBits::new(0x30); pub const COM1B0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const COM1B1: RegisterBits<Self> = RegisterBits::new(1<<5); pub const WGM1: RegisterBits<Self> = RegisterBits::new(0x3); pub const WGM10: RegisterBits<Self> = RegisterBits::new(1<<0); pub const WGM11: RegisterBits<Self> = RegisterBits::new(1<<1); } impl Register for TCCR1A { type T = u8; const ADDRESS: *mut u8 = 0x80 as *mut u8; } #[allow(non_camel_case_types)] pub struct TCCR1B; impl TCCR1B { pub const ICNC1: RegisterBits<Self> = RegisterBits::new(0x80); pub const ICNC10: RegisterBits<Self> = RegisterBits::new(1<<7); pub const ICES1: RegisterBits<Self> = RegisterBits::new(0x40); pub const ICES10: RegisterBits<Self> = RegisterBits::new(1<<6); pub const WGM1: RegisterBits<Self> = RegisterBits::new(0x18); pub const WGM10: RegisterBits<Self> = RegisterBits::new(1<<3); pub const WGM11: RegisterBits<Self> = RegisterBits::new(1<<4); pub const CS1: RegisterBits<Self> = RegisterBits::new(0x7); pub const CS10: RegisterBits<Self> = RegisterBits::new(1<<0); pub const CS11: RegisterBits<Self> = RegisterBits::new(1<<1); pub const CS12: RegisterBits<Self> = RegisterBits::new(1<<2); } impl Register for TCCR1B { type T = u8; const ADDRESS: *mut u8 = 0x81 as *mut u8; } #[allow(non_camel_case_types)] pub struct TCCR1C; impl TCCR1C { pub const FOC1A: RegisterBits<Self> = RegisterBits::new(0x80); pub const FOC1A0: RegisterBits<Self> = RegisterBits::new(1<<7); pub const FOC1B: RegisterBits<Self> = RegisterBits::new(0x40); pub const FOC1B0: RegisterBits<Self> = RegisterBits::new(1<<6); } impl Register for TCCR1C { type T = u8; const ADDRESS: *mut u8 = 0x82 as *mut u8; } #[allow(non_camel_case_types)] pub struct TCNT1; impl TCNT1 { } impl Register for TCNT1 { type T = u16; const ADDRESS: *mut u16 = 0x84 as *mut u16; } #[allow(non_camel_case_types)] pub struct OCR1A; impl OCR1A { } impl Register for OCR1A { type T = u16; const ADDRESS: *mut u16 = 0x88 as *mut u16; } #[allow(non_camel_case_types)] pub struct OCR1B; impl OCR1B { } impl Register for OCR1B { type T = u16; const ADDRESS: *mut u16 = 0x8a as *mut u16; } #[allow(non_camel_case_types)] pub struct ICR1; impl ICR1 { } impl Register for ICR1 { type T = u16; const ADDRESS: *mut u16 = 0x86 as *mut u16; } #[allow(non_camel_case_types)] pub struct TIMSK2; impl TIMSK2 { pub const OCIE2B: RegisterBits<Self> = RegisterBits::new(0x4); pub const OCIE2B0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const OCIE2A: RegisterBits<Self> = RegisterBits::new(0x2); pub const OCIE2A0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const TOIE2: RegisterBits<Self> = RegisterBits::new(0x1); pub const TOIE20: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for TIMSK2 { type T = u8; const ADDRESS: *mut u8 = 0x70 as *mut u8; } #[allow(non_camel_case_types)] pub struct TIFR2; impl TIFR2 { pub const OCF2B: RegisterBits<Self> = RegisterBits::new(0x4); pub const OCF2B0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const OCF2A: RegisterBits<Self> = RegisterBits::new(0x2); pub const OCF2A0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const TOV2: RegisterBits<Self> = RegisterBits::new(0x1); pub const TOV20: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for TIFR2 { type T = u8; const ADDRESS: *mut u8 = 0x37 as *mut u8; } #[allow(non_camel_case_types)] pub struct TCCR2A; impl TCCR2A { pub const COM2A: RegisterBits<Self> = RegisterBits::new(0xc0); pub const COM2A0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const COM2A1: RegisterBits<Self> = RegisterBits::new(1<<7); pub const COM2B: RegisterBits<Self> = RegisterBits::new(0x30); pub const COM2B0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const COM2B1: RegisterBits<Self> = RegisterBits::new(1<<5); pub const WGM2: RegisterBits<Self> = RegisterBits::new(0x3); pub const WGM20: RegisterBits<Self> = RegisterBits::new(1<<0); pub const WGM21: RegisterBits<Self> = RegisterBits::new(1<<1); } impl Register for TCCR2A { type T = u8; const ADDRESS: *mut u8 = 0xb0 as *mut u8; } #[allow(non_camel_case_types)] pub struct TCCR2B; impl TCCR2B { pub const FOC2A: RegisterBits<Self> = RegisterBits::new(0x80); pub const FOC2A0: RegisterBits<Self> = RegisterBits::new(1<<7); pub const FOC2B: RegisterBits<Self> = RegisterBits::new(0x40); pub const FOC2B0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const WGM22: RegisterBits<Self> = RegisterBits::new(0x8); pub const WGM220: RegisterBits<Self> = RegisterBits::new(1<<3); pub const CS2: RegisterBits<Self> = RegisterBits::new(0x7); pub const CS20: RegisterBits<Self> = RegisterBits::new(1<<0); pub const CS21: RegisterBits<Self> = RegisterBits::new(1<<1); pub const CS22: RegisterBits<Self> = RegisterBits::new(1<<2); } impl Register for TCCR2B { type T = u8; const ADDRESS: *mut u8 = 0xb1 as *mut u8; } #[allow(non_camel_case_types)] pub struct TCNT2; impl TCNT2 { } impl Register for TCNT2 { type T = u8; const ADDRESS: *mut u8 = 0xb2 as *mut u8; } #[allow(non_camel_case_types)] pub struct OCR2B; impl OCR2B { } impl Register for OCR2B { type T = u8; const ADDRESS: *mut u8 = 0xb4 as *mut u8; } #[allow(non_camel_case_types)] pub struct OCR2A; impl OCR2A { } impl Register for OCR2A { type T = u8; const ADDRESS: *mut u8 = 0xb3 as *mut u8; } #[allow(non_camel_case_types)] pub struct ASSR; impl ASSR { pub const EXCLK: RegisterBits<Self> = RegisterBits::new(0x40); pub const EXCLK0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const AS2: RegisterBits<Self> = RegisterBits::new(0x20); pub const AS20: RegisterBits<Self> = RegisterBits::new(1<<5); pub const TCN2UB: RegisterBits<Self> = RegisterBits::new(0x10); pub const TCN2UB0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const OCR2AUB: RegisterBits<Self> = RegisterBits::new(0x8); pub const OCR2AUB0: RegisterBits<Self> = RegisterBits::new(1<<3); pub const OCR2BUB: RegisterBits<Self> = RegisterBits::new(0x4); pub const OCR2BUB0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const TCR2AUB: RegisterBits<Self> = RegisterBits::new(0x2); pub const TCR2AUB0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const TCR2BUB: RegisterBits<Self> = RegisterBits::new(0x1); pub const TCR2BUB0: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for ASSR { type T = u8; const ADDRESS: *mut u8 = 0xb6 as *mut u8; } #[allow(non_camel_case_types)] pub struct ADMUX; impl ADMUX { pub const REFS: RegisterBits<Self> = RegisterBits::new(0xc0); pub const REFS0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const REFS1: RegisterBits<Self> = RegisterBits::new(1<<7); pub const ADLAR: RegisterBits<Self> = RegisterBits::new(0x20); pub const ADLAR0: RegisterBits<Self> = RegisterBits::new(1<<5); pub const MUX: RegisterBits<Self> = RegisterBits::new(0xf); pub const MUX0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const MUX1: RegisterBits<Self> = RegisterBits::new(1<<1); pub const MUX2: RegisterBits<Self> = RegisterBits::new(1<<2); pub const MUX3: RegisterBits<Self> = RegisterBits::new(1<<3); } impl Register for ADMUX { type T = u8; const ADDRESS: *mut u8 = 0x7c as *mut u8; } #[allow(non_camel_case_types)] pub struct ADC; impl ADC { } impl Register for ADC { type T = u16; const ADDRESS: *mut u16 = 0x78 as *mut u16; } #[allow(non_camel_case_types)] pub struct ADCSRA; impl ADCSRA { pub const ADEN: RegisterBits<Self> = RegisterBits::new(0x80); pub const ADEN0: RegisterBits<Self> = RegisterBits::new(1<<7); pub const ADSC: RegisterBits<Self> = RegisterBits::new(0x40); pub const ADSC0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const ADATE: RegisterBits<Self> = RegisterBits::new(0x20); pub const ADATE0: RegisterBits<Self> = RegisterBits::new(1<<5); pub const ADIF: RegisterBits<Self> = RegisterBits::new(0x10); pub const ADIF0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const ADIE: RegisterBits<Self> = RegisterBits::new(0x8); pub const ADIE0: RegisterBits<Self> = RegisterBits::new(1<<3); pub const ADPS: RegisterBits<Self> = RegisterBits::new(0x7); pub const ADPS0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const ADPS1: RegisterBits<Self> = RegisterBits::new(1<<1); pub const ADPS2: RegisterBits<Self> = RegisterBits::new(1<<2); } impl Register for ADCSRA { type T = u8; const ADDRESS: *mut u8 = 0x7a as *mut u8; } #[allow(non_camel_case_types)] pub struct ADCSRB; impl ADCSRB { pub const ACME: RegisterBits<Self> = RegisterBits::new(0x40); pub const ACME0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const ADTS: RegisterBits<Self> = RegisterBits::new(0x7); pub const ADTS0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const ADTS1: RegisterBits<Self> = RegisterBits::new(1<<1); pub const ADTS2: RegisterBits<Self> = RegisterBits::new(1<<2); } impl Register for ADCSRB { type T = u8; const ADDRESS: *mut u8 = 0x7b as *mut u8; } #[allow(non_camel_case_types)] pub struct DIDR0; impl DIDR0 { pub const ADC5D: RegisterBits<Self> = RegisterBits::new(0x20); pub const ADC5D0: RegisterBits<Self> = RegisterBits::new(1<<5); pub const ADC4D: RegisterBits<Self> = RegisterBits::new(0x10); pub const ADC4D0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const ADC3D: RegisterBits<Self> = RegisterBits::new(0x8); pub const ADC3D0: RegisterBits<Self> = RegisterBits::new(1<<3); pub const ADC2D: RegisterBits<Self> = RegisterBits::new(0x4); pub const ADC2D0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const ADC1D: RegisterBits<Self> = RegisterBits::new(0x2); pub const ADC1D0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const ADC0D: RegisterBits<Self> = RegisterBits::new(0x1); pub const ADC0D0: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for DIDR0 { type T = u8; const ADDRESS: *mut u8 = 0x7e as *mut u8; } #[allow(non_camel_case_types)] pub struct ACSR; impl ACSR { pub const ACD: RegisterBits<Self> = RegisterBits::new(0x80); pub const ACD0: RegisterBits<Self> = RegisterBits::new(1<<7); pub const ACBG: RegisterBits<Self> = RegisterBits::new(0x40); pub const ACBG0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const ACO: RegisterBits<Self> = RegisterBits::new(0x20); pub const ACO0: RegisterBits<Self> = RegisterBits::new(1<<5); pub const ACI: RegisterBits<Self> = RegisterBits::new(0x10); pub const ACI0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const ACIE: RegisterBits<Self> = RegisterBits::new(0x8); pub const ACIE0: RegisterBits<Self> = RegisterBits::new(1<<3); pub const ACIC: RegisterBits<Self> = RegisterBits::new(0x4); pub const ACIC0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const ACIS: RegisterBits<Self> = RegisterBits::new(0x3); pub const ACIS0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const ACIS1: RegisterBits<Self> = RegisterBits::new(1<<1); } impl Register for ACSR { type T = u8; const ADDRESS: *mut u8 = 0x50 as *mut u8; } #[allow(non_camel_case_types)] pub struct DIDR1; impl DIDR1 { pub const AIN1D: RegisterBits<Self> = RegisterBits::new(0x2); pub const AIN1D0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const AIN0D: RegisterBits<Self> = RegisterBits::new(0x1); pub const AIN0D0: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for DIDR1 { type T = u8; const ADDRESS: *mut u8 = 0x7f as *mut u8; } #[allow(non_camel_case_types)] pub struct PORTB; impl PORTB { } impl Register for PORTB { type T = u8; const ADDRESS: *mut u8 = 0x25 as *mut u8; } #[allow(non_camel_case_types)] pub struct DDRB; impl DDRB { } impl Register for DDRB { type T = u8; const ADDRESS: *mut u8 = 0x24 as *mut u8; } #[allow(non_camel_case_types)] pub struct PINB; impl PINB { } impl Register for PINB { type T = u8; const ADDRESS: *mut u8 = 0x23 as *mut u8; } #[allow(non_camel_case_types)] pub struct PORTC; impl PORTC { } impl Register for PORTC { type T = u8; const ADDRESS: *mut u8 = 0x28 as *mut u8; } #[allow(non_camel_case_types)] pub struct DDRC; impl DDRC { } impl Register for DDRC { type T = u8; const ADDRESS: *mut u8 = 0x27 as *mut u8; } #[allow(non_camel_case_types)] pub struct PINC; impl PINC { } impl Register for PINC { type T = u8; const ADDRESS: *mut u8 = 0x26 as *mut u8; } #[allow(non_camel_case_types)] pub struct PORTD; impl PORTD { } impl Register for PORTD { type T = u8; const ADDRESS: *mut u8 = 0x2b as *mut u8; } #[allow(non_camel_case_types)] pub struct DDRD; impl DDRD { } impl Register for DDRD { type T = u8; const ADDRESS: *mut u8 = 0x2a as *mut u8; } #[allow(non_camel_case_types)] pub struct PIND; impl PIND { } impl Register for PIND { type T = u8; const ADDRESS: *mut u8 = 0x29 as *mut u8; } #[allow(non_camel_case_types)] pub struct OCR0B; impl OCR0B { } impl Register for OCR0B { type T = u8; const ADDRESS: *mut u8 = 0x48 as *mut u8; } #[allow(non_camel_case_types)] pub struct OCR0A; impl OCR0A { } impl Register for OCR0A { type T = u8; const ADDRESS: *mut u8 = 0x47 as *mut u8; } #[allow(non_camel_case_types)] pub struct TCNT0; impl TCNT0 { } impl Register for TCNT0 { type T = u8; const ADDRESS: *mut u8 = 0x46 as *mut u8; } #[allow(non_camel_case_types)] pub struct TCCR0B; impl TCCR0B { pub const FOC0A: RegisterBits<Self> = RegisterBits::new(0x80); pub const FOC0A0: RegisterBits<Self> = RegisterBits::new(1<<7); pub const FOC0B: RegisterBits<Self> = RegisterBits::new(0x40); pub const FOC0B0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const WGM02: RegisterBits<Self> = RegisterBits::new(0x8); pub const WGM020: RegisterBits<Self> = RegisterBits::new(1<<3); pub const CS0: RegisterBits<Self> = RegisterBits::new(0x7); pub const CS00: RegisterBits<Self> = RegisterBits::new(1<<0); pub const CS01: RegisterBits<Self> = RegisterBits::new(1<<1); pub const CS02: RegisterBits<Self> = RegisterBits::new(1<<2); } impl Register for TCCR0B { type T = u8; const ADDRESS: *mut u8 = 0x45 as *mut u8; } #[allow(non_camel_case_types)] pub struct TCCR0A; impl TCCR0A { pub const COM0A: RegisterBits<Self> = RegisterBits::new(0xc0); pub const COM0A0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const COM0A1: RegisterBits<Self> = RegisterBits::new(1<<7); pub const COM0B: RegisterBits<Self> = RegisterBits::new(0x30); pub const COM0B0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const COM0B1: RegisterBits<Self> = RegisterBits::new(1<<5); pub const WGM0: RegisterBits<Self> = RegisterBits::new(0x3); pub const WGM00: RegisterBits<Self> = RegisterBits::new(1<<0); pub const WGM01: RegisterBits<Self> = RegisterBits::new(1<<1); } impl Register for TCCR0A { type T = u8; const ADDRESS: *mut u8 = 0x44 as *mut u8; } #[allow(non_camel_case_types)] pub struct TIMSK0; impl TIMSK0 { pub const OCIE0B: RegisterBits<Self> = RegisterBits::new(0x4); pub const OCIE0B0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const OCIE0A: RegisterBits<Self> = RegisterBits::new(0x2); pub const OCIE0A0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const TOIE0: RegisterBits<Self> = RegisterBits::new(0x1); pub const TOIE00: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for TIMSK0 { type T = u8; const ADDRESS: *mut u8 = 0x6e as *mut u8; } #[allow(non_camel_case_types)] pub struct TIFR0; impl TIFR0 { pub const OCF0B: RegisterBits<Self> = RegisterBits::new(0x4); pub const OCF0B0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const OCF0A: RegisterBits<Self> = RegisterBits::new(0x2); pub const OCF0A0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const TOV0: RegisterBits<Self> = RegisterBits::new(0x1); pub const TOV00: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for TIFR0 { type T = u8; const ADDRESS: *mut u8 = 0x35 as *mut u8; } #[allow(non_camel_case_types)] pub struct EICRA; impl EICRA { pub const ISC1: RegisterBits<Self> = RegisterBits::new(0xc); pub const ISC10: RegisterBits<Self> = RegisterBits::new(1<<2); pub const ISC11: RegisterBits<Self> = RegisterBits::new(1<<3); pub const ISC0: RegisterBits<Self> = RegisterBits::new(0x3); pub const ISC00: RegisterBits<Self> = RegisterBits::new(1<<0); pub const ISC01: RegisterBits<Self> = RegisterBits::new(1<<1); } impl Register for EICRA { type T = u8; const ADDRESS: *mut u8 = 0x69 as *mut u8; } #[allow(non_camel_case_types)] pub struct EIMSK; impl EIMSK { pub const INT: RegisterBits<Self> = RegisterBits::new(0x3); pub const INT0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const INT1: RegisterBits<Self> = RegisterBits::new(1<<1); } impl Register for EIMSK { type T = u8; const ADDRESS: *mut u8 = 0x3d as *mut u8; } #[allow(non_camel_case_types)] pub struct EIFR; impl EIFR { pub const INTF: RegisterBits<Self> = RegisterBits::new(0x3); pub const INTF0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const INTF1: RegisterBits<Self> = RegisterBits::new(1<<1); } impl Register for EIFR { type T = u8; const ADDRESS: *mut u8 = 0x3c as *mut u8; } #[allow(non_camel_case_types)] pub struct PCICR; impl PCICR { pub const PCIE: RegisterBits<Self> = RegisterBits::new(0x7); pub const PCIE0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const PCIE1: RegisterBits<Self> = RegisterBits::new(1<<1); pub const PCIE2: RegisterBits<Self> = RegisterBits::new(1<<2); } impl Register for PCICR { type T = u8; const ADDRESS: *mut u8 = 0x68 as *mut u8; } #[allow(non_camel_case_types)] pub struct PCMSK2; impl PCMSK2 { pub const PCINT: RegisterBits<Self> = RegisterBits::new(0xff); pub const PCINT0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const PCINT1: RegisterBits<Self> = RegisterBits::new(1<<1); pub const PCINT2: RegisterBits<Self> = RegisterBits::new(1<<2); pub const PCINT3: RegisterBits<Self> = RegisterBits::new(1<<3); pub const PCINT4: RegisterBits<Self> = RegisterBits::new(1<<4); pub const PCINT5: RegisterBits<Self> = RegisterBits::new(1<<5); pub const PCINT6: RegisterBits<Self> = RegisterBits::new(1<<6); pub const PCINT7: RegisterBits<Self> = RegisterBits::new(1<<7); } impl Register for PCMSK2 { type T = u8; const ADDRESS: *mut u8 = 0x6d as *mut u8; } #[allow(non_camel_case_types)] pub struct PCMSK1; impl PCMSK1 { pub const PCINT: RegisterBits<Self> = RegisterBits::new(0x7f); pub const PCINT0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const PCINT1: RegisterBits<Self> = RegisterBits::new(1<<1); pub const PCINT2: RegisterBits<Self> = RegisterBits::new(1<<2); pub const PCINT3: RegisterBits<Self> = RegisterBits::new(1<<3); pub const PCINT4: RegisterBits<Self> = RegisterBits::new(1<<4); pub const PCINT5: RegisterBits<Self> = RegisterBits::new(1<<5); pub const PCINT6: RegisterBits<Self> = RegisterBits::new(1<<6); } impl Register for PCMSK1 { type T = u8; const ADDRESS: *mut u8 = 0x6c as *mut u8; } #[allow(non_camel_case_types)] pub struct PCMSK0; impl PCMSK0 { pub const PCINT: RegisterBits<Self> = RegisterBits::new(0xff); pub const PCINT0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const PCINT1: RegisterBits<Self> = RegisterBits::new(1<<1); pub const PCINT2: RegisterBits<Self> = RegisterBits::new(1<<2); pub const PCINT3: RegisterBits<Self> = RegisterBits::new(1<<3); pub const PCINT4: RegisterBits<Self> = RegisterBits::new(1<<4); pub const PCINT5: RegisterBits<Self> = RegisterBits::new(1<<5); pub const PCINT6: RegisterBits<Self> = RegisterBits::new(1<<6); pub const PCINT7: RegisterBits<Self> = RegisterBits::new(1<<7); } impl Register for PCMSK0 { type T = u8; const ADDRESS: *mut u8 = 0x6b as *mut u8; } #[allow(non_camel_case_types)] pub struct PCIFR; impl PCIFR { pub const PCIF: RegisterBits<Self> = RegisterBits::new(0x7); pub const PCIF0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const PCIF1: RegisterBits<Self> = RegisterBits::new(1<<1); pub const PCIF2: RegisterBits<Self> = RegisterBits::new(1<<2); } impl Register for PCIFR { type T = u8; const ADDRESS: *mut u8 = 0x3b as *mut u8; } #[allow(non_camel_case_types)] pub struct SPDR; impl SPDR { } impl Register for SPDR { type T = u8; const ADDRESS: *mut u8 = 0x4e as *mut u8; } #[allow(non_camel_case_types)] pub struct SPSR; impl SPSR { pub const SPIF: RegisterBits<Self> = RegisterBits::new(0x80); pub const SPIF0: RegisterBits<Self> = RegisterBits::new(1<<7); pub const WCOL: RegisterBits<Self> = RegisterBits::new(0x40); pub const WCOL0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const SPI2X: RegisterBits<Self> = RegisterBits::new(0x1); pub const SPI2X0: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for SPSR { type T = u8; const ADDRESS: *mut u8 = 0x4d as *mut u8; } #[allow(non_camel_case_types)] pub struct SPCR; impl SPCR { pub const SPIE: RegisterBits<Self> = RegisterBits::new(0x80); pub const SPIE0: RegisterBits<Self> = RegisterBits::new(1<<7); pub const SPE: RegisterBits<Self> = RegisterBits::new(0x40); pub const SPE0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const DORD: RegisterBits<Self> = RegisterBits::new(0x20); pub const DORD0: RegisterBits<Self> = RegisterBits::new(1<<5); pub const MSTR: RegisterBits<Self> = RegisterBits::new(0x10); pub const MSTR0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const CPOL: RegisterBits<Self> = RegisterBits::new(0x8); pub const CPOL0: RegisterBits<Self> = RegisterBits::new(1<<3); pub const CPHA: RegisterBits<Self> = RegisterBits::new(0x4); pub const CPHA0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const SPR: RegisterBits<Self> = RegisterBits::new(0x3); pub const SPR0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const SPR1: RegisterBits<Self> = RegisterBits::new(1<<1); } impl Register for SPCR { type T = u8; const ADDRESS: *mut u8 = 0x4c as *mut u8; } #[allow(non_camel_case_types)] pub struct WDTCSR; impl WDTCSR { pub const WDIF: RegisterBits<Self> = RegisterBits::new(0x80); pub const WDIF0: RegisterBits<Self> = RegisterBits::new(1<<7); pub const WDIE: RegisterBits<Self> = RegisterBits::new(0x40); pub const WDIE0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const WDP: RegisterBits<Self> = RegisterBits::new(0x27); pub const WDP0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const WDP1: RegisterBits<Self> = RegisterBits::new(1<<1); pub const WDP2: RegisterBits<Self> = RegisterBits::new(1<<2); pub const WDP3: RegisterBits<Self> = RegisterBits::new(1<<5); pub const WDCE: RegisterBits<Self> = RegisterBits::new(0x10); pub const WDCE0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const WDE: RegisterBits<Self> = RegisterBits::new(0x8); pub const WDE0: RegisterBits<Self> = RegisterBits::new(1<<3); } impl Register for WDTCSR { type T = u8; const ADDRESS: *mut u8 = 0x60 as *mut u8; } #[allow(non_camel_case_types)] pub struct EEAR; impl EEAR { } impl Register for EEAR { type T = u16; const ADDRESS: *mut u16 = 0x41 as *mut u16; } #[allow(non_camel_case_types)] pub struct EEDR; impl EEDR { } impl Register for EEDR { type T = u8; const ADDRESS: *mut u8 = 0x40 as *mut u8; } #[allow(non_camel_case_types)] pub struct EECR; impl EECR { pub const EEPM: RegisterBits<Self> = RegisterBits::new(0x30); pub const EEPM0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const EEPM1: RegisterBits<Self> = RegisterBits::new(1<<5); pub const EERIE: RegisterBits<Self> = RegisterBits::new(0x8); pub const EERIE0: RegisterBits<Self> = RegisterBits::new(1<<3); pub const EEMPE: RegisterBits<Self> = RegisterBits::new(0x4); pub const EEMPE0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const EEPE: RegisterBits<Self> = RegisterBits::new(0x2); pub const EEPE0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const EERE: RegisterBits<Self> = RegisterBits::new(0x1); pub const EERE0: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for EECR { type T = u8; const ADDRESS: *mut u8 = 0x3f as *mut u8; } #[allow(non_camel_case_types)] pub struct PRR; impl PRR { pub const PRTWI: RegisterBits<Self> = RegisterBits::new(0x80); pub const PRTWI0: RegisterBits<Self> = RegisterBits::new(1<<7); pub const PRTIM2: RegisterBits<Self> = RegisterBits::new(0x40); pub const PRTIM20: RegisterBits<Self> = RegisterBits::new(1<<6); pub const PRTIM0: RegisterBits<Self> = RegisterBits::new(0x20); pub const PRTIM00: RegisterBits<Self> = RegisterBits::new(1<<5); pub const PRTIM1: RegisterBits<Self> = RegisterBits::new(0x8); pub const PRTIM10: RegisterBits<Self> = RegisterBits::new(1<<3); pub const PRSPI: RegisterBits<Self> = RegisterBits::new(0x4); pub const PRSPI0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const PRUSART0: RegisterBits<Self> = RegisterBits::new(0x2); pub const PRUSART00: RegisterBits<Self> = RegisterBits::new(1<<1); pub const PRADC: RegisterBits<Self> = RegisterBits::new(0x1); pub const PRADC0: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for PRR { type T = u8; const ADDRESS: *mut u8 = 0x64 as *mut u8; } #[allow(non_camel_case_types)] pub struct OSCCAL; impl OSCCAL { pub const OSCCAL: RegisterBits<Self> = RegisterBits::new(0xff); pub const OSCCAL0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const OSCCAL1: RegisterBits<Self> = RegisterBits::new(1<<1); pub const OSCCAL2: RegisterBits<Self> = RegisterBits::new(1<<2); pub const OSCCAL3: RegisterBits<Self> = RegisterBits::new(1<<3); pub const OSCCAL4: RegisterBits<Self> = RegisterBits::new(1<<4); pub const OSCCAL5: RegisterBits<Self> = RegisterBits::new(1<<5); pub const OSCCAL6: RegisterBits<Self> = RegisterBits::new(1<<6); pub const OSCCAL7: RegisterBits<Self> = RegisterBits::new(1<<7); } impl Register for OSCCAL { type T = u8; const ADDRESS: *mut u8 = 0x66 as *mut u8; } #[allow(non_camel_case_types)] pub struct CLKPR; impl CLKPR { pub const CLKPCE: RegisterBits<Self> = RegisterBits::new(0x80); pub const CLKPCE0: RegisterBits<Self> = RegisterBits::new(1<<7); pub const CLKPS: RegisterBits<Self> = RegisterBits::new(0xf); pub const CLKPS0: RegisterBits<Self> = RegisterBits::new(1<<0); pub const CLKPS1: RegisterBits<Self> = RegisterBits::new(1<<1); pub const CLKPS2: RegisterBits<Self> = RegisterBits::new(1<<2); pub const CLKPS3: RegisterBits<Self> = RegisterBits::new(1<<3); } impl Register for CLKPR { type T = u8; const ADDRESS: *mut u8 = 0x61 as *mut u8; } #[allow(non_camel_case_types)] pub struct SREG; impl SREG { pub const I: RegisterBits<Self> = RegisterBits::new(0x80); pub const I0: RegisterBits<Self> = RegisterBits::new(1<<7); pub const T: RegisterBits<Self> = RegisterBits::new(0x40); pub const T0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const H: RegisterBits<Self> = RegisterBits::new(0x20); pub const H0: RegisterBits<Self> = RegisterBits::new(1<<5); pub const S: RegisterBits<Self> = RegisterBits::new(0x10); pub const S0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const V: RegisterBits<Self> = RegisterBits::new(0x8); pub const V0: RegisterBits<Self> = RegisterBits::new(1<<3); pub const N: RegisterBits<Self> = RegisterBits::new(0x4); pub const N0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const Z: RegisterBits<Self> = RegisterBits::new(0x2); pub const Z0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const C: RegisterBits<Self> = RegisterBits::new(0x1); pub const C0: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for SREG { type T = u8; const ADDRESS: *mut u8 = 0x5f as *mut u8; } #[allow(non_camel_case_types)] pub struct SP; impl SP { } impl Register for SP { type T = u16; const ADDRESS: *mut u16 = 0x5d as *mut u16; } #[allow(non_camel_case_types)] pub struct SPMCSR; impl SPMCSR { pub const SPMIE: RegisterBits<Self> = RegisterBits::new(0x80); pub const SPMIE0: RegisterBits<Self> = RegisterBits::new(1<<7); pub const RWWSB: RegisterBits<Self> = RegisterBits::new(0x40); pub const RWWSB0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const SIGRD: RegisterBits<Self> = RegisterBits::new(0x20); pub const SIGRD0: RegisterBits<Self> = RegisterBits::new(1<<5); pub const RWWSRE: RegisterBits<Self> = RegisterBits::new(0x10); pub const RWWSRE0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const BLBSET: RegisterBits<Self> = RegisterBits::new(0x8); pub const BLBSET0: RegisterBits<Self> = RegisterBits::new(1<<3); pub const PGWRT: RegisterBits<Self> = RegisterBits::new(0x4); pub const PGWRT0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const PGERS: RegisterBits<Self> = RegisterBits::new(0x2); pub const PGERS0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const SPMEN: RegisterBits<Self> = RegisterBits::new(0x1); pub const SPMEN0: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for SPMCSR { type T = u8; const ADDRESS: *mut u8 = 0x57 as *mut u8; } #[allow(non_camel_case_types)] pub struct MCUCR; impl MCUCR { pub const BODS: RegisterBits<Self> = RegisterBits::new(0x40); pub const BODS0: RegisterBits<Self> = RegisterBits::new(1<<6); pub const BODSE: RegisterBits<Self> = RegisterBits::new(0x20); pub const BODSE0: RegisterBits<Self> = RegisterBits::new(1<<5); pub const PUD: RegisterBits<Self> = RegisterBits::new(0x10); pub const PUD0: RegisterBits<Self> = RegisterBits::new(1<<4); pub const IVSEL: RegisterBits<Self> = RegisterBits::new(0x2); pub const IVSEL0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const IVCE: RegisterBits<Self> = RegisterBits::new(0x1); pub const IVCE0: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for MCUCR { type T = u8; const ADDRESS: *mut u8 = 0x55 as *mut u8; } #[allow(non_camel_case_types)] pub struct MCUSR; impl MCUSR { pub const WDRF: RegisterBits<Self> = RegisterBits::new(0x8); pub const WDRF0: RegisterBits<Self> = RegisterBits::new(1<<3); pub const BORF: RegisterBits<Self> = RegisterBits::new(0x4); pub const BORF0: RegisterBits<Self> = RegisterBits::new(1<<2); pub const EXTRF: RegisterBits<Self> = RegisterBits::new(0x2); pub const EXTRF0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const PORF: RegisterBits<Self> = RegisterBits::new(0x1); pub const PORF0: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for MCUSR { type T = u8; const ADDRESS: *mut u8 = 0x54 as *mut u8; } #[allow(non_camel_case_types)] pub struct SMCR; impl SMCR { pub const SM: RegisterBits<Self> = RegisterBits::new(0xe); pub const SM0: RegisterBits<Self> = RegisterBits::new(1<<1); pub const SM1: RegisterBits<Self> = RegisterBits::new(1<<2); pub const SM2: RegisterBits<Self> = RegisterBits::new(1<<3); pub const SE: RegisterBits<Self> = RegisterBits::new(0x1); pub const SE0: RegisterBits<Self> = RegisterBits::new(1<<0); } impl Register for SMCR { type T = u8; const ADDRESS: *mut u8 = 0x53 as *mut u8; } #[allow(non_camel_case_types)] pub struct GPIOR2; impl GPIOR2 { } impl Register for GPIOR2 { type T = u8; const ADDRESS: *mut u8 = 0x4b as *mut u8; } #[allow(non_camel_case_types)] pub struct GPIOR1; impl GPIOR1 { } impl Register for GPIOR1 { type T = u8; const ADDRESS: *mut u8 = 0x4a as *mut u8; } #[allow(non_camel_case_types)] pub struct GPIOR0; impl GPIOR0 { } impl Register for GPIOR0 { type T = u8; const ADDRESS: *mut u8 = 0x3e as *mut u8; } pub mod port { #![allow(unused_imports)] use super::*; use crate::Pin; pub struct B0; impl Pin for B0 { /// Port B Data Register. type PORT = PORTB; /// Port B Data Direction Register. type DDR = DDRB; /// Port B Input Pins. type PIN = PINB; /// PB0 const MASK: u8 = 1<<0; } pub struct B1; impl Pin for B1 { /// Port B Data Register. type PORT = PORTB; /// Port B Data Direction Register. type DDR = DDRB; /// Port B Input Pins. type PIN = PINB; /// PB1 const MASK: u8 = 1<<1; } pub struct B2; impl Pin for B2 { /// Port B Data Register. type PORT = PORTB; /// Port B Data Direction Register. type DDR = DDRB; /// Port B Input Pins. type PIN = PINB; /// PB2 const MASK: u8 = 1<<2; } pub struct B3; impl Pin for B3 { /// Port B Data Register. type PORT = PORTB; /// Port B Data Direction Register. type DDR = DDRB; /// Port B Input Pins. type PIN = PINB; /// PB3 const MASK: u8 = 1<<3; } pub struct B4; impl Pin for B4 { /// Port B Data Register. type PORT = PORTB; /// Port B Data Direction Register. type DDR = DDRB; /// Port B Input Pins. type PIN = PINB; /// PB4 const MASK: u8 = 1<<4; } pub struct B5; impl Pin for B5 { /// Port B Data Register. type PORT = PORTB; /// Port B Data Direction Register. type DDR = DDRB; /// Port B Input Pins. type PIN = PINB; /// PB5 const MASK: u8 = 1<<5; } pub struct B6; impl Pin for B6 { /// Port B Data Register. type PORT = PORTB; /// Port B Data Direction Register. type DDR = DDRB; /// Port B Input Pins. type PIN = PINB; /// PB6 const MASK: u8 = 1<<6; } pub struct B7; impl Pin for B7 { /// Port B Data Register. type PORT = PORTB; /// Port B Data Direction Register. type DDR = DDRB; /// Port B Input Pins. type PIN = PINB; /// PB7 const MASK: u8 = 1<<7; } pub struct C0; impl Pin for C0 { /// Port C Data Register. type PORT = PORTC; /// Port C Data Direction Register. type DDR = DDRC; /// Port C Input Pins. type PIN = PINC; /// PC0 const MASK: u8 = 1<<0; } pub struct C1; impl Pin for C1 { /// Port C Data Register. type PORT = PORTC; /// Port C Data Direction Register. type DDR = DDRC; /// Port C Input Pins. type PIN = PINC; /// PC1 const MASK: u8 = 1<<1; } pub struct C2; impl Pin for C2 { /// Port C Data Register. type PORT = PORTC; /// Port C Data Direction Register. type DDR = DDRC; /// Port C Input Pins. type PIN = PINC; /// PC2 const MASK: u8 = 1<<2; } pub struct C3; impl Pin for C3 { /// Port C Data Register. type PORT = PORTC; /// Port C Data Direction Register. type DDR = DDRC; /// Port C Input Pins. type PIN = PINC; /// PC3 const MASK: u8 = 1<<3; } pub struct C4; impl Pin for C4 { /// Port C Data Register. type PORT = PORTC; /// Port C Data Direction Register. type DDR = DDRC; /// Port C Input Pins. type PIN = PINC; /// PC4 const MASK: u8 = 1<<4; } pub struct C5; impl Pin for C5 { /// Port C Data Register. type PORT = PORTC; /// Port C Data Direction Register. type DDR = DDRC; /// Port C Input Pins. type PIN = PINC; /// PC5 const MASK: u8 = 1<<5; } pub struct C6; impl Pin for C6 { /// Port C Data Register. type PORT = PORTC; /// Port C Data Direction Register. type DDR = DDRC; /// Port C Input Pins. type PIN = PINC; /// PC6 const MASK: u8 = 1<<6; } pub struct D0; impl Pin for D0 { /// Port D Data Register. type PORT = PORTD; /// Port D Data Direction Register. type DDR = DDRD; /// Port D Input Pins. type PIN = PIND; /// PD0 const MASK: u8 = 1<<0; } pub struct D1; impl Pin for D1 { /// Port D Data Register. type PORT = PORTD; /// Port D Data Direction Register. type DDR = DDRD; /// Port D Input Pins. type PIN = PIND; /// PD1 const MASK: u8 = 1<<1; } pub struct D2; impl Pin for D2 { /// Port D Data Register. type PORT = PORTD; /// Port D Data Direction Register. type DDR = DDRD; /// Port D Input Pins. type PIN = PIND; /// PD2 const MASK: u8 = 1<<2; } pub struct D3; impl Pin for D3 { /// Port D Data Register. type PORT = PORTD; /// Port D Data Direction Register. type DDR = DDRD; /// Port D Input Pins. type PIN = PIND; /// PD3 const MASK: u8 = 1<<3; } pub struct D4; impl Pin for D4 { /// Port D Data Register. type PORT = PORTD; /// Port D Data Direction Register. type DDR = DDRD; /// Port D Input Pins. type PIN = PIND; /// PD4 const MASK: u8 = 1<<4; } pub struct D5; impl Pin for D5 { /// Port D Data Register. type PORT = PORTD; /// Port D Data Direction Register. type DDR = DDRD; /// Port D Input Pins. type PIN = PIND; /// PD5 const MASK: u8 = 1<<5; } pub struct D6; impl Pin for D6 { /// Port D Data Register. type PORT = PORTD; /// Port D Data Direction Register. type DDR = DDRD; /// Port D Input Pins. type PIN = PIND; /// PD6 const MASK: u8 = 1<<6; } pub struct D7; impl Pin for D7 { /// Port D Data Register. type PORT = PORTD; /// Port D Data Direction Register. type DDR = DDRD; /// Port D Input Pins. type PIN = PIND; /// PD7 const MASK: u8 = 1<<7; } } pub struct Spi; impl modules::HardwareSpi for Spi { type SlaveSelect = port::B2; type MasterOutSlaveIn = port::B3; type MasterInSlaveOut = port::B4; type Clock = port::B5; type DataRegister = SPDR; type StatusRegister = SPSR; type ControlRegister = SPCR; } /// The USART0 module. pub struct USART0; impl modules::HardwareUsart for USART0 { type DataRegister = UDR0; type ControlRegisterA = UCSR0A; type ControlRegisterB = UCSR0B; type ControlRegisterC = UCSR0C; type BaudRateRegister = UBRR0; } /// 8-bit timer. pub struct Timer8; impl modules::Timer8 for Timer8 { type CompareA = OCR0A; type CompareB = OCR0B; type Counter = TCNT0; type ControlA = TCCR0A; type ControlB = TCCR0B; type InterruptMask = TIMSK0; type InterruptFlag = TIFR0; const CS0: RegisterBits<Self::ControlB> = Self::ControlB::CS00; const CS1: RegisterBits<Self::ControlB> = Self::ControlB::CS01; const CS2: RegisterBits<Self::ControlB> = Self::ControlB::CS02; const WGM0: RegisterBits<Self::ControlA> = Self::ControlA::WGM00; const WGM1: RegisterBits<Self::ControlA> = Self::ControlA::WGM01; const WGM2: RegisterBits<Self::ControlB> = Self::ControlB::WGM020; const OCIEA: RegisterBits<Self::InterruptMask> = Self::InterruptMask::OCIE0A; } /// 16-bit timer. pub struct Timer16; impl modules::Timer16 for Timer16 { type CompareA = OCR1A; type CompareB = OCR1B; type Counter = TCNT1; type ControlA = TCCR1A; type ControlB = TCCR1B; type ControlC = TCCR1C; type InterruptMask = TIMSK1; type InterruptFlag = TIFR1; const CS0: RegisterBits<Self::ControlB> = Self::ControlB::CS10; const CS1: RegisterBits<Self::ControlB> = Self::ControlB::CS11; const CS2: RegisterBits<Self::ControlB> = Self::ControlB::CS12; const WGM0: RegisterBits<Self::ControlA> = Self::ControlA::WGM10; const WGM1: RegisterBits<Self::ControlA> = Self::ControlA::WGM11; const WGM2: RegisterBits<Self::ControlB> = Self::ControlB::WGM10; const WGM3: RegisterBits<Self::ControlB> = Self::ControlB::WGM11; const OCIEA: RegisterBits<Self::InterruptMask> = Self::InterruptMask::OCIE1A; }
enum Sentence { Hello(u32), Nice, Goodbye { Person: String }, } fn manage(person: &Sentence) { match *person { Sentence::Hello(n) => { for _ in 0..n { println!("Hello"); } } Sentence::Nice => { println!("Nice to meet you"); } Sentence::Goodbye { Person: ref person } => { println!("say goodbye to {}", person); } } } fn main() { let p_vec = vec![Sentence::Hello(2), Sentence::Nice, Sentence::Goodbye { Person: "p_1".to_string() }]; for index in 0..3 { manage(&p_vec[index]); } }
use crate::prelude::*; pub struct Edges<'a, N, E> { edges: &'a generational_arena::Arena<Edge<N, E>>, direction: Direction, next: Next<N, E>, } impl<'a, N, E> Edges<'a, N, E> { pub(crate) fn new( direction: Direction, next: Next<N, E>, edges: &'a generational_arena::Arena<Edge<N, E>>, ) -> Self { Self { direction, next, edges, } } } impl<'a, N, E> Iterator for Edges<'a, N, E> { type Item = N; fn size_hint(&self) -> (usize, Option<usize>) { (self.edges.len(), None) } fn next(&mut self) -> Option<Self::Item> { todo!() } }
#[cfg(test)] mod tests { use pygmaea::ast::*; use pygmaea::lexer::Lexer; use pygmaea::parser::Parser; fn setup_let_statement_input() -> Vec<String> { vec![ " let x = 5;", "let y = 10;", "let foobar = 838383; ", ] .into_iter() .map(str::to_string) .collect() } fn setup_let_statement_expects() -> Vec<String> { vec!["x", "y", "foobar"] .into_iter() .map(str::to_string) .collect() } #[test] fn test_let_statement() { let inputs = setup_let_statement_input(); let expects = setup_let_statement_expects(); inputs .into_iter() .zip(expects.into_iter()) .enumerate() .for_each(|(i, (input, expect))| { let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let program = parser.parse_program(); check_parser_errors(&parser, i); assert_eq!( 1, program.len(), "[{}] program does not contains 1 statements. got={}", i, program.len() ); assert_let_statement(program.get(0).unwrap(), expect, i); }); } fn assert_let_statement(statement: &Statement, expect_name: String, i: usize) { let let_statement = match statement { Statement::Let(ref statement) => statement, other_statement => panic!( "[{}] statement not ReturnStatement. got={}", i, other_statement ), }; assert_eq!( "let".to_string(), let_statement.token_literal(), "[{}] statement.token_literal not 'let'. got={}", i, let_statement.token_literal() ); assert_eq!( expect_name, let_statement.identifier.value, "[{}] let_statement.name.value not '{}'. got={}", i, expect_name, let_statement.identifier.value ); assert_eq!( expect_name, let_statement.identifier.token_literal(), "[{}] let_statement.name.token_literal not '{}'. got={}", i, expect_name, let_statement.identifier.token_literal() ); } fn setup_return_statement_input() -> String { " return 5; return 10; return 993322; " .to_string() } #[test] fn test_return_statement() { let inputs = vec![setup_return_statement_input()]; inputs.into_iter().enumerate().for_each(|(i, input)| { let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let program = parser.parse_program(); check_parser_errors(&parser, i); assert_eq!( 3, program.len(), "[{}] program does not contain 3 statements. got={}", i, program.len() ); program.iter().for_each(|statement| { let return_statement = match statement { Statement::Return(statement) => statement, other_statement => panic!( "[{}] statement not ReturnStatement. got={}", i, other_statement ), }; assert_eq!( "return", return_statement.token_literal(), "[{}] statement.token_literal not 'return'. got={}", i, return_statement.token_literal() ); }); }); } #[test] fn test_identifier_expression() { let inputs = vec!["foobar;".to_string()]; inputs.into_iter().enumerate().for_each(|(i, input)| { let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let program = parser.parse_program(); check_parser_errors(&parser, i); assert_eq!( 1, program.len(), "[{}] program has not enough etatements. got={}", i, program.len() ); let expression_statement = match program.get(0) { Some(Statement::Expression(statement)) => statement, _ => panic!( "[{}] program statement is not ExpressionStatement. got={}", i, program.get(0).unwrap() ), }; let identifier = match *expression_statement.expression { Expression::Identifier(ref identifier) => identifier, _ => panic!( "[{}] expression not Identifier. got={}", i, expression_statement ), }; assert_eq!( "foobar", identifier.value, "[{}] identifier value not {}. got={}", i, "foobar", identifier.value ); assert_eq!( "foobar", identifier.token_literal(), "[{}] identifier token_literal() not {}. got={}", i, "foobar", identifier.token_literal() ); }); } #[test] fn test_integer_literal_expression() { let inputs = vec!["5;".to_string()]; inputs.into_iter().enumerate().for_each(|(i, input)| { let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let program = parser.parse_program(); check_parser_errors(&parser, i); assert_eq!( 1, program.len(), "[{}] program has not enough statements. got={}", i, program.len() ); let expression_statement = match program.get(0) { Some(Statement::Expression(statement)) => statement, _ => panic!( "[{}] program statements is not ExpressionStatement. got={}", i, program.get(0).unwrap() ), }; let integer_literal = match *expression_statement.expression { Expression::Integer(ref literal) => literal, _ => panic!( "[{}] expression not IntegerLiteral. got={}", i, expression_statement.expression ), }; assert_eq!( 5, integer_literal.value, "[{}] literal value not 5. got={}", i, integer_literal.value ); assert_eq!( "5".to_string(), integer_literal.token_literal(), "[{}] literal token_literal not '5'. got={}", i, integer_literal.token_literal() ); }); } fn setup_parsing_prefix_expression_input() -> Vec<String> { vec!["!5", "-15", "!true", "!false"] .into_iter() .map(str::to_string) .collect() } fn setup_parsing_prefix_expression_expect() -> Vec<(String, Concrete)> { vec![ ("!", Concrete::Integer(5)), ("-", Concrete::Integer(15)), ("!", Concrete::Boolean(true)), ("!", Concrete::Boolean(false)), ] .into_iter() .map(|(prefix, value)| (prefix.to_string(), value)) .collect() } #[test] fn test_parsing_prefix_expression() { let inputs = setup_parsing_prefix_expression_input(); let expects = setup_parsing_prefix_expression_expect(); inputs .into_iter() .zip(expects.into_iter()) .enumerate() .for_each(|(i, (input, expect))| { let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let program = parser.parse_program(); check_parser_errors(&parser, i); assert_eq!( 1, program.len(), "[{}] program statements does not contain 1 statements. got={}", i, program.len() ); let expression_statement = match program.get(0) { Some(Statement::Expression(statement)) => statement, _ => panic!( "[{}] program statements is not ExpressionStatement. got={}", i, program.get(0).unwrap() ), }; let prefix_expression = match *expression_statement.expression { Expression::Prefix(ref expression) => expression, _ => panic!( "[{}] expression is not PrefixExpression. got={}", i, expression_statement.expression ), }; assert_eq!( expect.0, prefix_expression.operator, "[{}] expression operator is not {}. got={}", i, expect.0, prefix_expression.operator ); expect .1 .assert_literal_expression(&prefix_expression.right, i); }); } fn setup_parsing_infix_expression_input() -> Vec<String> { vec![ "5 + 5;", "5 - 5;", "5 * 5;", "5 / 5;", "5 > 5;", "5 < 5;", "5 == 5;", "5 != 5;", "true == true", "true != false", "false == false", ] .into_iter() .map(str::to_string) .collect() } fn setup_parsing_infix_expression_expect() -> Vec<(Concrete, String, Concrete)> { vec![ (Concrete::Integer(5), "+", Concrete::Integer(5)), (Concrete::Integer(5), "-", Concrete::Integer(5)), (Concrete::Integer(5), "*", Concrete::Integer(5)), (Concrete::Integer(5), "/", Concrete::Integer(5)), (Concrete::Integer(5), ">", Concrete::Integer(5)), (Concrete::Integer(5), "<", Concrete::Integer(5)), (Concrete::Integer(5), "==", Concrete::Integer(5)), (Concrete::Integer(5), "!=", Concrete::Integer(5)), (Concrete::Boolean(true), "==", Concrete::Boolean(true)), (Concrete::Boolean(true), "!=", Concrete::Boolean(false)), (Concrete::Boolean(false), "==", Concrete::Boolean(false)), ] .into_iter() .map(|(left, op, right)| (left, op.to_string(), right)) .collect() } #[test] fn test_parsing_infix_expression() { let inputs = setup_parsing_infix_expression_input(); let expects = setup_parsing_infix_expression_expect(); assert_eq!( inputs.len(), expects.len(), "inputs.len and expects.len is mismatch" ); inputs .into_iter() .zip(expects.into_iter()) .enumerate() .for_each(|(i, (input, expect))| { let mut parser = Parser::new(Lexer::new(input)); let program = parser.parse_program(); check_parser_errors(&parser, i); assert_eq!( 1, program.len(), "[{}] program statements does not contain 1 statements. got={}", i, program.len() ); let expression_statement = match program.get(0) { Some(Statement::Expression(statement)) => statement, _ => panic!("[{}] program statement is not ExpressionStatement.", i), }; assert_infix_expression( &expression_statement.expression, expect.0, expect.1, expect.2, i, ); }); } fn assert_infix_expression( expression: &Expression, left: impl Wrapped, operator: String, right: impl Wrapped, i: usize, ) { let infix_expression = match expression { Expression::Infix(expression) => expression, _ => panic!( "[{}] expression is not InfixExpression. got={}", i, expression ), }; left.assert_literal_expression(&infix_expression.left, i); assert_eq!( infix_expression.operator, operator, "[{}] expression.operator is not {}. got={}", i, operator, infix_expression.operator ); right.assert_literal_expression(&infix_expression.right, i); } fn setup_operator_precedence_parsing_input() -> Vec<String> { vec![ "-a * b", "!-a", "a + b + c", "a + b - c", "a * b * c", "a * b / c", "a + b / c", "a + b * c + d / e - f", "3 + 4; -5 * 5", "5 > 4 == 3 < 4", "5 < 4 != 3 > 4", "3 + 4 * 5 == 3 * 1 + 4 * 5", "true", "false", "3 > 5 == false", "3 < 5 == true", ] .into_iter() .map(str::to_string) .collect() } fn setup_operator_precedence_parsing_expect() -> Vec<String> { vec![ "((-a) * b)", "(!(-a))", "((a + b) + c)", "((a + b) - c)", "((a * b) * c)", "((a * b) / c)", "(a + (b / c))", "(((a + (b * c)) + (d / e)) - f)", "(3 + 4)((-5) * 5)", "((5 > 4) == (3 < 4))", "((5 < 4) != (3 > 4))", "((3 + (4 * 5)) == ((3 * 1) + (4 * 5)))", "true", "false", "((3 > 5) == false)", "((3 < 5) == true)", ] .into_iter() .map(str::to_string) .collect() } #[test] fn test_operator_precedence_parsing() { let inputs = setup_operator_precedence_parsing_input(); let expects = setup_operator_precedence_parsing_expect(); assert_eq!( inputs.len(), expects.len(), "inputs.len and expects.len is mismatch" ); inputs .into_iter() .zip(expects.into_iter()) .enumerate() .for_each(|(i, (input, expect))| { let mut parser = Parser::new(Lexer::new(input)); let program = parser.parse_program(); check_parser_errors(&parser, i); assert!(program.first().is_some(), "[{}] first is none", i); assert_eq!( expect, string(&program), "[{}] expected={}, got={}", i, expect, string(&program) ); }) } fn setup_boolean_expression_input() -> Vec<String> { vec![ "true;", "false;", "let foobar = true;", "let barfoo = false;", ] .into_iter() .map(str::to_string) .collect() } fn setup_boolean_expression_expect() -> Vec<bool> { vec![true, false, true, false] } #[test] fn test_boolean_expression() { let inputs = setup_boolean_expression_input(); let expects = setup_boolean_expression_expect(); inputs .into_iter() .zip(expects.into_iter()) .enumerate() .for_each(|(i, (input, expect))| { let lexer = Lexer::new(input); let mut parser = Parser::new(lexer); let program = parser.parse_program(); check_parser_errors(&parser, i); assert!(program.first().is_some(), "first is none"); match program.get(0).unwrap() { Statement::Let(statement) => { assert_boolean_expression(&statement.expression, expect, i) } Statement::Expression(statement) => { assert_boolean_expression(&statement.expression, expect, i) } _ => panic!( "[{}] statement is not LetStatement or ExpressionStatement. got={}", i, program.get(0).unwrap() ), } }); } fn assert_boolean_expression(expression: &Expression, expect: bool, i: usize) { let boolean_expression = match expression { Expression::Boolean(expression) => expression, _ => panic!("[{}] expression is not Boolean. got={}", i, expression), }; assert_eq!( expect, boolean_expression.value, "[{}] boolean value not {}. got={}", i, expect, boolean_expression.value ); assert_eq!( expect.to_string(), boolean_expression.token_literal(), "[{}] literal token_literal not {}. got={}", i, expect.to_string(), boolean_expression.token_literal() ); } fn assert_integer_literal(expression: &Expression, value: i64, i: usize) { let integer_literal = match expression { Expression::Integer(literal) => literal, _ => panic!("[{}] expression not IntegerLiteral. got={}", i, expression), }; assert_eq!( value, integer_literal.value, "[{}] literal value not {}. got={}", i, value, integer_literal.value ); assert_eq!( value.to_string(), integer_literal.token_literal(), "[{}] literal token_literal not {}. got={}", i, value.to_string(), integer_literal.token_literal() ); } fn assert_identifier(expression: &Expression, value: String, i: usize) { let identifier = match expression { Expression::Identifier(identifier) => identifier, _ => panic!("[{}] expression not Identifier. got={}", i, expression), }; assert_eq!( identifier.value, value, "[{}] identifier.value not {}. got={}", i, value, identifier.value ); assert_eq!( identifier.token_literal(), value, "[{}] identifier.token_literal() not {}. got={}", i, value, identifier.token_literal() ); } fn assert_boolean_literal(expression: &Expression, value: bool, i: usize) { let boolean = match expression { Expression::Boolean(boolean) => boolean, _ => panic!("[{}] expression not boolean. got={}", i, expression), }; assert_eq!( value, boolean.value, "[{}] expression.value not {}. got={}", i, value, boolean.value ); assert_eq!( value.to_string(), boolean.token_literal(), "[{}] expression.token_literal() not {}. got={}", i, value.to_string(), boolean.token_literal() ); } fn check_parser_errors(parser: &Parser, i: usize) { if parser.errors.is_empty() { return; } eprintln!("[{}] parser has {} errors", i, parser.errors.len()); parser .errors .iter() .enumerate() .for_each(|(i, err)| eprintln!("[{}] parser error: {}", i, err)); } trait Wrapped { fn assert_literal_expression(self, expression: &Expression, i: usize); } enum Concrete { Integer(i64), String(String), Boolean(bool), } impl Wrapped for Concrete { fn assert_literal_expression(self, expression: &Expression, i: usize) { match self { Concrete::Integer(v) => assert_integer_literal(expression, v, i), Concrete::String(v) => assert_identifier(expression, v, i), Concrete::Boolean(v) => assert_boolean_literal(expression, v, i), } } } }
//! Interior mutability stuff. #[cfg(feature = "v2")] use crate::v2::models::Resolvable; #[cfg(feature = "v2")] use serde::{Serialize, Serializer}; #[cfg(feature = "v2")] impl<T> Serialize for Resolvable<T> where T: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match self { Resolvable::Raw(s) => s.serialize(serializer), Resolvable::Resolved { new, .. } => new.serialize(serializer), } } }
#![warn(unsafe_code)] #![warn(rust_2018_idioms)] #![allow(dead_code)] use auto_enums::enum_derive; #[cfg(feature = "external_libraries")] #[test] fn stable_external() { #[enum_derive( rayon::ParallelIterator, rayon::IndexedParallelIterator, rayon::ParallelExtend, serde::Serialize )] enum Enum1<A, B> { A(A), B(B), } #[enum_derive( Future, futures::Stream, futures::Sink, futures::AsyncRead, futures::AsyncWrite, futures::AsyncSeek, futures::AsyncBufRead )] enum Future<A, B> { A(A), B(B), } // #[enum_derive(futures01::Future, futures01::Sink, futures01::Stream)] // enum Future01<A, B> { // A(A), // B(B), // } }
use std::cmp; use std::convert::TryFrom; use std::str::FromStr; enum Mode { Position, Immediate, } #[derive(Debug)] struct ModeParseError; impl TryFrom<char> for Mode { type Error = ModeParseError; fn try_from(c: char) -> Result<Self, Self::Error> { match c { '0' => Ok(Mode::Position), '1' => Ok(Mode::Immediate), _ => Err(ModeParseError), } } } enum Instruction { Add(Mode, Mode), Mul(Mode, Mode), Input, Output(Mode), Halt, JumpNZ(Mode, Mode), JumpZ(Mode, Mode), LT(Mode, Mode), EQ(Mode, Mode), } #[derive(Debug, Copy, Clone)] pub enum Cell<'a> { Value(i64), Symbol(&'a str), } impl<'a> Cell<'_> { fn value(&self) -> i64 { match self { Cell::Value(v) => *v, Cell::Symbol(s) => s.parse::<i64>().unwrap(), } } fn instruction(&self) -> Instruction { match self { Cell::Symbol(s) => s.parse().unwrap(), Cell::Value(v) => v.to_string().parse().unwrap(), } } } #[derive(Debug)] struct InstructionParseError; impl FromStr for Instruction { type Err = InstructionParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { let len = s.len(); let (modes, opcode) = s.split_at(len - cmp::min(2, len)); let mut modes = modes.chars().rev().map(|s| Mode::try_from(s).unwrap()); let mut mode = || modes.next().unwrap_or(Mode::Position); match opcode.parse::<i64>().unwrap() { 1 => Ok(Instruction::Add(mode(), mode())), 2 => Ok(Instruction::Mul(mode(), mode())), 3 => Ok(Instruction::Input), 4 => Ok(Instruction::Output(mode())), 5 => Ok(Instruction::JumpNZ(mode(), mode())), 6 => Ok(Instruction::JumpZ(mode(), mode())), 7 => Ok(Instruction::LT(mode(), mode())), 8 => Ok(Instruction::EQ(mode(), mode())), 99 => Ok(Instruction::Halt), _ => Err(InstructionParseError), } } } #[derive(Default)] pub struct IntCodeMachine { inputs: Vec<i64>, outputs: Vec<i64>, } fn load(tape: &[Cell], cursor: usize, offset: usize, mode: Mode) -> i64 { match mode { Mode::Immediate => tape[cursor + offset].value(), Mode::Position => tape[tape[cursor + offset].value() as usize].value(), } } fn store(tape: &mut [Cell], cursor: usize, offset: usize, value: i64) { tape[tape[cursor + offset].value() as usize] = Cell::Value(value); } impl IntCodeMachine { pub fn add_input(&mut self, input: i64) { self.inputs.push(input); } pub fn diagnostic_code(&self) -> Option<i64> { self.outputs.last().copied() } pub fn errors(&self) -> bool { let len = self.outputs.len(); self.outputs[..len - 1].iter().any(|&output| output != 0) } pub fn clear(&mut self) { self.inputs.clear(); self.outputs.clear(); } pub fn run(&mut self, tape: &mut [Cell]) -> i64 { let mut cursor = 0; loop { match tape[cursor].instruction() { Instruction::Add(mode_1, mode_2) => { let a = load(tape, cursor, 1, mode_1); let b = load(tape, cursor, 2, mode_2); store(tape, cursor, 3, a + b); cursor += 4 } Instruction::Mul(mode_1, mode_2) => { let a = load(tape, cursor, 1, mode_1); let b = load(tape, cursor, 2, mode_2); store(tape, cursor, 3, a * b); cursor += 4 } Instruction::Input => { store(tape, cursor, 1, self.inputs.pop().unwrap()); cursor += 2; } Instruction::Output(mode) => { self.outputs.push(load(tape, cursor, 1, mode)); cursor += 2 } Instruction::JumpNZ(mode_1, mode_2) => { if load(tape, cursor, 1, mode_1) != 0 { cursor = load(tape, cursor, 2, mode_2) as usize; } else { cursor += 3; } } Instruction::JumpZ(mode_1, mode_2) => { if load(tape, cursor, 1, mode_1) == 0 { cursor = load(tape, cursor, 2, mode_2) as usize; } else { cursor += 3 } } Instruction::LT(mode_1, mode_2) => { let a = load(tape, cursor, 1, mode_1); let b = load(tape, cursor, 2, mode_2); store(tape, cursor, 3, if a < b { 1 } else { 0 }); cursor += 4; } Instruction::EQ(mode_1, mode_2) => { let a = load(tape, cursor, 1, mode_1); let b = load(tape, cursor, 2, mode_2); store(tape, cursor, 3, if a == b { 1 } else { 0 }); cursor += 4; } Instruction::Halt => break, } } tape[0].value() } }
pub struct Solution; #[derive(Debug, PartialEq, Eq)] pub struct TreeNode { pub val: i32, pub left: Tree, pub right: Tree, } use std::cell::RefCell; use std::rc::Rc; type Tree = Option<Rc<RefCell<TreeNode>>>; impl Solution { pub fn binary_tree_paths(root: Tree) -> Vec<String> { fn rec(node: Rc<RefCell<TreeNode>>, s: String, res: &mut Vec<String>) { match (node.borrow().left.clone(), node.borrow().right.clone()) { (None, None) => { res.push(s); } (Some(node), None) | (None, Some(node)) => { let mut s = s; s.push_str(&format!("->{}", node.borrow().val)); rec(node, s, res); } (Some(node1), Some(node2)) => { let mut s1 = s.clone(); let mut s2 = s; s1.push_str(&format!("->{}", node1.borrow().val)); s2.push_str(&format!("->{}", node2.borrow().val)); rec(node1, s1, res); rec(node2, s2, res); } } } if root.is_none() { return Vec::new(); } let mut res = Vec::new(); let node = root.unwrap(); let s = format!("{}", node.borrow().val); rec(node, s, &mut res); res } } #[test] fn test0257() { fn case(root: Tree, want: Vec<&str>) { let got = Solution::binary_tree_paths(root); let want: Vec<String> = want.iter().map(|s| s.to_string()).collect(); assert_eq!(got, want); } fn tree(val: i32, left: Tree, right: Tree) -> Tree { Some(Rc::new(RefCell::new(TreeNode { val, left, right }))) } case( tree(1, tree(2, None, tree(5, None, None)), tree(3, None, None)), vec!["1->2->5", "1->3"], ); case(None, vec![]); }
mod reqmgr; pub use reqmgr::*; mod server; pub use server::*;
pub mod database; pub mod daemon; pub mod settings; use self::daemon::Daemon; use self::database::Database; use self::settings::Settings; pub struct Root { daemon: Option<Daemon>, database: Option<Database>, settings: Option<Settings> } impl Root { pub fn new() -> Root { let mut root = Root { daemon: None, database: None, settings: None }; root.settings = Some(Settings::new(&root)); root.database = Some(Database::new(&root)); root.daemon = Some(Daemon::new(&root)); root } pub fn database(&self) -> &Database { &self.database.as_ref().unwrap() } pub fn daemon(&self) -> &Daemon { &self.daemon.as_ref().unwrap() } pub fn settings(&self) -> &Settings { &self.settings.as_ref().unwrap() } }
fn main() { println!("Area of a 50x30 rect params is {}", area(30, 50)); println!("Area of a 50x30 rect tuples is {}", area_tup((30, 50))); let rect = Rectangle { width: 30, height: 50, }; println!("Area of a 50x30 rect struct is {}", area_rect(&rect)); println!("Area of a 50x30 rect struct with impl is {}", rect.area()); println!("Printing rect debug: {:?}", rect); println!("Printing rect debug: {:#?}", rect); let rect1 = Rectangle { width: 30, height: 50 }; let rect2 = Rectangle { width: 10, height: 40 }; let rect3 = Rectangle { width: 60, height: 45 }; println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3)); println!("A square of 20x20: {:?}", Rectangle::square(20)); } fn area(width: u32, height: u32) -> u32 { width * height } fn area_tup(dimensions: (u32, u32)) -> u32 { dimensions.0 * dimensions.1 } #[derive(Debug)] struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn can_hold(&self, rect: &Rectangle) -> bool { self.width > rect.width && self.height > rect.height } fn square(size: u32) -> Rectangle { Rectangle { width: size, height: size, } } } fn area_rect(rect: &Rectangle) -> u32 { rect.width * rect.height }
//! An efficient representation of a 2D matrix. use crate::prelude::*; use std::ops::Index; use std::ops::IndexMut; // ============ // == Matrix == // ============ /// An efficient 2D matrix implemented on top of [`std::vec::Vec`]. #[derive(Clone,Debug,Default,PartialEq,Eq)] #[allow(missing_docs)] pub struct Matrix<T> { pub rows : usize, pub columns : usize, pub matrix : Vec<T>, } impl<T:Copy> Matrix<T> { /// Get the number of rows in the matrix. pub fn rows(&self) -> usize { self.rows } /// Get the number of columns in the matrix. pub fn columns(&self) -> usize { self.columns } /// Obtain the indices for the rows in this matrix. pub fn row_indices(&self) -> Range<usize> { 0..self.rows() } /// Indexing with bounds checking. pub fn safe_index(&self, row:usize, column:usize) -> Option<T> { (row < self.rows && column < self.columns).as_some_from(|| { self.matrix[row*self.columns+column] }) } } impl<T:Default> Matrix<T> { /// Construct a matrix with the dimensions given by `rows` and `columns`. pub fn new(rows:usize, columns:usize) -> Self { let mut matrix = Vec::with_capacity(rows*columns); for _ in 0..matrix.capacity() { matrix.push(default()) } Self{rows,columns,matrix} } /// Add a new row to the matrix `self`, filled with default values. pub fn new_row(&mut self) { for _ in 0..self.columns { self.matrix.push(default()); } self.rows += 1; } /// Add a new column to the matrix `self`, filled with default values. /// /// Note that this is an _expensive_ operation that requires moving potentially very large /// allocations around. pub fn new_column(&mut self) { for n in 0..self.rows { let index = self.columns*n + self.columns+n; self.matrix.insert(index,default()); } self.columns += 1; } } // FIXME: Wrong indexing order! // === Trait Impls === impl<T> Index<(usize,usize)> for Matrix<T> { type Output = T; fn index(&self, index:(usize,usize)) -> &T { &self.matrix[index.0*self.columns+index.1] } } impl<T> IndexMut<(usize,usize)> for Matrix<T> { fn index_mut(&mut self, index:(usize,usize)) -> &mut T { &mut self.matrix[index.0*self.columns+index.1] } } // ============= // === Tests === // ============= #[cfg(test)] mod tests { use super::*; #[test] fn default_size() { let default = Matrix::<usize>::default(); assert_eq!(default.rows,0); assert_eq!(default.columns,0); } #[test] fn construct_with_dimensions() { let matrix = Matrix::<usize>::new(5, 10); assert_eq!(matrix.rows,5); assert_eq!(matrix.columns,10); } #[test] fn add_row() { let mut matrix = Matrix::<usize>::new(2, 2); matrix[(0,0)] = 1; matrix[(0,1)] = 2; matrix[(1,0)] = 3; matrix[(1,1)] = 4; assert_eq!(matrix.rows,2); assert_eq!(matrix.columns,2); matrix.new_row(); assert_eq!(matrix.rows,3); assert_eq!(matrix.columns,2); assert_eq!(matrix[(0,0)],1); assert_eq!(matrix[(0,1)],2); assert_eq!(matrix[(1,0)],3); assert_eq!(matrix[(1,1)],4); assert_eq!(matrix[(2,0)],0); assert_eq!(matrix[(2,1)],0); } #[test] fn add_column() { let mut matrix = Matrix::<usize>::new(2,2); matrix[(0,0)] = 1; matrix[(0,1)] = 2; matrix[(1,0)] = 3; matrix[(1,1)] = 4; assert_eq!(matrix.rows,2); assert_eq!(matrix.columns,2); matrix.new_column(); assert_eq!(matrix.rows,2); assert_eq!(matrix.columns,3); assert_eq!(matrix[(0,0)],1); assert_eq!(matrix[(0,1)],2); assert_eq!(matrix[(1,0)],3); assert_eq!(matrix[(1,1)],4); assert_eq!(matrix[(0,2)],0); assert_eq!(matrix[(1,2)],0); } #[test] fn row_column_indexing() { let mut matrix = Matrix::<usize>::new(2,2); matrix[(0,0)] = 1; matrix[(0,1)] = 2; matrix[(1,0)] = 3; matrix[(1,1)] = 4; let mut output = Vec::default(); for row in 0..2 { for col in 0..2 { output.push(matrix[(row,col)]); } } assert_eq!(output,vec![1,2,3,4]); } #[test] fn safe_indexing() { let matrix = Matrix::<usize>::new(2,2); let exists = matrix.safe_index(0,0); let does_not_exist = matrix.safe_index(3,0); assert_eq!(exists,Some(0)); assert_eq!(does_not_exist,None); } }
// LCOV_EXCL_START use yaml_rust::{Yaml, YamlLoader}; lazy_static! { /// Translations for the application service pub static ref TRANSLATIONS: Vec<Yaml> = { let translations = include_str!("../../assets/translations.yaml"); YamlLoader::load_from_str(translations).expect("Could not load translations") }; } macro_rules! build_i18n_struct { ($($f:ident),*) => { /// Struct that stores translations for all supported languages #[derive(Debug)] pub struct I18n { /// Variables to replace placeholders in the language string pub vars: Option<Vec<(&'static str, String)>>, $( /// language field pub $f: String ),* } impl I18n { /// Set the variables to replace placeholders in the language string pub fn with_vars(mut self, vars: Vec<(&'static str, String)>) -> I18n { self.vars = Some(vars); self } /// Return the translation for a language pub fn l(&self, language: &str) -> String { let mut translation = match language{ $(stringify!($f) => self.$f.clone(),)* _ => "Unsupported language".to_string() }; if let Some(vars) = self.vars.clone() { for (key, val) in vars { let placeholder = format!("${{{}}}", key); translation = translation.replace(&placeholder, &val); } } translation } } } } macro_rules! translate_all_languages { ($($language:ident => [[$($key:expr),*]; [$($k:expr => $v:expr),*]]);*) =>{ { I18n { vars: None, $($language: { let translation = &TRANSLATIONS[0][stringify!($language)]$([$key])*; match translation.as_str() { Some(value) => value.to_string()$(.replace(concat!("{", $k, "}"),$v))*, None => format!("Translation '{}' not found", [$($key),*].join(".")) } } ),+ } } }; } macro_rules! setup_translation_macro { ($($l:ident),*) => { macro_rules! t { ($keys:tt;$repl:tt) => { { translate_all_languages!($($l => [$keys; $repl]);*) } }; ($keys:tt) => { { translate_all_languages!($($l => [$keys;[]]);*) } } } }; } macro_rules! i18n_languages { ($($l:ident),*) => { build_i18n_struct!($($l),*); setup_translation_macro!($($l),*); } } /// A list of languages that are supported by the application bridge i18n_languages!(en); /// Language that is used if no language is specified pub const DEFAULT_LANGUAGE: &str = "en"; // LCOV_EXCL_STOP
use core::fmt; use alloc::Vec; use alloc::String; use alloc::slice::SliceConcatExt; use kernel::random; #[derive(Debug)] pub struct UUID(Vec<u8>); impl UUID { pub fn new() -> Self { UUID(random::read(16)) } } impl fmt::Display for UUID { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &UUID(ref bytes) = self; let strs: Vec<String> = bytes.iter() .map(|b| format!("{:02X}", b)) .collect(); let uuid_str = strs.join(""); write!(f, "{}", uuid_str) } }
use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn say(s: &str) -> String { return String::from("NASA's Content of the day: ") + s; }
#![allow(clippy::all)] fn parse_line(line: &str) -> ((usize, usize), (usize, usize)) { let mut parts = line.trim().split(" -> "); let mut begin_part = parts.next().unwrap().split(","); let mut end_part = parts.next().unwrap().split(","); let x1 = begin_part.next().unwrap().parse::<usize>().unwrap(); let y1 = begin_part.next().unwrap().parse::<usize>().unwrap(); let x2 = end_part.next().unwrap().parse::<usize>().unwrap(); let y2 = end_part.next().unwrap().parse::<usize>().unwrap(); ((x1, y1), (x2, y2)) } pub fn part1(input: String) { let lines = input.split("\n"); let hydrothermal_vents = lines.map(|l| parse_line(l)).collect::<Vec<_>>(); let (max_x, max_y) = hydrothermal_vents .iter() .fold((0, 0), |(mut max_x, mut max_y), (begin, end)| { if begin.0 > max_x { max_x = begin.0; } if end.0 > max_x { max_x = begin.0; } if begin.1 > max_y { max_y = begin.1; } if end.1 > max_y { max_y = begin.1; } (max_x, max_y) }); println!("{:?}", hydrothermal_vents[0]); println!("Max X: {}, Max Y: {}", max_x, max_y); let mut grid = [[0usize; 1000]; 1000]; hydrothermal_vents.iter().for_each(|(begin, end)| { if begin.0 != end.0 && begin.1 != end.1 { let begin = (begin.0 as i64, begin.1 as i64); let end = (end.0 as i64, end.1 as i64); // (end.1 - begin.1)/(end.0 - begin.0)*(x - begin.0) = y - begin.1 let (x_start, x_end) = match begin.0.cmp(&end.0) { std::cmp::Ordering::Greater => (end.0, begin.0), std::cmp::Ordering::Less => (begin.0, end.0), _ => unreachable!(), }; for x in x_start..x_end + 1 { let y = ((end.1 - begin.1) * (x - begin.0)) / (end.0 - begin.0) + begin.1; grid[x as usize][y as usize] += 1; } return; } if begin.0 == end.0 { let (start, end) = match begin.1.cmp(&end.1) { std::cmp::Ordering::Equal => (begin.1, end.1), std::cmp::Ordering::Greater => (end.1, begin.1), std::cmp::Ordering::Less => (begin.1, end.1), }; for j in start..end + 1 { grid[begin.0][j] += 1; } return; } if begin.1 == end.1 { let (start, end) = match begin.0.cmp(&end.0) { std::cmp::Ordering::Equal => (begin.0, end.0), std::cmp::Ordering::Greater => (end.0, begin.0), std::cmp::Ordering::Less => (begin.0, end.0), }; for i in start..end + 1 { grid[i][begin.1] += 1; } return; } unreachable!(); }); let mut overlaps = 0; for i in 0..1000 { for j in 0..1000 { if grid[i][j] >= 2 { overlaps += 1; } } } println!("Overlaps: {}", overlaps); }
use std::collections::HashSet; use std::sync::mpsc; use std::thread; fn generate_multiples_until(x: u32, limit: u32) -> Vec<u32> { let mut multiples: Vec<u32> = Vec::new(); if x == 0 { return multiples; } let mut multiple: u32 = x; while multiple < limit { multiples.push(multiple); multiple += x; } multiples } fn sum_multiples(rx: mpsc::Receiver<Vec<u32>>) -> u32 { let mut unique_multiples: HashSet<u32> = HashSet::new(); let mut sum: u32 = 0; for multiples in rx { for multiple in multiples { if unique_multiples.insert(multiple) { sum += multiple; } } } sum } pub fn sum_of_multiples(limit: u32, factors: &'static [u32]) -> u32 { let (tx, rx) = mpsc::channel(); for factor in factors { let tx1 = mpsc::Sender::clone(&tx); // Generate multiples smaller than limit thread::spawn(move || { // Generate values let multiples = generate_multiples_until(*factor, limit); tx1.send(multiples).unwrap(); }); } drop(tx); sum_multiples(rx) }
#[cfg(feature = "async")] use crate::protocol::util_async; #[cfg(feature = "sync")] use crate::protocol::util_sync; use crate::HdbResult; #[cfg(feature = "sync")] use byteorder::{LittleEndian, ReadBytesExt}; #[derive(Debug)] pub struct ReadLobReply { locator_id: u64, is_last_data: bool, data: Vec<u8>, } impl ReadLobReply { pub fn locator_id(&self) -> &u64 { &self.locator_id } pub fn into_data_and_last(self) -> (Vec<u8>, bool) { (self.data, self.is_last_data) } } impl ReadLobReply { #[cfg(feature = "sync")] pub fn parse_sync(rdr: &mut dyn std::io::Read) -> HdbResult<Self> { let locator_id = rdr.read_u64::<LittleEndian>()?; // I8 let options = rdr.read_u8()?; // I1 let is_last_data = (options & 0b100_u8) != 0; let chunk_length = rdr.read_i32::<LittleEndian>()?; // I4 util_sync::skip_bytes(3, rdr)?; // B3 (filler) #[allow(clippy::cast_sign_loss)] let data = util_sync::parse_bytes(chunk_length as usize, rdr)?; // B[chunk_length] Ok(Self { locator_id, is_last_data, data, }) } #[cfg(feature = "async")] pub async fn parse_async<R: std::marker::Unpin + tokio::io::AsyncReadExt>( rdr: &mut R, ) -> HdbResult<Self> { let locator_id = rdr.read_u64_le().await?; // I8 let options = rdr.read_u8().await?; // I1 let is_last_data = (options & 0b100_u8) != 0; let chunk_length = rdr.read_i32_le().await?; // I4 util_async::skip_bytes(3, rdr).await?; // B3 (filler) #[allow(clippy::cast_sign_loss)] let data = util_async::parse_bytes(chunk_length as usize, rdr).await?; // B[chunk_length] Ok(Self { locator_id, is_last_data, data, }) } }
extern crate reverse_endian; #[cfg(test)] mod tests { use reverse_endian::ReverseEndian; #[derive(Debug, PartialEq, ReverseEndian)] struct TestStruct { four_bytes: u32, two_bytes: u16, } #[test] fn test_struct_named() { let original = TestStruct { four_bytes: 0xd4c3b2a1, two_bytes: 0xa1b2, }; let reversed = TestStruct { four_bytes: 0xa1b2c3d4, two_bytes: 0xb2a1, }; assert_eq!(reversed, original.reverse_endian()); } }
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. /// Mail exchange data. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct MailExchange<'a> { /// Preference. pub preference: u16, /// Mail server name. pub mail_server_name: WithCompressionParsedName<'a>, }
// These functions are only used if the API uses Nullable properties, so allow them to be // dead code. #![allow(dead_code)] #[cfg(feature = "serdejson")] use serde::de::Error as SerdeError; #[cfg(feature = "serdejson")] use serde::de::{Deserialize, DeserializeOwned, Deserializer}; #[cfg(feature = "serdejson")] use serde::ser::{Serialize, Serializer}; use std::clone::Clone; use std::mem; /// The Nullable type. Represents a value which may be specified as null on an API. /// Note that this is distinct from a value that is optional and not present! /// /// Nullable implements many of the same methods as the Option type (map, unwrap, etc). #[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] pub enum Nullable<T> { /// Null value Null, /// Value is present Present(T), } impl<T> Nullable<T> { ///////////////////////////////////////////////////////////////////////// // Querying the contained values ///////////////////////////////////////////////////////////////////////// /// Returns `true` if the Nullable is a `Present` value. /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let x: Nullable<u32> = Nullable::Present(2); /// assert_eq!(x.is_present(), true); /// /// let x: Nullable<u32> = Nullable::Null; /// assert_eq!(x.is_present(), false); /// ``` #[inline] pub fn is_present(&self) -> bool { match *self { Nullable::Present(_) => true, Nullable::Null => false, } } /// Returns `true` if the Nullable is a `Null` value. /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let x: Nullable<u32> = Nullable::Present(2); /// assert_eq!(x.is_null(), false); /// /// let x: Nullable<u32> = Nullable::Null; /// assert_eq!(x.is_null(), true); /// ``` #[inline] pub fn is_null(&self) -> bool { !self.is_present() } ///////////////////////////////////////////////////////////////////////// // Adapter for working with references ///////////////////////////////////////////////////////////////////////// /// Converts from `Nullable<T>` to `Nullable<&T>`. /// /// # Examples /// /// Convert an `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, preserving the original. /// The [`map`] method takes the `self` argument by value, consuming the original, /// so this technique uses `as_ref` to first take a `Nullable` to a reference /// to the value inside the original. /// /// [`map`]: enum.Nullable.html#method.map /// [`String`]: ../../std/string/struct.String.html /// [`usize`]: ../../std/primitive.usize.html /// /// ``` /// # use ::swagger::Nullable; /// /// let num_as_str: Nullable<String> = Nullable::Present("10".to_string()); /// // First, cast `Nullable<String>` to `Nullable<&String>` with `as_ref`, /// // then consume *that* with `map`, leaving `num_as_str` on the stack. /// let num_as_int: Nullable<usize> = num_as_str.as_ref().map(|n| n.len()); /// println!("still can print num_as_str: {:?}", num_as_str); /// ``` #[inline] pub fn as_ref(&self) -> Nullable<&T> { match *self { Nullable::Present(ref x) => Nullable::Present(x), Nullable::Null => Nullable::Null, } } /// Converts from `Nullable<T>` to `Nullable<&mut T>`. /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let mut x = Nullable::Present(2); /// match x.as_mut() { /// Nullable::Present(v) => *v = 42, /// Nullable::Null => {}, /// } /// assert_eq!(x, Nullable::Present(42)); /// ``` #[inline] pub fn as_mut(&mut self) -> Nullable<&mut T> { match *self { Nullable::Present(ref mut x) => Nullable::Present(x), Nullable::Null => Nullable::Null, } } ///////////////////////////////////////////////////////////////////////// // Getting to contained values ///////////////////////////////////////////////////////////////////////// /// Unwraps a Nullable, yielding the content of a `Nullable::Present`. /// /// # Panics /// /// Panics if the value is a [`Nullable::Null`] with a custom panic message provided by /// `msg`. /// /// [`Nullable::Null`]: #variant.Null /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let x = Nullable::Present("value"); /// assert_eq!(x.expect("the world is ending"), "value"); /// ``` /// /// ```{.should_panic} /// # use ::swagger::Nullable; /// /// let x: Nullable<&str> = Nullable::Null; /// x.expect("the world is ending"); // panics with `the world is ending` /// ``` #[inline] pub fn expect(self, msg: &str) -> T { match self { Nullable::Present(val) => val, Nullable::Null => expect_failed(msg), } } /// Moves the value `v` out of the `Nullable<T>` if it is `Nullable::Present(v)`. /// /// In general, because this function may panic, its use is discouraged. /// Instead, prefer to use pattern matching and handle the `Nullable::Null` /// case explicitly. /// /// # Panics /// /// Panics if the self value equals [`Nullable::Null`]. /// /// [`Nullable::Null`]: #variant.Null /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let x = Nullable::Present("air"); /// assert_eq!(x.unwrap(), "air"); /// ``` /// /// ```{.should_panic} /// # use ::swagger::Nullable; /// /// let x: Nullable<&str> = Nullable::Null; /// assert_eq!(x.unwrap(), "air"); // fails /// ``` #[inline] pub fn unwrap(self) -> T { match self { Nullable::Present(val) => val, Nullable::Null => panic!("called `Nullable::unwrap()` on a `Nullable::Null` value"), } } /// Returns the contained value or a default. /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// assert_eq!(Nullable::Present("car").unwrap_or("bike"), "car"); /// assert_eq!(Nullable::Null.unwrap_or("bike"), "bike"); /// ``` #[inline] pub fn unwrap_or(self, def: T) -> T { match self { Nullable::Present(x) => x, Nullable::Null => def, } } /// Returns the contained value or computes it from a closure. /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let k = 10; /// assert_eq!(Nullable::Present(4).unwrap_or_else(|| 2 * k), 4); /// assert_eq!(Nullable::Null.unwrap_or_else(|| 2 * k), 20); /// ``` #[inline] pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T { match self { Nullable::Present(x) => x, Nullable::Null => f(), } } ///////////////////////////////////////////////////////////////////////// // Transforming contained values ///////////////////////////////////////////////////////////////////////// /// Maps a `Nullable<T>` to `Nullable<U>` by applying a function to a contained value. /// /// # Examples /// /// Convert a `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, consuming the original: /// /// [`String`]: ../../std/string/struct.String.html /// [`usize`]: ../../std/primitive.usize.html /// /// ``` /// # use ::swagger::Nullable; /// /// let maybe_some_string = Nullable::Present(String::from("Hello, World!")); /// // `Nullable::map` takes self *by value*, consuming `maybe_some_string` /// let maybe_some_len = maybe_some_string.map(|s| s.len()); /// /// assert_eq!(maybe_some_len, Nullable::Present(13)); /// ``` #[inline] pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Nullable<U> { match self { Nullable::Present(x) => Nullable::Present(f(x)), Nullable::Null => Nullable::Null, } } /// Applies a function to the contained value (if any), /// or returns a `default` (if not). /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let x = Nullable::Present("foo"); /// assert_eq!(x.map_or(42, |v| v.len()), 3); /// /// let x: Nullable<&str> = Nullable::Null; /// assert_eq!(x.map_or(42, |v| v.len()), 42); /// ``` #[inline] pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U { match self { Nullable::Present(t) => f(t), Nullable::Null => default, } } /// Applies a function to the contained value (if any), /// or computes a `default` (if not). /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let k = 21; /// /// let x = Nullable::Present("foo"); /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); /// /// let x: Nullable<&str> = Nullable::Null; /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); /// ``` #[inline] pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { match self { Nullable::Present(t) => f(t), Nullable::Null => default(), } } /// Transforms the `Nullable<T>` into a [`Result<T, E>`], mapping `Nullable::Present(v)` to /// [`Ok(v)`] and `Nullable::Null` to [`Err(err)`][Err]. /// /// [`Result<T, E>`]: ../../std/result/enum.Result.html /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok /// [Err]: ../../std/result/enum.Result.html#variant.Err /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let x = Nullable::Present("foo"); /// assert_eq!(x.ok_or(0), Ok("foo")); /// /// let x: Nullable<&str> = Nullable::Null; /// assert_eq!(x.ok_or(0), Err(0)); /// ``` #[inline] pub fn ok_or<E>(self, err: E) -> Result<T, E> { match self { Nullable::Present(v) => Ok(v), Nullable::Null => Err(err), } } /// Transforms the `Nullable<T>` into a [`Result<T, E>`], mapping `Nullable::Present(v)` to /// [`Ok(v)`] and `Nullable::Null` to [`Err(err())`][Err]. /// /// [`Result<T, E>`]: ../../std/result/enum.Result.html /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok /// [Err]: ../../std/result/enum.Result.html#variant.Err /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let x = Nullable::Present("foo"); /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); /// /// let x: Nullable<&str> = Nullable::Null; /// assert_eq!(x.ok_or_else(|| 0), Err(0)); /// ``` #[inline] pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> { match self { Nullable::Present(v) => Ok(v), Nullable::Null => Err(err()), } } ///////////////////////////////////////////////////////////////////////// // Boolean operations on the values, eager and lazy ///////////////////////////////////////////////////////////////////////// /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise returns `optb`. /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let x = Nullable::Present(2); /// let y: Nullable<&str> = Nullable::Null; /// assert_eq!(x.and(y), Nullable::Null); /// /// let x: Nullable<u32> = Nullable::Null; /// let y = Nullable::Present("foo"); /// assert_eq!(x.and(y), Nullable::Null); /// /// let x = Nullable::Present(2); /// let y = Nullable::Present("foo"); /// assert_eq!(x.and(y), Nullable::Present("foo")); /// /// let x: Nullable<u32> = Nullable::Null; /// let y: Nullable<&str> = Nullable::Null; /// assert_eq!(x.and(y), Nullable::Null); /// ``` #[inline] pub fn and<U>(self, optb: Nullable<U>) -> Nullable<U> { match self { Nullable::Present(_) => optb, Nullable::Null => Nullable::Null, } } /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise calls `f` with the /// wrapped value and returns the result. /// /// Some languages call this operation flatmap. /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// fn sq(x: u32) -> Nullable<u32> { Nullable::Present(x * x) } /// fn nope(_: u32) -> Nullable<u32> { Nullable::Null } /// /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(sq), Nullable::Present(16)); /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(nope), Nullable::Null); /// assert_eq!(Nullable::Present(2).and_then(nope).and_then(sq), Nullable::Null); /// assert_eq!(Nullable::Null.and_then(sq).and_then(sq), Nullable::Null); /// ``` #[inline] pub fn and_then<U, F: FnOnce(T) -> Nullable<U>>(self, f: F) -> Nullable<U> { match self { Nullable::Present(x) => f(x), Nullable::Null => Nullable::Null, } } /// Returns the Nullable if it contains a value, otherwise returns `optb`. /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let x = Nullable::Present(2); /// let y = Nullable::Null; /// assert_eq!(x.or(y), Nullable::Present(2)); /// /// let x = Nullable::Null; /// let y = Nullable::Present(100); /// assert_eq!(x.or(y), Nullable::Present(100)); /// /// let x = Nullable::Present(2); /// let y = Nullable::Present(100); /// assert_eq!(x.or(y), Nullable::Present(2)); /// /// let x: Nullable<u32> = Nullable::Null; /// let y = Nullable::Null; /// assert_eq!(x.or(y), Nullable::Null); /// ``` #[inline] pub fn or(self, optb: Nullable<T>) -> Nullable<T> { match self { Nullable::Present(_) => self, Nullable::Null => optb, } } /// Returns the Nullable if it contains a value, otherwise calls `f` and /// returns the result. /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// fn nobody() -> Nullable<&'static str> { Nullable::Null } /// fn vikings() -> Nullable<&'static str> { Nullable::Present("vikings") } /// /// assert_eq!(Nullable::Present("barbarians").or_else(vikings), /// Nullable::Present("barbarians")); /// assert_eq!(Nullable::Null.or_else(vikings), Nullable::Present("vikings")); /// assert_eq!(Nullable::Null.or_else(nobody), Nullable::Null); /// ``` #[inline] pub fn or_else<F: FnOnce() -> Nullable<T>>(self, f: F) -> Nullable<T> { match self { Nullable::Present(_) => self, Nullable::Null => f(), } } ///////////////////////////////////////////////////////////////////////// // Misc ///////////////////////////////////////////////////////////////////////// /// Takes the value out of the Nullable, leaving a `Nullable::Null` in its place. /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let mut x = Nullable::Present(2); /// x.take(); /// assert_eq!(x, Nullable::Null); /// /// let mut x: Nullable<u32> = Nullable::Null; /// x.take(); /// assert_eq!(x, Nullable::Null); /// ``` #[inline] pub fn take(&mut self) -> Nullable<T> { mem::replace(self, Nullable::Null) } } impl<'a, T: Clone> Nullable<&'a T> { /// Maps an `Nullable<&T>` to an `Nullable<T>` by cloning the contents of the /// Nullable. /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let x = 12; /// let opt_x = Nullable::Present(&x); /// assert_eq!(opt_x, Nullable::Present(&12)); /// let cloned = opt_x.cloned(); /// assert_eq!(cloned, Nullable::Present(12)); /// ``` pub fn cloned(self) -> Nullable<T> { self.map(Clone::clone) } } impl<T: Default> Nullable<T> { /// Returns the contained value or a default /// /// Consumes the `self` argument then, if `Nullable::Present`, returns the contained /// value, otherwise if `Nullable::Null`, returns the default value for that /// type. /// /// # Examples /// /// ``` /// # use ::swagger::Nullable; /// /// let x = Nullable::Present(42); /// assert_eq!(42, x.unwrap_or_default()); /// /// let y: Nullable<i32> = Nullable::Null; /// assert_eq!(0, y.unwrap_or_default()); /// ``` #[inline] pub fn unwrap_or_default(self) -> T { match self { Nullable::Present(x) => x, Nullable::Null => Default::default(), } } } // This is a separate function to reduce the code size of .expect() itself. #[inline(never)] #[cold] fn expect_failed(msg: &str) -> ! { panic!("{}", msg) } ///////////////////////////////////////////////////////////////////////////// // Trait implementations ///////////////////////////////////////////////////////////////////////////// impl<T> Default for Nullable<T> { /// Returns None. #[inline] fn default() -> Nullable<T> { Nullable::Null } } impl<T> From<T> for Nullable<T> { fn from(val: T) -> Nullable<T> { Nullable::Present(val) } } #[cfg(feature = "serdejson")] impl<T> Serialize for Nullable<T> where T: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match *self { Nullable::Present(ref inner) => serializer.serialize_some(&inner), Nullable::Null => serializer.serialize_none(), } } } #[cfg(feature = "serdejson")] impl<'de, T> Deserialize<'de> for Nullable<T> where T: DeserializeOwned, { fn deserialize<D>(deserializer: D) -> Result<Nullable<T>, D::Error> where D: Deserializer<'de>, { // In order to deserialize a required, but nullable, value, we first have to check whether // the value is present at all. To do this, we deserialize to a serde_json::Value, which // fails if the value is missing, or gives serde_json::Value::Null if the value is present. // If that succeeds as null, we can easily return a Null. // If that succeeds as some value, we deserialize that value and return a Present. // If that errors, we return the error. let presence: Result<::serde_json::Value, _> = ::serde::Deserialize::deserialize(deserializer); match presence { Ok(::serde_json::Value::Null) => Ok(Nullable::Null), Ok(some_value) => ::serde_json::from_value(some_value) .map(Nullable::Present) .map_err(SerdeError::custom), Err(x) => Err(x), } } } /// Serde helper function to create a default `Option<Nullable<T>>` while /// deserializing pub fn default_optional_nullable<T>() -> Option<Nullable<T>> { None } /// Serde helper function to deserialize into an `Option<Nullable<T>>` #[cfg(feature = "serdejson")] pub fn deserialize_optional_nullable<'de, D, T>( deserializer: D, ) -> Result<Option<Nullable<T>>, D::Error> where D: Deserializer<'de>, T: Deserialize<'de>, { Option::<T>::deserialize(deserializer).map(|val| match val { Some(inner) => Some(Nullable::Present(inner)), None => Some(Nullable::Null), }) } #[cfg(test)] #[cfg(feature = "serdejson")] mod serde_tests { use super::*; use serde::{Deserialize, Serialize}; // Set up: #[derive(Clone, Debug, Deserialize, Serialize)] struct NullableStringStruct { item: Nullable<String>, } #[derive(Clone, Debug, Deserialize, Serialize)] struct OptionalNullableStringStruct { #[serde(deserialize_with = "deserialize_optional_nullable")] #[serde(default = "default_optional_nullable")] #[serde(skip_serializing_if = "Option::is_none")] item: Option<Nullable<String>>, } #[derive(Clone, Debug, Deserialize, Serialize)] struct NullableObjectStruct { item: Nullable<NullableStringStruct>, } #[derive(Clone, Debug, Deserialize, Serialize)] struct OptionalNullableObjectStruct { item: Option<Nullable<NullableStringStruct>>, } // Helper: macro_rules! round_trip { ($type:ty, $string:expr) => { println!("Original: {:?}", $string); let json: ::serde_json::Value = ::serde_json::from_str($string).expect("Deserialization to JSON Value failed"); println!("JSON Value: {:?}", json); let thing: $type = ::serde_json::from_value(json.clone()).expect("Deserialization to struct failed"); println!("Struct: {:?}", thing); let json_redux: ::serde_json::Value = ::serde_json::to_value(thing.clone()) .expect("Reserialization to JSON Value failed"); println!("JSON Redux: {:?}", json_redux); let string_redux = ::serde_json::to_string(&thing).expect("Reserialziation to JSON String failed"); println!("String Redux: {:?}", string_redux); assert_eq!( $string, string_redux, "Original did not match after round trip" ); }; } // The tests: #[test] fn missing_optionalnullable_value() { let string = "{}"; round_trip!(OptionalNullableStringStruct, string); } #[test] fn null_optionalnullable_value() { let string = "{\"item\":null}"; round_trip!(OptionalNullableStringStruct, string); } #[test] fn string_optionalnullable_value() { let string = "{\"item\":\"abc\"}"; round_trip!(OptionalNullableStringStruct, string); } #[test] fn object_optionalnullable_value() { let string = "{\"item\":{\"item\":\"abc\"}}"; round_trip!(OptionalNullableObjectStruct, string); } #[test] #[should_panic] fn missing_nullable_value() { let string = "{}"; round_trip!(NullableStringStruct, string); } #[test] fn null_nullable_value() { let string = "{\"item\":null}"; round_trip!(NullableStringStruct, string); } #[test] fn string_nullable_value() { let string = "{\"item\":\"abc\"}"; round_trip!(NullableStringStruct, string); } #[test] fn object_nullable_value() { let string = "{\"item\":{\"item\":\"abc\"}}"; round_trip!(NullableObjectStruct, string); } }
pub use ts_33_401::*; pub mod ts_33_401;
// An experiment to better understand nom's implementation and ideas #[derive(Debug)] pub enum ErrorKind { ParseError, EncodingError, Take, TakeUntil, Integer, Verify, Byte, Tag, Eof, } #[derive(Debug, Clone, Copy, PartialEq)] pub enum Endianness { Big, Little, } #[derive(Debug)] pub struct Error<'a> { pub input: &'a[u8], pub code: ErrorKind, } impl<'a> Error<'a> { fn new(i: &'a[u8], ek: ErrorKind) -> Self { Error { input: i, code: ek } } } pub type IResult<'a, O> = Result<(&'a[u8], O), Error<'a>>; // readers pub fn take<'a>(n: usize) -> impl Fn(&'a[u8]) -> IResult<&'a[u8]> { move |i:&[u8]| { if i.len() >= n { let (a, b) = i.split_at(n); Ok((b, a)) } else { Err(Error::new(i, ErrorKind::Take)) } } } pub fn u8_take_until<'a>(pat: &'a[u8]) -> impl Fn(&'a[u8]) -> IResult<&'a[u8]> { move |i:&[u8]| { let p = i.windows(pat.len()).position(|x| x == pat); if let Some(p) = p { let (a, b) = i.split_at(p); Ok((b, a)) } else { Err(Error::new(i, ErrorKind::TakeUntil)) } } } pub fn take_until<'a>(pat: &'a str) -> impl Fn(&'a[u8]) -> IResult<&'a[u8]> { u8_take_until(pat.as_bytes()) // FIXME: this doesn't seem safe, does it? } pub fn u64<'a>(e: Endianness) -> impl Fn(&'a[u8]) -> IResult<u64> { move |i:&[u8]| { if let Ok((i, r)) = take(8)(i) { let u = if e == Endianness::Big { (r[0] as u64) << 56 | (r[1] as u64) << 48 | (r[2] as u64) << 40 | (r[3] as u64) << 32 | (r[4] as u64) << 24 | (r[5] as u64) << 16 | (r[6] as u64) << 8 | r[7] as u64 } else { (r[7] as u64) << 56 | (r[6] as u64) << 48 | (r[5] as u64) << 40 | (r[4] as u64) << 32 | (r[3] as u64) << 24 | (r[2] as u64) << 16 | (r[1] as u64) << 8 | r[0] as u64 }; Ok((i, u)) } else { Err(Error::new(i, ErrorKind::Integer)) } } } pub fn be_u64<'a>(i: &'a[u8]) -> IResult<u64> { u64(Endianness::Big)(i) } pub fn le_u64<'a>(i: &'a[u8]) -> IResult<u64> { u64(Endianness::Little)(i) } pub fn u32<'a>(e: Endianness) -> impl Fn(&'a[u8]) -> IResult<u32> { move |i:&[u8]| { if let Ok((a, b)) = take(4)(i) { let u = if e == Endianness::Big { (b[0] as u32) << 24 | (b[1] as u32) << 16 | (b[2] as u32) << 8 | b[3] as u32 } else { (b[3] as u32) << 24 | (b[2] as u32) << 16 | (b[1] as u32) << 8 | b[0] as u32 }; Ok((a, u)) } else { Err(Error::new(i, ErrorKind::Integer)) } } } pub fn be_u32<'a>(i: &'a[u8]) -> IResult<u32> { u32(Endianness::Big)(i) } pub fn le_u32<'a>(i: &'a[u8]) -> IResult<u32> { u32(Endianness::Little)(i) } pub fn u16<'a>(e: Endianness) -> impl Fn(&'a[u8]) -> IResult<u16> { move |i:&[u8]| { if let Ok((i, b)) = take(2)(i) { let u = if e == Endianness::Big { (b[0] as u16) << 8 | b[1] as u16 } else { (b[1] as u16) << 8 | b[0] as u16 }; Ok((i, u)) } else { Err(Error::new(i, ErrorKind::Integer)) } } } pub fn be_u16<'a>(i: &'a[u8]) -> IResult<u16> { u16(Endianness::Big)(i) } pub fn le_u16<'a>(i: &'a[u8]) -> IResult<u16> { u16(Endianness::Little)(i) } pub fn u8<'a>(i:&'a[u8]) -> IResult<u8> { if !i.is_empty() { Ok((&i[1..], i[0])) } else { Err(Error::new(i, ErrorKind::Byte)) } } pub fn be_u8<'a>(i:&'a[u8]) -> IResult<u8> { u8(i) } // matchers pub fn byte<'a>(b: u8) -> impl Fn(&'a[u8]) -> IResult<u8> { move |i:&[u8]| { if !i.is_empty() && i[0] == b { Ok((&i[1..], b)) } else { Err(Error::new(i, ErrorKind::Byte)) } } } pub fn tag<'a>(t: &'a[u8]) -> impl Fn(&'a[u8]) -> IResult<&'a[u8]> { move |i:&[u8]| { if i.len() >= t.len() { let (a, b) = i.split_at(t.len()); if a == t { return Ok((b, a)); } } Err(Error::new(i, ErrorKind::Tag)) } } // Combinators pub fn many0<'a, O>(p: impl Fn(&'a[u8]) -> IResult<O>) -> impl Fn(&'a[u8]) -> IResult<Vec<O>> { move |mut i:&[u8]| { let mut r = Vec::new(); while let Ok((xi, x)) = p(i) { r.push(x); i = xi; } Ok((i, r)) } } pub fn many1<'a, O>(p: impl Fn(&'a[u8]) -> IResult<O>) -> impl Fn(&'a[u8]) -> IResult<Vec<O>> { move |i:&[u8]| { let mut r = Vec::with_capacity(1); let (mut i, x) = p(i)?; // need at least one r.push(x); while let Ok((xi, x)) = p(i) { r.push(x); i = xi; } Ok((i, r)) } } pub fn alt2<'a, O>(a: impl Fn(&'a[u8]) -> IResult<O>, b: impl Fn(&'a[u8]) -> IResult<O>) -> impl Fn(&'a[u8]) -> IResult<O> { move |i:&[u8]| { match a(i) { Ok(x) => Ok(x), _ => b(i), // could compose an error... chose not to. } } } pub fn verify<'a, O>(p: impl Fn(&'a[u8]) -> IResult<O>, f: impl Fn(&O) -> bool) -> impl Fn(&'a[u8])-> IResult<O> { move |i:&[u8]| { let (pi, r) = p(i)?; if f(&r) { Ok((pi, r)) } else { Err(Error::new(i, ErrorKind::Verify)) } } } pub fn map<'a, O1, O2>(p: impl Fn(&'a[u8]) -> IResult<O1>, f: impl Fn(O1) -> O2) -> impl Fn(&'a[u8]) -> IResult<O2> { move |i:&[u8]| { let (pi, r) = p(i)?; Ok((pi, f(r))) } } pub fn many_till<'a, O1, O2>(first: impl Fn(&'a[u8]) -> IResult<O1>, second: impl Fn(&'a[u8]) -> IResult<O2>) -> impl Fn(&'a[u8]) -> IResult<(Vec<O1>, O2)> { move |mut i:&[u8]| { let mut v = Vec::new(); loop { if let Ok((i, y)) = second(i) { return Ok((i, (v, y))); } let (xi, x) = first(i)?; v.push(x); i = xi; } // unreachable!(); } } pub fn eof(i:&[u8]) -> IResult<()> { if i.is_empty() { Ok((i, ())) } else { Err(Error::new(i, ErrorKind::Eof)) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_take() { let data = b"1234567"; let r = take(3)(data); assert!(r.is_ok()); let r = r.unwrap(); assert_eq!(r.0, b"4567"); assert_eq!(r.1, b"123"); } #[test] fn test_take_too_much() { let data = b"1234567"; let r = take(8)(data); assert!(r.is_err()); let data = b""; let r = take(1)(data); assert!(r.is_err()); } #[test] fn test_take_until() { let data = b"123\0456"; let r = take_until("\0")(data); assert!(r.is_ok()); let r = r.unwrap(); assert_eq!(r.0, b"\0456"); assert_eq!(r.1, b"123"); } #[test] fn test_many0() { let data = b"123456789ab"; let r = many0(take(3))(data); assert!(r.is_ok()); let r = r.unwrap(); assert_eq!(r.0, b"ab"); assert_eq!(r.1, vec![b"123", b"456", b"789"]); let data = b"ab"; let r = many0(take(3))(data); assert!(r.is_ok()); let r = r.unwrap(); assert_eq!(r.0, b"ab"); assert!(r.1.is_empty()); } #[test] fn test_many1() { let data = b"ab"; let r = many1(take(3))(data); assert!(r.is_err()); let data = b"123ab"; let r = many1(take(3))(data); assert!(r.is_ok()); let r = r.unwrap(); assert_eq!(r.0, b"ab"); assert_eq!(r.1.len(), 1); assert_eq!(r.1, vec![b"123"]); } #[test] fn test_u32() { let data = b"\x11\x22\x33\x44"; let r = u32(Endianness::Little)(data); assert!(r.is_ok()); let _r = r.unwrap(); } #[test] fn test_u16() { let data = b"\x11\x22\x33\x44"; let r = u16(Endianness::Little)(data); assert!(r.is_ok()); let _r = r.unwrap(); } #[test] fn test_verify() { let data = b"ab"; let r = verify(take(1), |x| x == b"a")(data); assert!(r.is_ok()); let r = r.unwrap(); assert_eq!(r.0, b"b"); assert_eq!(r.1, b"a"); let data = b"ab"; let r = verify(take(1), |x| x == b"b")(data); assert!(r.is_err()); } #[test] fn test_byte() { let data = b"\0ab"; let r = byte(0)(data); assert!(r.is_ok()); let r = r.unwrap(); assert_eq!(r.0, b"ab"); assert_eq!(r.1, 0); } #[test] fn test_map() { let data = b"\0ab"; let r = map(byte(0), |x| x+1)(data); assert!(r.is_ok()); let r = r.unwrap(); assert_eq!(r.0, b"ab"); assert_eq!(r.1, 1); } #[test] fn test_tag() { let data = b"123abcde"; let r = tag(b"123")(data); assert!(r.is_ok()); let r = r.unwrap(); assert_eq!(r.0, b"abcde"); assert_eq!(r.1, b"123"); let r = tag(b"abc")(data); assert!(r.is_err()); } #[test] fn test_many_till() { let data = b"121212abc"; let r = many_till(tag(b"12"), byte(b'a'))(data); assert!(r.is_ok()); let r = r.unwrap(); assert_eq!(r.0, b"bc"); assert_eq!(r.1.0, vec![b"12", b"12", b"12"]); assert_eq!(r.1.1, b'a'); } #[test] fn test_take_at_end() { let data = b"123"; let r = take(3)(data); assert!(r.is_ok()); let r = r.unwrap(); assert_eq!(r.0, b""); assert_eq!(r.1, b"123"); } #[test] fn test_many_till_eof() { let data = b"121212ab"; let r = many_till(alt2(tag(b"12"), tag(b"ab")), eof)(data); assert!(r.is_ok()); let r = r.unwrap(); assert_eq!(r.0, b""); assert_eq!(r.1.0, vec![b"12", b"12", b"12", b"ab"]); assert_eq!(r.1.1, ()); let data = b"121212ab1"; let r = many_till(alt2(tag(b"12"), tag(b"ab")), eof)(data); assert!(r.is_err()); let data = b"121212ab"; let r = many_till(take(2), eof)(data); assert!(r.is_ok()); let r = r.unwrap(); assert_eq!(r.0, b""); assert_eq!(r.1.0, vec![b"12", b"12", b"12", b"ab"]); assert_eq!(r.1.1, ()); } }
use std::{i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64}; use std::io::stdin; fn main() { println!("Max i8={}", i8::MAX); println!("Min i8={}\n", i8::MIN); println!("Max i16={}", i16::MAX); println!("Min i16={}\n", i16::MIN); println!("Max i32={}", i32::MAX); println!("Min i32={}\n", i32::MIN); println!("Max i64={}", i64::MAX); println!("Min i64={}\n", i64::MIN); println!("Max u8={}", u8::MAX); println!("Min u8={}\n", u8::MIN); println!("Max u16={}", u16::MAX); println!("Min u16={}\n", u16::MIN); println!("Max u32={}", u32::MAX); println!("Min u32={}\n", u32::MIN); println!("Max u64={}", u64::MAX); println!("Min u64={}\n", u64::MIN); println!("Max isize={}", isize::MAX); println!("Min isize={}\n", isize::MIN); println!("Max usize={}", usize::MAX); println!("Min usize={}\n", usize::MIN); println!("Max f32={}", f32::MAX); println!("Min f32={}\n", f32::MIN); println!("Max f64={}", f64::MAX); println!("Min f64={}\n", f64::MIN); }
use std::cmp; use std::intrinsics::unlikely; use std::ptr::{self, NonNull}; use intrusive_collections::{LinkedListLink, UnsafeRef}; use liblumen_alloc_macros::*; use liblumen_core::alloc::mmap; use liblumen_core::alloc::prelude::*; use liblumen_core::alloc::size_classes::{SizeClass, SizeClassIndex}; use liblumen_core::locks::RwLock; use crate::blocks::ThreadSafeBlockBitSubset; use crate::carriers::{superalign_down, SUPERALIGNED_CARRIER_SIZE}; use crate::carriers::{SingleBlockCarrier, SlabCarrier}; use crate::carriers::{SingleBlockCarrierList, SlabCarrierList}; /// Like `StandardAlloc`, `SegmentedAlloc` splits allocations into two major categories, /// multi-block carriers up to a certain threshold, after which allocations use single-block /// carriers. /// /// However, `SegmentedAlloc` differs in some key ways: /// /// - The multi-block carriers are allocated into multiple size classes, where each carrier belongs /// to a size class and therefore only fulfills allocation requests for blocks of uniform size. /// - The single-block carrier threshold is statically determined based on the maximum size class /// for the multi-block carriers and is therefore not configurable. /// /// Each size class for multi-block carriers contains at least one carrier, and new carriers are /// allocated as needed when the carrier(s) for a size class are unable to fulfill allocation /// requests. /// /// Allocations of blocks in multi-block carriers are filled using address order for both carriers /// and blocks to reduce fragmentation and improve allocation locality for allocations that fall /// within the same size class. #[derive(SizeClassIndex)] pub struct SegmentedAlloc { sbc_threshold: usize, sbc: RwLock<SingleBlockCarrierList>, classes: Box<[RwLock<SlabCarrierList>]>, } impl SegmentedAlloc { /// Create a new instance of this allocator pub fn new() -> Self { // Initialize to default set of empty slab lists let mut classes = Vec::with_capacity(Self::NUM_SIZE_CLASSES); // Initialize every size class with a single slab carrier for size_class in Self::SIZE_CLASSES.iter() { let mut list = SlabCarrierList::default(); let slab = unsafe { Self::create_slab_carrier(*size_class).unwrap() }; list.push_front(unsafe { UnsafeRef::from_raw(slab) }); classes.push(RwLock::new(list)); } Self { sbc_threshold: Self::MAX_SIZE_CLASS.to_bytes(), sbc: RwLock::default(), classes: classes.into_boxed_slice(), } } /// Creates a new, empty slab carrier, unlinked to the allocator /// /// The carrier is allocated via mmap on supported platforms, or the system /// allocator otherwise. /// /// NOTE: You must make sure to add the carrier to the free list of the /// allocator, or it will not be used, and will not be freed unsafe fn create_carrier( size_class: SizeClass, ) -> Result<*mut SlabCarrier<LinkedListLink, ThreadSafeBlockBitSubset>, AllocError> { let size = SUPERALIGNED_CARRIER_SIZE; assert!(size_class.to_bytes() < size); let carrier_layout = Layout::from_size_align_unchecked(size, size); // Allocate raw memory for carrier let ptr = mmap::map(carrier_layout)?; // Initialize carrier in memory let carrier = SlabCarrier::init(ptr.as_ptr(), size, size_class); // Return an unsafe ref to this carrier back to the caller Ok(carrier) } } unsafe impl Allocator for SegmentedAlloc { #[inline] fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { if layout.size() >= self.sbc_threshold { return unsafe { self.alloc_large(layout) }; } unsafe { self.alloc_sized(layout) } } #[inline] unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { if layout.size() >= self.sbc_threshold { // This block would have to be in a single-block carrier return self.dealloc_large(ptr.as_ptr()); } self.dealloc_sized(ptr, layout); } #[inline] unsafe fn grow( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { if old_layout.size() >= self.sbc_threshold { // This was a single-block carrier // // Even if the new size would fit in a multi-block carrier, we're going // to keep the allocation in the single-block carrier, to avoid the extra // complexity, as there is little payoff return self.realloc_large(ptr, old_layout, new_layout); } self.realloc_sized(ptr, old_layout, new_layout) } #[inline] unsafe fn shrink( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { if old_layout.size() >= self.sbc_threshold { // This was a single-block carrier // // Even if the new size would fit in a multi-block carrier, we're going // to keep the allocation in the single-block carrier, to avoid the extra // complexity, as there is little payoff return self.realloc_large(ptr, old_layout, new_layout); } self.realloc_sized(ptr, old_layout, new_layout) } } impl SegmentedAlloc { /// This function handles allocations which exceed the single-block carrier threshold unsafe fn alloc_large(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { // Ensure allocated region has enough space for carrier header and aligned block let data_layout = layout.clone(); let data_layout_size = data_layout.size(); let carrier_layout = Layout::new::<SingleBlockCarrier<LinkedListLink>>(); let (carrier_layout, data_offset) = carrier_layout.extend(data_layout).unwrap(); // Track total size for carrier metadata let size = carrier_layout.size(); // Allocate region let ptr = mmap::map(carrier_layout)?; // Get pointer to carrier header location let carrier = ptr.as_ptr() as *mut SingleBlockCarrier<LinkedListLink>; // Write initial carrier header ptr::write( carrier, SingleBlockCarrier { size, layout, link: LinkedListLink::new(), }, ); // Get pointer to data region in allocated carrier+block let data = (carrier as *mut u8).add(data_offset); // Cast carrier pointer to UnsafeRef and add to linked list // This implicitly mutates the link in the carrier let carrier = UnsafeRef::from_raw(carrier); let mut sbc = self.sbc.write(); sbc.push_front(carrier); let non_null_byte_slice = NonNull::slice_from_raw_parts(NonNull::new_unchecked(data), data_layout_size); // Return data pointer Ok(non_null_byte_slice) } unsafe fn realloc_large( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { // Allocate new carrier let non_null_byte_slice = self.alloc_large(new_layout)?; // Copy old data into new carrier let old_ptr = ptr.as_ptr(); let old_size = old_layout.size(); ptr::copy_nonoverlapping( old_ptr, non_null_byte_slice.as_mut_ptr(), cmp::min(old_size, non_null_byte_slice.len()), ); // Free old carrier self.dealloc_large(old_ptr); // Return new carrier Ok(non_null_byte_slice) } /// This function handles allocations which exceed the single-block carrier threshold unsafe fn dealloc_large(&self, ptr: *const u8) { // In the case of single-block carriers, // we must walk the list until we find the owning carrier let mut sbc = self.sbc.write(); let mut cursor = sbc.front_mut(); loop { let next = cursor.get(); debug_assert!(next.is_some(), "invalid free of carrier"); let carrier = next.unwrap(); if !carrier.owns(ptr) { cursor.move_next(); continue; } let carrier_ptr = carrier as *const _ as *mut u8; // Calculate the layout of the allocated carrier // - First, get layout of carrier header // - Extend the layout with the block layout to get the original layout used in // `try_alloc` let (layout, _) = Layout::new::<SingleBlockCarrier<LinkedListLink>>() .extend(carrier.layout()) .unwrap(); // Unlink the carrier from the linked list let _ = cursor.remove(); // Release memory for carrier to OS mmap::unmap(carrier_ptr, layout); return; } } } impl SegmentedAlloc { /// Creates a new, empty slab carrier, unlinked to the allocator /// /// The carrier is allocated via mmap on supported platforms, or the system /// allocator otherwise. /// /// NOTE: You must make sure to add the carrier to the free list of the /// allocator, or it will not be used, and will not be freed unsafe fn create_slab_carrier( size_class: SizeClass, ) -> Result<*mut SlabCarrier<LinkedListLink, ThreadSafeBlockBitSubset>, AllocError> { let size = SUPERALIGNED_CARRIER_SIZE; assert!(size_class.to_bytes() < size); let carrier_layout = Layout::from_size_align_unchecked(size, size); // Allocate raw memory for carrier let ptr = mmap::map(carrier_layout)?; // Initialize carrier in memory let carrier = SlabCarrier::init(ptr.as_ptr(), size, size_class); // Return an unsafe ref to this carrier back to the caller Ok(carrier) } #[inline] unsafe fn alloc_sized(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { // Ensure allocated region has enough space for carrier header and aligned block let size = layout.size(); if unlikely(size > Self::MAX_SIZE_CLASS.to_bytes()) { return Err(AllocError); } let size_class = self.size_class_for_unchecked(size); let index = self.index_for(size_class); let carriers = self.classes[index].read(); for carrier in carriers.iter() { if let Ok(ptr) = carrier.alloc_block() { return Ok(NonNull::slice_from_raw_parts(ptr, size_class.to_bytes())); } } drop(carriers); // No carriers had availability, create a new carrier, locking // the carrier list for this size class while we do so, to avoid // other readers from trying to create their own carriers at the // same time let mut carriers = self.classes[index].write(); let carrier_ptr = Self::create_carrier(size_class)?; let carrier = &mut *carrier_ptr; // This should never fail, but we only assert that in debug mode let result = carrier.alloc_block(); debug_assert!(result.is_ok()); carriers.push_front(UnsafeRef::from_raw(carrier_ptr)); result.map(|data| NonNull::slice_from_raw_parts(data, size_class.to_bytes())) } #[inline] unsafe fn realloc_sized( &self, ptr: NonNull<u8>, old_layout: Layout, new_layout: Layout, ) -> Result<NonNull<[u8]>, AllocError> { let new_size = new_layout.size(); if unlikely(new_size > Self::MAX_SIZE_CLASS.to_bytes()) { return Err(AllocError); } let old_size = old_layout.size(); let old_size_class = self.size_class_for_unchecked(old_size); let new_size = new_layout.size(); let new_size_class = self.size_class_for_unchecked(new_size); // If the size is in the same size class, we don't have to do anything if old_size_class == new_size_class { return Ok(NonNull::slice_from_raw_parts( ptr, old_size_class.to_bytes(), )); } // Otherwise we have to allocate in the new size class, // copy to that new block, and deallocate the original block let non_null_byte_slice = self.allocate(new_layout)?; // Copy let copy_size = cmp::min(old_size, non_null_byte_slice.len()); ptr::copy_nonoverlapping(ptr.as_ptr(), non_null_byte_slice.as_mut_ptr(), copy_size); // Deallocate the original block self.deallocate(ptr, old_layout); // Return new block Ok(non_null_byte_slice) } unsafe fn dealloc_sized(&self, ptr: NonNull<u8>, _layout: Layout) { // Locate the owning carrier and deallocate with it let raw = ptr.as_ptr(); // Since the slabs are super-aligned, we can mask off the low // bits of the given pointer to find our carrier let carrier_ptr = superalign_down(raw as usize) as *mut SlabCarrier<LinkedListLink, ThreadSafeBlockBitSubset>; let carrier = &mut *carrier_ptr; carrier.free_block(raw); } } impl Drop for SegmentedAlloc { fn drop(&mut self) { // Drop single-block carriers let mut sbc = self.sbc.write(); // We have to dynamically allocate this vec because the only // other method we have of collecting the pointer/layout combo // is by using a cursor, and the current API is not flexible enough // to allow us to walk the tree freeing each element after we've moved // the cursor past it. Instead we gather all the pointers to clean up // and do it all at once at the end // // NOTE: May be worth exploring a `Drop` impl for the carriers let mut carriers = sbc .iter() .map(|carrier| (carrier as *const _ as *mut _, carrier.layout())) .collect::<Vec<_>>(); // Prevent the list from trying to drop memory that has now been freed sbc.fast_clear(); // Actually drop the carriers for (ptr, layout) in carriers.drain(..) { unsafe { mmap::unmap(ptr, layout); } } // Drop slab carriers let slab_size = SUPERALIGNED_CARRIER_SIZE; let slab_layout = unsafe { Layout::from_size_align_unchecked(slab_size, slab_size) }; for class in self.classes.iter() { // Lock the class list while we free the slabs in it let mut list = class.write(); // Collect the pointers/layouts for all slabs allocated in this class let mut slabs = list .iter() .map(|slab| (slab as *const _ as *mut _, slab_layout.clone())) .collect::<Vec<_>>(); // Clear the list without dropping the elements, since we're handling that list.fast_clear(); // Free the memory for all the slabs for (ptr, layout) in slabs.drain(..) { unsafe { mmap::unmap(ptr, layout) } } } } } unsafe impl Sync for SegmentedAlloc {} unsafe impl Send for SegmentedAlloc {}
use super::component_prelude::*; #[derive(Default)] pub struct CanHover; impl Component for CanHover { type Storage = NullStorage<Self>; }
extern crate env_logger; extern crate tokio_core; extern crate futures; extern crate tokio_solicit; use std::str; use std::io::{self}; use futures::{Future, Stream}; use futures::future::{self}; use tokio_core::reactor::{Core}; use tokio_solicit::client::H2Client; // Shows the usage of `H2Client` when establishing an HTTP/2 connection over cleartext TCP. // Also demonstrates how to stream the body of the response (i.e. get response body chunks as soon // as they are received on a `futures::Stream`. fn cleartext_example() { let mut core = Core::new().expect("event loop required"); let handle = core.handle(); let addr = "127.0.0.1:8080".parse().expect("valid IP address"); let future_client = H2Client::cleartext_connect("localhost", &addr, &handle); let future_response = future_client.and_then(|mut client| { println!("Connection established."); // For the first request, we simply want the full body, without streaming individual body // chunks... let get = client.get(b"/get").into_full_body_response(); let post = client.post(b"/post", b"Hello, world!".to_vec()); // ...for the other, we accumulate the body "manually" in order to do some more // processing for each chunk (for demo purposes). Also, discards the headers. let post = post.and_then(|(_headers, body)| { body.fold(Vec::<u8>::new(), |mut vec, chunk| { println!("receiving a new chunk of size {}", chunk.body.len()); vec.extend(chunk.body.into_iter()); future::ok::<_, io::Error>(vec) }) }); // Finally, yield a future that resolves once both requests are complete (and both bodies // are available). Future::join(get, post) }).map(|(get_response, post_response_body)| { // Convert the bodies to a UTF-8 string let get_res: String = str::from_utf8(&get_response.body).unwrap().into(); let post_res: String = str::from_utf8(&post_response_body).unwrap().into(); // ...and yield a pair of bodies converted to a string. (get_res, post_res) }); let res = core.run(future_response).expect("responses!"); println!("{:?}", res); } /// Fetches the response of google.com over HTTP/2. /// /// The connection is negotiated during the TLS handshake using ALPN. fn alpn_example() { println!(); println!("---- ALPN example ----"); use std::net::{ToSocketAddrs}; let mut core = Core::new().expect("event loop required"); let handle = core.handle(); let addr = "google.com:443" .to_socket_addrs() .expect("unable to resolve the domain name") .next() .expect("no matching ip addresses"); let future_response = H2Client::connect("google.com", &addr, &handle).and_then(|mut client| { // Ask for the homepage... client.get(b"/").into_full_body_response() }); let response = core.run(future_response).expect("unexpected failure"); // Print both the headers and the response body... println!("{:?}", response.headers); // (Recklessly assume it's utf-8!) let body = str::from_utf8(&response.body).unwrap(); println!("{}", body); println!("---- ALPN example end ----"); } fn main() { env_logger::init().expect("logger init is required"); // Establish an http/2 connection (over cleartext TCP), issue a couple of requests, and // stream the body of the response of one of them. Wait until both are ready and then // print the bodies. cleartext_example(); // Show how to estalbish a connection over TLS, while negotiating the use of http/2 over ALPN. alpn_example(); // An additional demo showing how to perform a streaming _request_ (i.e. the body of the // request is streamed out to the server). do_streaming_request(); } fn do_streaming_request() { println!(); println!("---- streaming request example ----"); use std::iter; use tokio_solicit::client::HttpRequestBody; use futures::Sink; let mut core = Core::new().expect("event loop required"); let handle = core.handle(); let addr = "127.0.0.1:8080".parse().expect("valid IP address"); let future_client = H2Client::cleartext_connect("localhost", &addr, &handle); let future_response = future_client.and_then(|mut client| { let (post, tx) = client.streaming_request(b"POST", b"/post", iter::empty()); tx .send(Ok(HttpRequestBody::new(b"HELLO ".to_vec()))) .and_then(|tx| tx.send(Ok(HttpRequestBody::new(b" WORLD".to_vec())))) .and_then(|tx| tx.send(Ok(HttpRequestBody::new(b"!".to_vec())))) .map_err(|_err| io::Error::from(io::ErrorKind::BrokenPipe)) .and_then(|_tx| post.into_full_body_response()) }); let res = core.run(future_response).expect("response"); println!("{:?}", res); println!("---- streaming request example end ----"); }
#[derive(Debug)] pub struct HighScores<'a> { scores: &'a [u32], } impl<'a> HighScores<'a> { pub fn new(scores: &'a [u32]) -> Self { HighScores { scores } } pub fn scores(&self) -> &[u32] { self.scores } pub fn latest(&self) -> Option<u32> { match self.scores.len() { 0 => None, _ => Some(self.scores[self.scores.len() - 1]), } } pub fn personal_best(&self) -> Option<u32> { match self.scores.len() { 0 => None, _ => Some( self.scores .iter() .fold(0, |best, &score| if score > best { score } else { best }), ), } } pub fn personal_top_three(&self) -> Vec<u32> { let mut scores = self.scores.to_vec(); scores.sort_unstable_by(|a, b| b.cmp(a)); scores.truncate(3); scores } }
use alloc::alloc::{AllocError, Allocator, Global, Layout}; use alloc::borrow::{self, Cow}; use core::any::{Any, TypeId}; use core::fmt::{self, Debug, Display}; use core::hash::{Hash, Hasher}; use core::marker::{PhantomData, Unsize}; use core::mem::{self, MaybeUninit}; use core::ops::{Deref, DerefMut}; use core::ptr::{self, DynMetadata, NonNull, Pointee}; use static_assertions::assert_eq_size; #[repr(transparent)] pub struct GcBox<T> where T: ?Sized + 'static, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { ptr: NonNull<u8>, _marker: PhantomData<T>, } assert_eq_size!(GcBox<dyn Any>, *const ()); impl<T: ?Sized + 'static> Copy for GcBox<T> where PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata> { } impl<T: ?Sized + 'static> Clone for GcBox<T> where PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { fn clone(&self) -> Self { Self { ptr: self.ptr, _marker: PhantomData, } } } impl<T> GcBox<T> where T: Any, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { pub fn new(value: T) -> Self { Self::new_in(value, Global).unwrap() } pub fn new_uninit() -> GcBox<MaybeUninit<T>> { Self::new_uninit_in(Global).unwrap() } pub fn new_in<A: Allocator>(value: T, alloc: A) -> Result<Self, AllocError> { let meta = Metadata::new::<T>(&value); let value_layout = Layout::for_value(&value); let (layout, value_offset) = Layout::new::<Metadata>().extend(value_layout).unwrap(); let ptr: NonNull<u8> = alloc.allocate(layout)?.cast(); unsafe { let ptr = NonNull::new_unchecked(ptr.as_ptr().add(value_offset)); let boxed = Self { ptr, _marker: PhantomData, }; ptr::write(header(boxed.ptr.as_ptr()), meta); ptr::write(boxed.ptr.as_ptr().cast(), value); Ok(boxed) } } pub fn new_uninit_in<A: Allocator>(alloc: A) -> Result<GcBox<MaybeUninit<T>>, AllocError> { let value_layout = Layout::new::<T>(); let (layout, value_offset) = Layout::new::<Metadata>().extend(value_layout).unwrap(); let ptr: NonNull<u8> = alloc.allocate(layout)?.cast(); unsafe { let ptr = NonNull::new_unchecked(ptr.as_ptr().add(value_offset)); let meta = Metadata::new::<T>(ptr.as_ptr() as *mut T); let boxed = GcBox { ptr, _marker: PhantomData::<MaybeUninit<T>>, }; ptr::write(header(boxed.ptr.as_ptr()), meta); Ok(boxed) } } } impl<T> GcBox<T> where T: ?Sized + 'static, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { pub fn new_unsize<V: Unsize<T>>(value: V) -> Self { Self::new_unsize_in(value, Global).unwrap() } pub fn new_unsize_in<V: Unsize<T>, A: Allocator>( value: V, alloc: A, ) -> Result<Self, AllocError> { let unsized_: &T = &value; let meta = Metadata::new::<T>(unsized_); let value_layout = Layout::for_value(&value); let (layout, value_offset) = Layout::new::<Metadata>().extend(value_layout).unwrap(); let ptr: NonNull<u8> = alloc.allocate(layout)?.cast(); unsafe { let ptr = NonNull::new_unchecked(ptr.as_ptr().add(value_offset)); let boxed = Self { ptr, _marker: PhantomData, }; ptr::write(header(boxed.ptr.as_ptr().cast()), meta); let ptr: *mut T = boxed.value(); ptr::write(ptr.cast(), value); Ok(boxed) } } /// Converts a GcBox<T> to GcBox<U> where T: Unsize<U> /// /// This is the only type of in-place conversion that is safe for GcBox, /// based on the guarantees provided by the Unsize marker trait. pub fn cast<U>(self) -> GcBox<U> where U: ?Sized + 'static, T: Unsize<U>, PtrMetadata: From<<U as Pointee>::Metadata> + TryInto<<U as Pointee>::Metadata>, { // Get the raw pointer to T let ptr = Self::into_raw(self); // Coerce via Unsize<U> to U, and get the new metadata let meta = { let unsized_: &U = unsafe { &*ptr }; Metadata::new::<U>(unsized_) }; // Construct a new box let boxed = GcBox { ptr: unsafe { NonNull::new_unchecked(ptr as *mut u8) }, _marker: PhantomData, }; // Write the new metadata to the header for our new box let header = header(boxed.ptr.as_ptr()); unsafe { *header = meta; } boxed } /// Extracts the TypeId of an opaque pointee /// /// This is highly unsafe, and is only intended for uses where you are absolutely /// certain the pointer given was allocated by GcBox. /// /// In our case, we have opaque pointers on process heaps that are always allocated via GcBox, /// and we need to be able to cast them back to their original types efficiently. To do so, we /// use a combination of this function, a jump table of type ids, and subsequent unchecked casts. /// This allows for efficient pointer casts while ensuring we don't improperly cast a pointer to /// the wrong type. pub unsafe fn type_id(raw: *mut u8) -> TypeId { debug_assert!(!raw.is_null()); let header = &*header(raw); header.ty } /// Attempts to convert a raw pointer obtained from `GcBox::into_raw` back to a `GcBox<T>` /// /// # Safety /// /// Like `from_raw`, this function is unsafe if the pointer was not allocated by `GcBox`. /// /// NOTE: This function is a bit safer than `from_raw` in that it won't panic if the pointee /// is not of the correct type, instead it returns `Err`. pub unsafe fn try_from_raw(raw: *mut u8) -> Result<Self, ()> { debug_assert!(!raw.is_null()); let meta = &*header(raw); if meta.is::<T>() { Ok(Self { ptr: NonNull::new_unchecked(raw), _marker: PhantomData, }) } else { Err(()) } } /// Converts a raw pointer obtained from `GcBox::into_raw` back to a `GcBox<T>` /// /// # Safety /// /// This function is unsafe, as there is no way to guarantee that the pointer given /// was allocated via `GcBox<T>`, and if it wasn't, then calling this function on it /// is undefined behavior, and almost certainly bad. /// /// NOTE: This function will panic if the pointer was allocated for a different type, /// but it is always safe to call if the pointer was allocated by `GcBox`. pub unsafe fn from_raw(raw: *mut T) -> Self { debug_assert!(!raw.is_null()); let raw = raw.cast(); let meta = &*header(raw); assert!(meta.is::<T>()); Self { ptr: NonNull::new_unchecked(raw), _marker: PhantomData, } } /// This function is absurdly dangerous. /// /// However, it exists and is exposed to the rest of this crate for one purpose: to /// make pointer casts efficient in the OpaqueTerm -> Value conversion, which specifically /// ensures that the pointee is of the correct type before calling this function. It should /// not be used _anywhere else_ unless the same guarantees are upheld. For one-off casts from /// raw opaque pointers, use `from_raw` or `try_from_raw`, which are slightly less efficient, /// but ensure that the pointee is the correct type. /// /// NOTE: Seriously, don't use this. pub unsafe fn from_raw_unchecked(raw: *mut u8) -> Self { debug_assert!(!raw.is_null()); Self { ptr: NonNull::new_unchecked(raw), _marker: PhantomData, } } pub fn into_raw(boxed: Self) -> *mut T { let boxed = mem::ManuallyDrop::new(boxed); (*boxed).value() } #[inline] pub fn as_ptr(boxed: &Self) -> *mut u8 { boxed.ptr.as_ptr() } pub unsafe fn drop_in<A: Allocator>(boxed: Self, alloc: A) { let value: *mut T = boxed.value(); let (layout, value_offset) = Layout::new::<Metadata>() .extend(Layout::for_value_raw(value)) .unwrap(); if layout.size() > 0 { ptr::drop_in_place(value); } let ptr = NonNull::new_unchecked(boxed.ptr.as_ptr().sub(value_offset)); alloc.deallocate(ptr, layout); } #[inline] fn value(&self) -> *mut T { let meta = unsafe { *header(self.ptr.as_ptr()) }; let meta = unsafe { meta.get::<T>() }; ptr::from_raw_parts_mut(self.ptr.as_ptr().cast(), meta) } } impl<T: ?Sized + 'static + Pointee<Metadata = usize>> GcBox<T> { /// Used to cast an unsized type to its sized representation pub fn to_sized<U>(self) -> GcBox<U> where U: Unsize<T> + 'static + Pointee<Metadata = ()>, { let raw = Self::into_raw(self) as *mut U; GcBox { ptr: unsafe { NonNull::new_unchecked(raw as *mut u8) }, _marker: PhantomData, } } } impl GcBox<dyn Any> { /// Attempts to safely cast a GcBox<dyn Any> to GcBox<T> pub fn downcast<T>(self) -> Option<GcBox<T>> where T: Any, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { let raw = Self::into_raw(self); let any: &dyn Any = unsafe { &*raw }; let Some(concrete) = any.downcast_ref::<T>() else { return None; }; let meta = Metadata::new::<T>(concrete); let boxed = GcBox { ptr: unsafe { NonNull::new_unchecked(concrete as *const _ as *mut u8) }, _marker: PhantomData, }; let header = header(boxed.ptr.as_ptr()); unsafe { *header = meta; } Some(boxed) } } impl GcBox<dyn Any + Send> { /// Attempts to safely cast a GcBox<dyn Any> to GcBox<T> pub fn downcast<T>(self) -> Option<GcBox<T>> where T: Any, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { let raw = Self::into_raw(self); let any: &(dyn Any + Send) = unsafe { &*raw }; let Some(concrete) = any.downcast_ref::<T>() else { return None; }; let meta = Metadata::new::<T>(concrete); let boxed = GcBox { ptr: unsafe { NonNull::new_unchecked(concrete as *const _ as *mut u8) }, _marker: PhantomData, }; let header = header(boxed.ptr.as_ptr()); unsafe { *header = meta; } Some(boxed) } } impl GcBox<dyn Any + Send + Sync> { /// Attempts to safely cast a GcBox<dyn Any> to GcBox<T> pub fn downcast<T>(self) -> Option<GcBox<T>> where T: Any, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { let raw = Self::into_raw(self); let any: &(dyn Any + Send + Sync) = unsafe { &*raw }; let Some(concrete) = any.downcast_ref::<T>() else { return None; }; let meta = Metadata::new::<T>(concrete); let boxed = GcBox { ptr: unsafe { NonNull::new_unchecked(concrete as *const _ as *mut u8) }, _marker: PhantomData, }; let header = header(boxed.ptr.as_ptr()); unsafe { *header = meta; } Some(boxed) } } impl<T> GcBox<T> where T: ?Sized + 'static + Pointee<Metadata = usize>, { pub fn with_capacity(cap: usize) -> Self { Self::with_capacity_in(cap, Global).unwrap() } pub fn with_capacity_in<A: Allocator>(cap: usize, alloc: A) -> Result<Self, AllocError> { let empty = ptr::from_raw_parts::<T>(ptr::null() as *const (), cap); let meta = Metadata::new::<T>(empty); let value_layout = unsafe { Layout::for_value_raw(empty) }; let (layout, value_offset) = Layout::new::<Metadata>().extend(value_layout).unwrap(); let ptr: NonNull<u8> = alloc.allocate(layout)?.cast(); unsafe { let ptr = NonNull::new_unchecked(ptr.as_ptr().add(value_offset)); let boxed = Self { ptr, _marker: PhantomData, }; ptr::write(header(boxed.ptr.as_ptr()), meta); Ok(boxed) } } } impl<T> GcBox<[T]> { #[inline] pub fn new_uninit_slice(len: usize) -> GcBox<[MaybeUninit<T>]> { GcBox::new_uninit_slice_in(len, Global).unwrap() } #[inline] pub fn new_uninit_slice_in<A: Allocator>( len: usize, alloc: A, ) -> Result<GcBox<[MaybeUninit<T>]>, AllocError> { GcBox::<[MaybeUninit<T>]>::with_capacity_in(len, alloc) } } impl<T: Clone> GcBox<[T]> { pub fn to_boxed_slice_in<A: Allocator>(slice: &[T], alloc: A) -> Result<Self, AllocError> { let mut boxed = GcBox::<[MaybeUninit<T>]>::with_capacity_in(slice.len(), alloc)?; boxed.write_slice_cloned(slice); Ok(unsafe { boxed.assume_init() }) } } impl<T: Any> GcBox<MaybeUninit<T>> { pub unsafe fn assume_init(self) -> GcBox<T> { let raw = GcBox::into_raw(self); GcBox::from_raw(raw as *mut T) } pub fn write(mut boxed: Self, value: T) -> GcBox<T> { unsafe { (*boxed).write(value); boxed.assume_init() } } } impl<T> GcBox<[MaybeUninit<T>]> { pub unsafe fn assume_init(self) -> GcBox<[T]> { let raw = GcBox::into_raw(self); GcBox::from_raw(raw as *mut [T]) } } impl<T: Copy> GcBox<[MaybeUninit<T>]> { pub fn write_slice(&mut self, src: &[T]) { MaybeUninit::write_slice(&mut **self, src); } } impl<T: Clone> GcBox<[MaybeUninit<T>]> { pub fn write_slice_cloned(&mut self, src: &[T]) { MaybeUninit::write_slice_cloned(&mut **self, src); } } impl<T> Debug for GcBox<T> where T: ?Sized + 'static + Debug, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Debug::fmt(&**self, f) } } impl<T> Display for GcBox<T> where T: ?Sized + 'static + Display, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Display::fmt(&**self, f) } } impl<T> fmt::Pointer for GcBox<T> where T: ?Sized + 'static, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Pointer::fmt(&self.ptr, f) } } impl<T> borrow::Borrow<T> for GcBox<T> where T: ?Sized + 'static, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { fn borrow(&self) -> &T { &**self } } impl<T> borrow::BorrowMut<T> for GcBox<T> where T: ?Sized + 'static, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { fn borrow_mut(&mut self) -> &mut T { &mut **self } } impl<T> AsRef<T> for GcBox<T> where T: ?Sized + 'static, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { fn as_ref(&self) -> &T { &**self } } impl<T> AsMut<T> for GcBox<T> where T: ?Sized + 'static, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { fn as_mut(&mut self) -> &mut T { &mut **self } } impl<T> PartialEq for GcBox<T> where T: ?Sized + PartialEq + 'static, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { #[inline] fn eq(&self, other: &Self) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &Self) -> bool { PartialEq::ne(&**self, &**other) } } impl<T> PartialEq<T> for GcBox<T> where T: ?Sized + PartialEq + 'static, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { #[inline] fn eq(&self, other: &T) -> bool { PartialEq::eq(&**self, other) } #[inline] fn ne(&self, other: &T) -> bool { PartialEq::ne(&**self, other) } } impl<T> PartialOrd<T> for GcBox<T> where T: ?Sized + 'static + PartialOrd, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { #[inline] fn partial_cmp(&self, other: &T) -> Option<core::cmp::Ordering> { PartialOrd::partial_cmp(&**self, other) } #[inline] fn lt(&self, other: &T) -> bool { PartialOrd::lt(&**self, other) } #[inline] fn le(&self, other: &T) -> bool { PartialOrd::le(&**self, other) } #[inline] fn ge(&self, other: &T) -> bool { PartialOrd::ge(&**self, other) } #[inline] fn gt(&self, other: &T) -> bool { PartialOrd::gt(&**self, other) } } impl<T> PartialOrd for GcBox<T> where T: ?Sized + 'static + PartialOrd, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { #[inline] fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { PartialOrd::partial_cmp(&**self, &**other) } #[inline] fn lt(&self, other: &Self) -> bool { PartialOrd::lt(&**self, &**other) } #[inline] fn le(&self, other: &Self) -> bool { PartialOrd::le(&**self, &**other) } #[inline] fn ge(&self, other: &Self) -> bool { PartialOrd::ge(&**self, &**other) } #[inline] fn gt(&self, other: &Self) -> bool { PartialOrd::gt(&**self, &**other) } } impl<T> Ord for GcBox<T> where T: ?Sized + 'static + Ord, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { #[inline] fn cmp(&self, other: &Self) -> core::cmp::Ordering { Ord::cmp(&**self, &**other) } } impl<T> Eq for GcBox<T> where T: ?Sized + 'static + Eq, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { } impl<T> Hash for GcBox<T> where T: ?Sized + 'static + Hash, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { fn hash<H: Hasher>(&self, state: &mut H) { (**self).hash(state); } } impl<T> From<T> for GcBox<T> where T: Any, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { fn from(t: T) -> Self { GcBox::new(t) } } impl<T: Copy> From<&[T]> for GcBox<[T]> { fn from(slice: &[T]) -> Self { let mut boxed = GcBox::<[MaybeUninit<T>]>::with_capacity(slice.len()); boxed.write_slice(slice); unsafe { boxed.assume_init() } } } impl<T: Copy> From<Cow<'_, [T]>> for GcBox<[T]> { #[inline] fn from(cow: Cow<'_, [T]>) -> Self { match cow { Cow::Borrowed(slice) => GcBox::from(slice), Cow::Owned(slice) => GcBox::from(slice.as_slice()), } } } impl<T> Deref for GcBox<T> where T: ?Sized + 'static, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { type Target = T; #[inline] fn deref(&self) -> &Self::Target { let ptr = self.value(); unsafe { &*ptr } } } impl<T> DerefMut for GcBox<T> where T: ?Sized + 'static, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { let ptr = self.value(); unsafe { &mut *ptr } } } impl<Args, F: FnOnce<Args>> FnOnce<Args> for GcBox<F> where F: 'static, PtrMetadata: From<<F as Pointee>::Metadata> + TryInto<<F as Pointee>::Metadata>, { type Output = <F as FnOnce<Args>>::Output; extern "rust-call" fn call_once(self, args: Args) -> Self::Output { let value = unsafe { ptr::read(self.value()) }; <F as FnOnce<Args>>::call_once(value, args) } } impl<Args, F: FnMut<Args>> FnMut<Args> for GcBox<F> where F: 'static, PtrMetadata: From<<F as Pointee>::Metadata> + TryInto<<F as Pointee>::Metadata>, { extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output { <F as FnMut<Args>>::call_mut(&mut **self, args) } } impl<Args, F: Fn<Args>> Fn<Args> for GcBox<F> where F: 'static, PtrMetadata: From<<F as Pointee>::Metadata> + TryInto<<F as Pointee>::Metadata>, { extern "rust-call" fn call(&self, args: Args) -> Self::Output { <F as Fn<Args>>::call(&**self, args) } } fn header(ptr: *mut u8) -> *mut Metadata { unsafe { ptr.sub(mem::size_of::<Metadata>()).cast() } } /// This is a marker type used to indicate that the data pointed to by a GcBox has been /// forwarded to a new location in memory. The metadata for the GcBox contains the new /// location pub struct ForwardingMarker; impl ForwardingMarker { pub const TYPE_ID: TypeId = TypeId::of::<ForwardingMarker>(); } /// This metadata provides enough information to restore a fat pointer from a thin /// pointer, and to cast to and from Opaque #[derive(Copy, Clone)] #[repr(C)] pub struct Metadata { ty: TypeId, meta: PtrMetadata, } impl Metadata { fn new<T: ?Sized + 'static>(raw: *const T) -> Self where PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { let ty = TypeId::of::<T>(); let meta = ptr::metadata(raw); Self { ty, meta: meta.into(), } } /// Creates metadata representing forwarding a pointer to a new location in memory #[allow(dead_code)] fn forward(forwarded: *const ()) -> Self { Self { ty: ForwardingMarker::TYPE_ID, meta: PtrMetadata { forwarded }, } } /// Returns true if this metadata indicates the containing GcBox has been forwarded #[allow(dead_code)] #[inline(always)] fn is_forwarded(&self) -> bool { self.ty == ForwardingMarker::TYPE_ID } /// This function attempts to extract pointer metadata valid for a pointer to type T /// from the current metadata contained in this struct. This is unsafe in that it allows /// coercions between any types that use the same metadata. If coercions between those types /// is safe, then this is fine; but if the coercions imply a different layout in memory, then /// this function is absolutely not safe to be called. It is up to the caller to ensure the /// following: /// /// * This function is only called with the same type as was used to produce the metadata, /// or a type for whom the metadata is equivalent and implies the same layout in memory. /// /// NOTE: Invalid casts between different metadata types are caught, i.e. it is not possible /// to read unsized metadata for a sized type or vice versa, same with trait objects. However, /// the risk is with reading unsized metadata or trait object metadata with incorrect types. unsafe fn get<T>(&self) -> <T as Pointee>::Metadata where T: ?Sized + Pointee, PtrMetadata: From<<T as Pointee>::Metadata> + TryInto<<T as Pointee>::Metadata>, { self.meta .try_into() .unwrap_or_else(|_| panic!("invalid pointer metadata")) } /// Returns true if this metadata is for a value of type T #[inline] fn is<T: ?Sized + 'static>(&self) -> bool { self.ty == TypeId::of::<T>() } } #[derive(Copy, Clone)] #[repr(C)] pub union PtrMetadata { #[allow(dead_code)] forwarded: *const (), size: usize, dynamic: DynMetadata<dyn Any>, dyn_send: DynMetadata<dyn Any + Send>, dyn_send_sync: DynMetadata<dyn Any + Send + Sync>, } impl PtrMetadata { const UNSIZED_FLAG: usize = 1 << ((core::mem::size_of::<usize>() * 8) - 1); #[inline] fn is_sized(&self) -> bool { unsafe { self.size == 0 } } #[inline] fn is_unsized(&self) -> bool { unsafe { self.size & Self::UNSIZED_FLAG == Self::UNSIZED_FLAG } } #[inline] fn is_dyn(&self) -> bool { !(self.is_sized() || self.is_unsized()) } } impl From<()> for PtrMetadata { fn from(_: ()) -> Self { Self { size: 0 } } } impl From<usize> for PtrMetadata { fn from(size: usize) -> Self { Self { size: (size | Self::UNSIZED_FLAG), } } } impl From<DynMetadata<dyn Any>> for PtrMetadata { fn from(dynamic: DynMetadata<dyn Any>) -> Self { let meta = Self { dynamic }; let raw = unsafe { meta.size }; assert_ne!( raw & Self::UNSIZED_FLAG, Self::UNSIZED_FLAG, "dyn metadata conflicts with sized metadata flag" ); meta } } impl From<DynMetadata<dyn Any + Send>> for PtrMetadata { fn from(dyn_send: DynMetadata<dyn Any + Send>) -> Self { let meta = Self { dyn_send }; let raw = unsafe { meta.size }; assert_ne!( raw & Self::UNSIZED_FLAG, Self::UNSIZED_FLAG, "dyn metadata conflicts with sized metadata flag" ); meta } } impl From<DynMetadata<dyn Any + Send + Sync>> for PtrMetadata { fn from(dyn_send_sync: DynMetadata<dyn Any + Send + Sync>) -> Self { let meta = Self { dyn_send_sync }; let raw = unsafe { meta.size }; assert_ne!( raw & Self::UNSIZED_FLAG, Self::UNSIZED_FLAG, "dyn metadata conflicts with sized metadata flag" ); meta } } impl TryInto<()> for PtrMetadata { type Error = core::convert::Infallible; #[inline] fn try_into(self) -> Result<(), Self::Error> { Ok(()) } } impl TryInto<usize> for PtrMetadata { type Error = InvalidPtrMetadata; #[inline] fn try_into(self) -> Result<usize, Self::Error> { if self.is_unsized() { Ok(unsafe { self.size } & !Self::UNSIZED_FLAG) } else { Err(InvalidPtrMetadata) } } } impl TryInto<DynMetadata<dyn Any>> for PtrMetadata { type Error = InvalidPtrMetadata; #[inline] fn try_into(self) -> Result<DynMetadata<dyn Any>, Self::Error> { if self.is_dyn() { Ok(unsafe { self.dynamic }) } else { Err(InvalidPtrMetadata) } } } impl TryInto<DynMetadata<dyn Any + Send>> for PtrMetadata { type Error = InvalidPtrMetadata; #[inline] fn try_into(self) -> Result<DynMetadata<dyn Any + Send>, Self::Error> { if self.is_dyn() { Ok(unsafe { self.dyn_send }) } else { Err(InvalidPtrMetadata) } } } impl TryInto<DynMetadata<dyn Any + Send + Sync>> for PtrMetadata { type Error = InvalidPtrMetadata; #[inline] fn try_into(self) -> Result<DynMetadata<dyn Any + Send + Sync>, Self::Error> { if self.is_dyn() { Ok(unsafe { self.dyn_send_sync }) } else { Err(InvalidPtrMetadata) } } } pub struct InvalidPtrMetadata; #[cfg(test)] mod test { use super::*; struct Cons { head: usize, tail: usize, } struct Tuple { _header: usize, data: [usize], } impl Tuple { fn len(&self) -> usize { self.data.len() } fn set_element(&mut self, index: usize, value: usize) { self.data[index] = value; } fn get_element(&self, index: usize) -> usize { self.data[index] } fn get(&self, index: usize) -> Option<usize> { self.data.get(index).copied() } } struct Closure<Args>(extern "rust-call" fn(Args) -> Option<usize>); impl<Args> FnOnce<Args> for Closure<Args> { type Output = Option<usize>; extern "rust-call" fn call_once(self, args: Args) -> Self::Output { (self.0)(args) } } impl<Args> FnMut<Args> for Closure<Args> { extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output { (self.0)(args) } } impl<Args> Fn<Args> for Closure<Args> { extern "rust-call" fn call(&self, args: Args) -> Self::Output { (self.0)(args) } } extern "rust-call" fn unboxed_closure(args: (GcBox<Tuple>, usize)) -> Option<usize> { let tuple = args.0; let index = args.1; tuple.get(index) } #[test] fn can_gcbox_pods() { let value = GcBox::new(Cons { head: 1, tail: 2 }); assert_eq!(value.head, 1); assert_eq!(value.tail, 2); } #[test] fn can_gcbox_dsts() { let mut value = GcBox::<Tuple>::with_capacity(2); value.set_element(0, 42); value.set_element(1, 11); assert_eq!(value.len(), 2); assert_eq!(value.get_element(0), 42); assert_eq!(value.get_element(1), 11); } #[test] fn can_gcbox_downcast_any() { let value = GcBox::<dyn Any>::new_unsize(Cons { head: 1, tail: 2 }); assert!(value.is::<Cons>()); let result = value.downcast::<Cons>(); assert!(result.is_some()); let cons = result.unwrap(); assert_eq!(cons.head, 1); assert_eq!(cons.tail, 2); } #[test] fn cant_gcbox_downcast_any_improperly() { let value = GcBox::<dyn Any>::new_unsize(Cons { head: 1, tail: 2 }); assert!(!value.is::<usize>()); let result = value.downcast::<usize>(); assert!(result.is_none()); } #[test] fn can_gcbox_unboxed_closures() { let mut tuple = GcBox::<Tuple>::with_capacity(1); tuple.set_element(0, 42); let closure = GcBox::new(Closure(unboxed_closure)); let result = closure(tuple, 0); assert_eq!(result, Some(42)); } #[test] fn can_gcbox_closures() { let mut tuple = GcBox::<Tuple>::with_capacity(1); tuple.set_element(0, 42); let closure = GcBox::new(|tuple: GcBox<Tuple>, index| tuple.get(index)); let result = closure(tuple, 0); assert_eq!(result, Some(42)); } }
#![allow(unused)] use super::configs::WindowConfig; use super::osspecific::osspecific::OsSpecific; use super::vulkancore::VulkanCore; #[cfg(feature = "audio")] use super::soundhandler::SoundHandler; use crate::prelude::*; use presentation::{input::eventsystem::PresentationEventType, prelude::*}; use std::collections::HashMap; use std::env::set_var; use std::path::Path; use std::rc::Rc; use std::sync::{Arc, Mutex, MutexGuard, RwLock, RwLockReadGuard}; use std::time::{Duration, Instant}; pub trait ContextObject { fn name(&self) -> &str; fn update(&self) -> VerboseResult<()>; fn event(&self, event: PresentationEventType) -> VerboseResult<()>; } pub struct Context { core: VulkanCore, pub(crate) presentation: PresentationCore, render_core: Box<dyn RenderCore + Send + Sync>, #[cfg(feature = "audio")] sound_handler: Mutex<SoundHandler>, os_specific: OsSpecific, application_start_time: Instant, context_object: RwLock<Option<Arc<dyn ContextObject + Send + Sync>>>, fallback: Mutex<Option<Box<dyn Fn(&str) -> VerboseResult<()> + Send + Sync>>>, push_events: Mutex<Vec<Box<dyn FnOnce() -> VerboseResult<()> + Send + Sync>>>, // queue timer last_check: Mutex<Duration>, } impl Context { pub fn new<'a>() -> ContextBuilder { ContextBuilder::default() } pub fn set_context_object( &self, context_object: Option<Arc<dyn ContextObject + Send + Sync>>, ) -> VerboseResult<()> { *self.context_object.write()? = context_object; Ok(()) } pub fn window_config<'a>(&'a self) -> VerboseResult<WindowConfig<'a>> { match self.presentation.backend() { PresentationBackend::Window(wsi) => Ok(WindowConfig::new(wsi)), PresentationBackend::OpenXR(_xri) => { create_error!("OpenXR backend has no window config") } PresentationBackend::OpenVR(_vri) => { create_error!("OpenVR backend has no window config") } } } pub fn push_event( &self, event: impl FnOnce() -> VerboseResult<()> + 'static + Send + Sync, ) -> VerboseResult<()> { self.push_events.lock()?.push(Box::new(event)); Ok(()) } #[cfg(feature = "audio")] pub fn sound(&self) -> VerboseResult<MutexGuard<'_, SoundHandler>> { Ok(self.sound_handler.lock()?) } pub fn run(&self) -> VerboseResult<()> { 'running: loop { match self.presentation.event_system().poll_events() { Ok(res) => { if !res { break 'running; } } Err(err) => { if let Some(fallback) = self.fallback.lock()?.as_ref() { (fallback)(&err.message())?; } } } if let Err(err) = self.update() { if let Some(fallback) = &self.fallback.lock()?.as_ref() { (fallback)(&err.message())?; } } if !self.render_core.next_frame()? { break 'running; } } self.set_context_object(None)?; self.render_core.clear_scenes()?; self.render_core.clear_post_processing_routines()?; Ok(()) } pub fn render_core(&self) -> &Box<dyn RenderCore + Send + Sync> { &self.render_core } pub fn set_fallback<F>(&self, fallback: F) -> VerboseResult<()> where F: Fn(&str) -> VerboseResult<()> + 'static + Send + Sync, { *self.fallback.lock()? = Some(Box::new(fallback)); Ok(()) } pub fn close(&self) -> VerboseResult<()> { self.presentation.event_system().quit() } pub fn device(&self) -> &Arc<Device> { &self.core.device() } pub fn queue(&self) -> &Arc<Mutex<Queue>> { self.core.queue() } pub fn time(&self) -> Duration { self.application_start_time.elapsed() } pub fn controllers(&self) -> VerboseResult<RwLockReadGuard<'_, Vec<Arc<RwLock<Controller>>>>> { self.presentation.event_system().controllers() } pub fn active_controller(&self) -> VerboseResult<Option<Arc<RwLock<Controller>>>> { self.presentation.event_system().active_controller() } pub fn set_active_controller(&self, controller: &Arc<RwLock<Controller>>) -> VerboseResult<()> { self.presentation .event_system() .set_active_controller(controller) } } impl std::fmt::Debug for Context { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Context {{ TODO }}") } } impl Context { #[inline] fn update(&self) -> VerboseResult<()> { if let Some(context_object) = self.context_object.read()?.as_ref() { if let Err(err) = context_object.update() { return Err(err); } } let mut push_events = self.push_events.lock()?; while let Some(event) = push_events.pop() { event()?; } let one_second = Duration::from_secs(1); let mut last_check = self.last_check.lock()?; if (self.time() - *last_check) > one_second { *last_check += one_second; #[cfg(feature = "audio")] { self.sound()?.check_clear_queue()?; } } Ok(()) } } pub struct ContextBuilder { #[cfg(feature = "audio")] volume_info: Option<VolumeInfo>, #[cfg(any(feature = "openvr", feature = "openxr"))] vr_mode: Option<VRMode>, #[cfg(feature = "openxr")] openxr_runtime_json: Option<String>, enable_backtrace: bool, // app info app_info: ApplicationInfo, // window information window_create_info: WindowCreateInfo, // os specifics os_specific_config: OsSpecificConfig, // vulkan core settings device_features: DeviceFeatures, sample_count: VkSampleCountFlags, enable_raytracing: bool, render_core_create_info: RenderCoreCreateInfo, // vulkan debug extension selection vulkan_debug_info: VulkanDebugInfo, // input settings enable_mouse: bool, enable_keyboard: bool, enable_controller: bool, controller_deadzone: f32, } impl<'a> Default for ContextBuilder { fn default() -> Self { ContextBuilder { #[cfg(feature = "audio")] volume_info: None, #[cfg(any(feature = "openvr", feature = "openxr"))] vr_mode: None, #[cfg(feature = "openxr")] openxr_runtime_json: None, enable_backtrace: false, // app info app_info: ApplicationInfo { application_name: "not set".to_string(), application_version: 0, engine_name: "not set".to_string(), engine_version: 0, }, // window information window_create_info: WindowCreateInfo { title: "Vulkan Application".to_string(), width: 800, height: 600, fullscreen: false, requested_display: None, }, // os specifics os_specific_config: OsSpecificConfig::default(), // vulkan core settings device_features: DeviceFeatures::default(), sample_count: VK_SAMPLE_COUNT_1_BIT, enable_raytracing: false, render_core_create_info: RenderCoreCreateInfo { format: VK_FORMAT_R8G8B8A8_UNORM, usage: 0.into(), vsync: false, }, // vulkan debug extension selection vulkan_debug_info: VulkanDebugInfo::default(), // input settings enable_mouse: false, enable_keyboard: false, enable_controller: false, controller_deadzone: 0.2, } } } impl ContextBuilder { #[cfg(feature = "audio")] pub fn set_volume_info(mut self, volume_info: VolumeInfo) -> Self { self.volume_info = Some(volume_info); self } #[cfg(any(feature = "openvr", feature = "openxr"))] pub fn set_vr_mode(mut self, vr_mode: VRMode) -> Self { self.vr_mode = Some(vr_mode); self } #[cfg(feature = "openxr")] pub fn set_openxr_json(mut self, openxr_json_path: &str) -> Self { self.openxr_runtime_json = Some(openxr_json_path.to_string()); self } pub fn set_app_info(mut self, app_info: ApplicationInfo) -> Self { self.app_info = app_info; self } pub fn set_window_info(mut self, window_info: WindowCreateInfo) -> Self { self.window_create_info = window_info; self } pub fn set_os_specific_info(mut self, os_specific: OsSpecificConfig) -> Self { self.os_specific_config = os_specific; self } pub fn set_device_features(mut self, device_features: DeviceFeatures) -> Self { self.device_features = device_features; self } pub fn set_sample_count(mut self, sample_count: VkSampleCountFlags) -> Self { self.sample_count = sample_count; self } pub fn enable_ray_tracing(mut self) -> Self { self.enable_raytracing = true; self } pub fn set_render_core_info( mut self, format: VkFormat, usage: impl Into<VkImageUsageFlagBits>, vsync: bool, ) -> Self { self.render_core_create_info = RenderCoreCreateInfo { format, usage: usage.into(), vsync, }; self } pub fn enable_backtrace(mut self) -> Self { self.enable_backtrace = true; self } pub fn set_vulkan_debug_info(mut self, vulkan_debug_info: VulkanDebugInfo) -> Self { self.vulkan_debug_info = vulkan_debug_info; self } pub fn enable_mouse(mut self) -> Self { self.enable_mouse = true; self } pub fn enable_keyboard(mut self) -> Self { self.enable_keyboard = true; self } pub fn enable_controller(mut self) -> Self { self.enable_controller = true; self } pub fn set_controller_deadzone(mut self, deadzone: f32) -> Self { self.controller_deadzone = deadzone; self } pub fn build(self) -> VerboseResult<Arc<Context>> { if self.enable_backtrace { // set environment variable for Rust-debug-trace set_var("RUST_BACKTRACE", "1"); } #[cfg(feature = "openxr")] self.use_openxr_json(); let vr_mode = self.get_vr_mode(); let presentation = PresentationCore::new(vr_mode, &self.window_create_info, self.app_info.clone())?; // vulkan core objects (VkInstance, VkDevice, ...) let core = VulkanCore::new( &presentation, &self.vulkan_debug_info, &self.app_info, self.device_features, )?; let os_specific = OsSpecific::new(&self.os_specific_config); let (render_core, _target_mode) = create_render_core( &presentation, core.device(), core.queue(), self.render_core_create_info, )?; let context = Arc::new(Context { core, presentation, render_core, #[cfg(feature = "audio")] sound_handler: Mutex::new(self.create_sound_handler()?), os_specific, application_start_time: Instant::now(), context_object: RwLock::new(None), fallback: Mutex::new(None), push_events: Mutex::new(Vec::new()), last_check: Mutex::new(Duration::from_secs(0)), }); let weak_context = Arc::downgrade(&context); context .presentation .event_system() .set_callback(move |event| { if let Some(context) = weak_context.upgrade() { // TODO: remove stupid workaround let mut ctx_obj = None; if let Some(context_object) = context.context_object.read()?.as_ref() { ctx_obj = Some(context_object.clone()); } if let Some(context_object) = ctx_obj { context_object.event(event)?; } } Ok(()) }); if self.enable_mouse { context.presentation.event_system().enable_mouse()?; } if self.enable_keyboard { context.presentation.event_system().enable_keyboard()?; } if self.enable_controller { context.presentation.event_system().enable_controller()?; } Ok(context) } #[cfg(feature = "openxr")] fn use_openxr_json(&self) { if let Some(openxr_json) = &self.openxr_runtime_json { // set environment variable for OpenXR set_var("XR_RUNTIME_JSON", openxr_json); } } fn get_vr_mode(&self) -> Option<VRMode> { #[cfg(any(feature = "openvr", feature = "openxr"))] // if we requested a VR mode, check if it is available match self.vr_mode { Some(vr_mode) => { let available_vr_modes = PresentationCore::enabled_vr_modes(); // if requested VR mode is enabled, use it if available_vr_modes.contains(&vr_mode) { return Some(vr_mode); } // fallback to the first available else if !available_vr_modes.is_empty() { let mode = available_vr_modes[0]; println!( "Requested VRMode ({:?}) is not available, using {:?} instead.", vr_mode, mode ); return Some(mode); } // use default desktop, as last resort else { println!("No VRMode present, fallback to Window"); return None; } } None => { return None; } } #[cfg(not(any(feature = "openvr", feature = "openxr")))] None } #[cfg(feature = "audio")] fn create_sound_handler(&self) -> VerboseResult<SoundHandler> { match self.volume_info { Some(volume_info) => SoundHandler::new(volume_info), None => create_error!("No volume info present, consider disabling 'audio' feature"), } } }
extern crate rand; extern crate minifb; extern crate ears; extern crate config; mod chip8; mod tests; mod modules; use chip8::cpu::Cpu; use std::{env, thread}; use std::io::Read; use std::io::Result; use std::fs::File; use std::path::Path; use std::time::Duration; use crate::modules::config::Config; fn main() { let rom_path = env::args().skip(1).next().expect("Usage: ./crust8cean <path-to-rom>"); let rom = read_rom(&mut File::open(&Path::new(&rom_path)).unwrap()) .expect("rom not found"); let config = Config::new("config"); println!("read config: {:?}", config); let mut cpu = Cpu::new(&rom, config); println!("crust8cean starting..."); thread::sleep(Duration::from_millis(3000)); loop { if !cpu.is_running() { break; } cpu.run(); } println!(); println!("Program finished!"); // TODO print some stats? println!(); println!("Total cycles emulated: {}", cpu.get_total_cycles()); println!("Times screen drawn: {}", cpu.get_times_screen_rendered()); } fn read_rom(r: &mut Read) -> Result<Vec<u8>> { let mut data = Vec::new(); r.read_to_end(&mut data)?; return Ok(data); }
pub use crate::board::Board; pub use crate::ai::AI; use text_io::read; pub struct HumanPlayer { board: Board, } impl AI for HumanPlayer { fn get_move(&mut self, last_move : i64) -> i64 { if last_move != -1 { self.board.make_move(last_move as usize); } self.board.pretty_print(); loop { println!("{:?} to move", self.board.get_to_move()); println!("Enter a square or 900 to resign: "); let i: usize = read!(); if i == 900 { return -1; } else { if self.board.make_move(i as usize) { return i as i64; } else { println!("{} is an illegal move", i); } } } } fn cleanup(&mut self) {} } impl HumanPlayer { pub fn new(max_level_: usize) -> HumanPlayer { HumanPlayer { board: Board::new(max_level_) } } }
use std::io; use std::convert::TryInto; use std::collections::HashSet; use std::collections::HashMap; use std::collections::LinkedList; use std::cmp::Reverse; use std::cmp; use std::str::FromStr; use std::iter::FromIterator; use std::time::Instant; use rand::Rng; use rand::seq::SliceRandom; use rand::thread_rng; const MAX_X:u8 = 15; const MAX_Y:u8 = 15; const PATH_INIT:f64 = 1.0; #[derive( Copy, Clone,Debug)] enum Direction { N,S,E,W, } impl Default for Direction { fn default() -> Self { Direction::N } } impl FromStr for Direction { type Err = (); fn from_str(s: &str) -> Result<Self, ()> { match s { "N" => Ok(Direction::N), "S" => Ok(Direction::S), "E" => Ok(Direction::E), "W" => Ok(Direction::W), _ => Err(()), } } } #[derive(Debug,Copy, Clone,PartialEq, Eq)] enum Action_type { MOVE, SURFACE, TORPEDO, SONAR, SILENCE, MINE, TRIGGER, } impl Default for Action_type { fn default() -> Self { Action_type::MOVE } } // --- coordinate #[derive(PartialEq, Eq, Hash, Copy, Clone,Debug, Default)] struct Coordinate { x: u8, y: u8, } impl Coordinate { fn dist(&self, c: &Coordinate) -> u8 { ((self.x as i8 -c.x as i8).abs() + (self.y as i8 -c.y as i8).abs()).try_into().unwrap() } fn l2_dist(&self, c: &Coordinate) -> u8 { (((self.x as i32 -c.x as i32).pow(2) + (self.y as i32 -c.y as i32).pow(2)) as f64).sqrt().floor() as u8 } fn to_surface(&self) -> u8 { if self.x < 5 && self.y < 5 {1} else if self.x < 10 && self.y < 5 {2} else if self.x < 15 && self.y < 5 {3} else if self.x < 5 && self.y < 10 {4} else if self.x < 10 && self.y < 10 {5} else if self.x < 15 && self.y < 10 {6} else if self.x < 5 && self.y < 15 {7} else if self.x < 10 && self.y < 15 {8} else if self.x < 15 && self.y < 15 {9} else {panic!("Bad sector")} } } // ----------- Action #[derive(Debug, Default,Copy, Clone)] struct Action { ac: Action_type, dir: Direction, coord: Coordinate, sector: u8, ac_load: Action_type, //only for load } impl Action { fn repr_action_v(va :&Vec::<Action>) -> String{ let mut out:String = "".to_string(); for (idx, a) in va.iter().enumerate() { if idx > 0 { out = format!("{}|", out); } match a.ac { Action_type::MOVE => out = format!("{}MOVE {:?} {:?}",out, a.dir, a.ac_load), Action_type::SURFACE => out = format!("{}SURFACE", out), Action_type::TORPEDO => out = format!("{}TORPEDO {} {}", out, a.coord.x, a.coord.y), Action_type::SONAR => out = format!("{}SONAR {}", out, a.sector), Action_type::SILENCE => out = format!("{}SILENCE {:?} {}", out, a.dir, a.sector), Action_type::MINE => out = format!("{}MINE {:?}", out, a.dir), Action_type::TRIGGER => out = format!("{}TRIGGER {} {}", out, a.coord.x, a.coord.y), } } out } fn parse_raw(st: &str) -> Vec::<Action> { if st == "NA" { return Vec::<Action>::new(); } let mut v_ret = Vec::<Action>::new(); for s in st.split("|"){ let vec_split: Vec<&str> = s.split(" ").collect(); match vec_split[0]{ "MOVE" => v_ret.push(Action {ac:Action_type::MOVE, dir:vec_split[1].parse::<Direction>().unwrap(), coord: Coordinate {x:0, y:0}, sector: 0, ac_load:Action_type::TORPEDO}), "SURFACE" => v_ret.push(Action {ac:Action_type::SURFACE, dir:Direction::N, coord: Coordinate {x:0, y:0}, sector: vec_split[1].parse::<u8>().unwrap(), ac_load:Action_type::TORPEDO}), "TORPEDO" => v_ret.push(Action {ac:Action_type::TORPEDO, dir:Direction::N, coord: Coordinate {x:vec_split[1].parse::<u8>().unwrap(), y:vec_split[2].parse::<u8>().unwrap()}, sector: 0, ac_load:Action_type::TORPEDO}), "SONAR" => v_ret.push(Action {ac:Action_type::SONAR, dir:Direction::N, coord: Coordinate {x:0, y:0}, sector: vec_split[1].parse::<u8>().unwrap(), ac_load:Action_type::TORPEDO}), "SILENCE" => v_ret.push(Action {ac:Action_type::SILENCE, dir:Direction::N, coord: Coordinate {x:0, y:0}, sector: 0, ac_load:Action_type::TORPEDO}), "MINE" => v_ret.push(Action {ac:Action_type::MINE, dir:Direction::N, coord: Coordinate {x:0, y:0}, sector: 0, ac_load:Action_type::TORPEDO}), "TRIGGER" => v_ret.push(Action {ac:Action_type::TRIGGER, dir:Direction::N, coord: Coordinate {x:vec_split[1].parse::<u8>().unwrap(), y:vec_split[2].parse::<u8>().unwrap()}, sector: 0, ac_load:Action_type::TORPEDO}), _ => panic!("Bad action"), } } v_ret } } //---- board #[derive( Copy, Clone,Debug)] struct Board { grid: [[u8; MAX_X as usize]; MAX_Y as usize], } impl Board { fn get_e(&self, c: &Coordinate) -> u8 { self.grid[c.x as usize][c.y as usize] } fn set_visited(&mut self, c: &Coordinate) { self.grid[c.x as usize][c.y as usize] = 1 } fn rem_visited(&mut self) { for x in 0..15 { for y in 0..15 { if self.grid[x as usize][y as usize] == 1 { self.grid[x as usize][y as usize] = 0 } } } } fn new(v: &Vec::<String>) -> Board { let mut r :[[u8; MAX_X as usize]; MAX_Y as usize] = [[0;MAX_X as usize];MAX_Y as usize]; for (idx,st) in v.iter().enumerate() { for (jdx,c) in st.chars().enumerate() { if c == '.' { r[jdx][idx] = 0 } else { r[jdx][idx] = 10 } } } Board {grid:r} } fn get_visited_stat(&self) -> (f64,f64) { let mut x_s = [false; MAX_X as usize]; let mut y_s = [false; MAX_Y as usize]; for x in 0..15 { for y in 0..15 { if self.grid[x as usize][y as usize] == 1 { x_s[x as usize] = true; y_s[y as usize] = true; } } } (x_s.iter().filter(|&n| *n == true).count() as f64, y_s.iter().filter(|&n| *n == true).count() as f64) } fn _rec_torpedo_coord_help(&self,c_init:&Coordinate, x:i32,y:i32,hist :&mut HashSet::<(i32,i32)>, ret_list:&mut Vec::<Coordinate>, num_vi:&mut i32){ *num_vi +=1; hist.insert((x,y)); if x < 0 || x >= MAX_X as i32|| y < 0 || y >= MAX_Y as i32 || self.get_e(&Coordinate {x:(x) as u8, y:(y) as u8}) == 10 { return } if c_init.dist(&Coordinate {x:(x) as u8, y:(y) as u8}) > 4 { return } ret_list.push(Coordinate {x:(x) as u8, y:(y) as u8}); if c_init.dist(&Coordinate {x:(x) as u8, y:(y) as u8}) == 4 { return } for modif in -1..2 { if !hist.contains(&(x + modif, y)) { self._rec_torpedo_coord_help(c_init, x + modif, y, hist, ret_list, num_vi); } if !hist.contains(&(x, y + modif)) { self._rec_torpedo_coord_help(c_init, x, y + modif, hist, ret_list, num_vi); } } } fn get_torpedo_pos_from_coord(&self, c:&Coordinate) -> Vec::<Coordinate> { let mut ret = Vec::<Coordinate>::new(); let mut num_vi = 0; self._rec_torpedo_coord_help(&c, c.x as i32, c.y as i32, &mut HashSet::<(i32,i32)>::new(), &mut ret, &mut num_vi); ret } fn get_diag_coord(&self, c:&Coordinate) -> Vec::<Coordinate> { let mut ret_v = Vec::<Coordinate>::new(); let x = c.x as i8; let y = c.y as i8; for x_a in -1..2 { for y_a in -1..2 { if !(x+x_a < 0 || x+x_a >= MAX_X as i8|| y+y_a < 0 || y+y_a >= MAX_Y as i8 || self.get_e(&Coordinate {x:(x +x_a) as u8, y:(y + y_a) as u8}) == 10) { ret_v.push(Coordinate {x:(x +x_a) as u8, y:(y + y_a) as u8}); } } } ret_v } fn get_nsew_coord(&self, c:&Coordinate) -> Vec::<Coordinate> { let mut ret_v = Vec::<Coordinate>::new(); let x = c.x as i8; let y = c.y as i8; for d in &[Direction::N, Direction::S, Direction::W, Direction::E] { let x_a; let y_a; match d { Direction::N => {x_a=0; y_a=-1}, Direction::S => {x_a=0; y_a=1}, Direction::W => {x_a=1; y_a=0}, Direction::E => {x_a=-1; y_a=0}, } if !(x+x_a < 0 || x+x_a >= MAX_X as i8|| y+y_a < 0 || y+y_a >= MAX_Y as i8 || self.get_e(&Coordinate {x:(x +x_a) as u8, y:(y + y_a) as u8}) == 10) { ret_v.push(Coordinate {x:(x +x_a) as u8, y:(y + y_a) as u8}); } } ret_v } //return the coord following the direction if correct fn check_dir(&self, c: &Coordinate, dir: &Direction) -> Option<Coordinate> { let mut xl = c.x as i8; let mut yl = c.y as i8; match dir { Direction::N => yl -= 1, Direction::S => yl += 1, Direction::W => xl -= 1, Direction::E => xl += 1, } if xl < 0 || xl >= MAX_X as i8|| yl < 0 || yl >= MAX_Y as i8 || self.get_e(&Coordinate {x:xl as u8, y:yl as u8}) != 0 { None } else { Some(Coordinate {x:xl as u8, y:yl as u8}) } } fn _rec_best_path(&self, cur_pos :&Coordinate, hist: &mut [[bool; MAX_X as usize]; MAX_Y as usize]) -> (u8, LinkedList::<Direction>) { //hist.insert(*cur_pos); hist[cur_pos.x as usize][cur_pos.y as usize] = true; let mut sum_a = 1; let mut dir_max = LinkedList::<Direction>::new(); let mut max_val = 0; for d in &[Direction::N, Direction::S, Direction::W, Direction::E]{ match self.check_dir(cur_pos, d) { Some(c_valid) => { if !hist[c_valid.x as usize][c_valid.y as usize] { let (val, r_l) = self._rec_best_path(&c_valid, hist); sum_a += val; if val > max_val { max_val = val; dir_max = r_l.iter().copied().collect(); dir_max.push_front(*d); } } } None => continue, } } (sum_a,dir_max) } fn _rec_num_pos(&self, cur_pos :&Coordinate, hist: &mut [[bool; MAX_X as usize]; MAX_Y as usize]) -> u8 { hist[cur_pos.x as usize][cur_pos.y as usize] = true; let mut sum_a = 1; for d in &[Direction::N, Direction::S, Direction::W, Direction::E]{ match self.check_dir(cur_pos, d) { Some(c_valid) => { if !hist[c_valid.x as usize][c_valid.y as usize] { sum_a += self._rec_num_pos(&c_valid, hist); } }, None => continue, } } sum_a } fn initial_position(&self) -> Coordinate { loop { let numx = 0; // rand::thread_rng().gen_range(0, 15); let numy = rand::thread_rng().gen_range(0, 15); if self.get_e(&Coordinate {x:numx as u8, y:numy as u8}) == 0 { let c = Coordinate {x:numx as u8,y:numy as u8}; break c } } } } // ------------------------- predictor ------------------ #[derive(Debug)] struct PathElem { freq: f64, coords: Vec::<Coordinate>, mines: Vec::<Coordinate>, } #[derive(Debug)] struct Path { //path_coords: Vec::<(f64, Vec::<Coordinate>)>, path_coords: Vec::<PathElem>, board: Board, reduced:bool, mines_m: MinesMng, } impl Path { fn new(board: Board) -> Path{ return Path { path_coords:Vec::<PathElem>::new(),board: board, reduced:false, mines_m:MinesMng::new()} } fn update_mines_infos(&mut self) { self.mines_m.update_mines_prob(&self.path_coords); } fn process_trigger(&mut self, co_t :Coordinate) { eprintln!("Process trigger, {:?}",co_t); //remove all paths which not contain co_t in mines list if !self.reduced { eprintln!("OK not reduced, we process trigger"); self.path_coords.retain(|pel| pel.mines.contains(&co_t)); //remove the mine triggered for pel in self.path_coords.iter_mut() { pel.mines.retain(|m| m != &co_t); } } } fn process_mine(&mut self) { eprintln!("Process MINE"); //add a mines to all potential path if !self.reduced { eprintln!("OK not reduced, we process mine"); for pel in self.path_coords.iter_mut(){ pel.mines.append(&mut self.board.get_nsew_coord(pel.coords.last().unwrap())); } } } fn process_torpedo(&mut self, co_t :Coordinate) { eprintln!("Process torpedo"); self.path_coords.retain(|pel| {pel.coords.last().unwrap().dist(&co_t) <= 4}); } fn process_surface(&mut self, sector :u8) { eprintln!("Process surface"); let rx:u8; let ry:u8; match sector { 1 => {rx=0; ry=0}, 2 => {rx=5; ry= 0}, 3 => {rx=10; ry= 0}, 4 => {rx=0; ry = 5}, 5 => {rx=5; ry = 5}, 6 => {rx=10; ry = 5}, 7 => {rx=0; ry = 10}, 8 => {rx=5; ry = 10}, 9 => {rx=10; ry= 10}, _ => panic!("Bad sector"), } let l_g:&Board = &self.board; self.path_coords.retain(|pel| { for x in rx..(rx + 5){ for y in ry..(ry + 5){ if l_g.grid[x as usize][y as usize] == 10 { continue; //Do not add the islands } if pel.coords.last().unwrap() == &(Coordinate {x:x, y:y}) { return true; } } } return false; }); //reset the paths, we keep mines for pel in &mut self.path_coords { pel.coords = vec![*pel.coords.last().unwrap()] } } fn _reduce_search_space(v_coord :&Vec::<PathElem>) -> Vec::<PathElem> { //ok reduce search space let mut p_coords_reduced = Vec::<PathElem>::new(); let mut frequency: HashMap<&Coordinate, f64> = HashMap::new(); let mut frequency_mines: HashMap<&Coordinate, HashSet<Coordinate>> = HashMap::new(); for pel in v_coord { let freq = pel.freq; let coord = &pel.coords; *frequency.entry(coord.last().unwrap()).or_insert(0.0) += freq; frequency_mines.entry(coord.last().unwrap()).or_insert(HashSet::<Coordinate>::new()).extend(pel.mines.iter()); } for (co,freq) in &frequency { p_coords_reduced.push(PathElem {freq:*freq, coords:vec![**co], mines:Vec::from_iter(frequency_mines[co].iter().copied())}); } p_coords_reduced } fn process_silence(&mut self) { eprintln!("Process SILENCE"); let max_search:usize = 1000; //max paths before reduction let mut p_coords_l = Vec::<PathElem>::new(); if self.path_coords.len() > max_search { eprintln!("REDUCE size before : {}", self.path_coords.len()); self.path_coords = Path::_reduce_search_space(&self.path_coords); eprintln!("REDUCE size after : {}", self.path_coords.len()); panic!("REDUCED should be avoided"); } for pel in &self.path_coords { //add new possible coord for each paths //adv can make a 0 move p_coords_l.push(PathElem {freq:pel.freq, coords:pel.coords.to_vec(), mines:pel.mines.to_vec()}); for d in [Direction::N, Direction::S, Direction::W, Direction::E].iter() { let cur_path:&mut Vec::<Coordinate> = &mut pel.coords.to_vec(); let mut cur_pos:Coordinate = *cur_path.last().unwrap(); for i in 1..5 { match self.board.check_dir(&cur_pos, &d) { Some(c_valid) => { if !cur_path.contains(&c_valid) { //if c_valid is in v, this means a cross between path -> invalid cur_path.push(c_valid); let new_freq:f64 = (pel.freq)*(((10-2*i) as f64)/10.0); p_coords_l.push(PathElem {freq:new_freq, coords:cur_path.to_vec(), mines:pel.mines.to_vec()}); //explicit copy cur_pos = c_valid; } else { break } }, None => break, } } } } self.path_coords = p_coords_l ; } fn process_move(&mut self, d: Direction) { eprintln!("Process MOVE"); if self.path_coords.is_empty() { eprintln!("+-+-----+++-+ path coords empty, initialize"); for x in 0..MAX_X { for y in 0..MAX_Y { if self.board.grid[x as usize][y as usize] == 10 { continue; //Do not add the islands } self.path_coords.push(PathElem {freq:PATH_INIT, coords:vec![Coordinate {x:x, y:y}], mines:Vec::<Coordinate>::new()}); } } } for pel in self.path_coords.iter_mut() { match self.board.check_dir(pel.coords.last().unwrap(), &d) { Some(c_valid) => { pel.coords.push(c_valid); } None => pel.coords.clear(), //impossible we clear the path } } //remove all element empty self.path_coords.retain(|pel| !pel.coords.is_empty()); } fn process_actions(&mut self, v_act:&Vec<Action>) { for a in v_act { match a.ac { Action_type::MOVE => self.process_move(a.dir), Action_type::SURFACE => self.process_surface(a.sector), Action_type::TORPEDO => self.process_torpedo(a.coord), Action_type::SONAR => {}, Action_type::SILENCE => self.process_silence(), Action_type::MINE => self.process_mine(), Action_type::TRIGGER => {self.process_trigger(a.coord)}, } } } fn comp_variance(v_c:&Vec::<PathElem>, max_freq:f64) -> (f64,f64) { let mut xm = -1.0; let mut ym = -1.0; let mut tot:f64 = 0.0; //comput mean for pel in v_c { if pel.freq < max_freq { continue; } let el = pel.coords.last().unwrap(); if xm < 0.0 { xm = pel.freq*el.x as f64; ym = pel.freq*el.y as f64; tot += pel.freq; } else { xm += pel.freq*el.x as f64; ym += pel.freq*el.y as f64; tot += pel.freq; } } xm /= tot; ym /= tot; //comput variance let mut x_v:f64 = 0.0; let mut y_v:f64 = 0.0; for pel in v_c { let el = pel.coords.last().unwrap(); x_v += (pel.freq as f64)*(el.x as f64 - xm).powi(2); y_v += (pel.freq as f64)*(el.y as f64 - ym).powi(2); } x_v /= tot as f64; y_v /= tot as f64; (x_v.sqrt(), y_v.sqrt()) } fn process_previous_actions(&mut self, va_issued:&Vec<Action>, va_opp_issued:&Vec<Action>, diff_life_arg:u8) { let mut diff_life = diff_life_arg; //ok tricky, if the opponement made an action that reduce it's life we need to take it into account //if we have torpedo in both actions, we cannot say anothing if diff_life_arg !=0 && va_issued.iter().any(|v| v.ac == Action_type::TORPEDO) && va_opp_issued.iter().any(|v| v.ac == Action_type::TORPEDO) { return } if va_issued.iter().filter(|&v| v.ac == Action_type::TORPEDO || v.ac == Action_type::TRIGGER).count() > 1 { eprintln!("Torpedo + trigger in previous action, don't update"); return } let mut coord_torpedo = Coordinate {x:0,y:0}; if va_issued.iter().any(|v| {coord_torpedo = v.coord; v.ac == Action_type::TORPEDO || v.ac == Action_type::TRIGGER}) { if va_opp_issued.iter().any(|a| a.ac == Action_type::SURFACE) { diff_life -= 1; eprintln!("== correction with surface"); } eprintln!("Found torpedo or trigger previous"); match diff_life { 1 => { eprintln!("torp touch 1! coord {:?}", coord_torpedo); self.path_coords.retain(|pel| {pel.coords.last().unwrap().l2_dist(&coord_torpedo) == 1}); eprintln!("re {:?}", Path::_reduce_search_space(&self.path_coords) ); }, 2 => { eprintln!("torp touch 2! coord {:?}", coord_torpedo); self.path_coords.retain(|pel| {pel.coords.last().unwrap().dist(&coord_torpedo) == 0}); eprintln!("re {:?}", Path::_reduce_search_space(&self.path_coords) ); }, 0 => { eprintln!("torp NO touch coord {:?}", coord_torpedo); self.path_coords.retain(|pel| {pel.coords.last().unwrap().l2_dist(&coord_torpedo) > 1}); }, _ => panic!("diff life != 1,2,0 val : {}",diff_life), } } } } // ------------ SIMULATOR #[derive( Clone,Debug)] struct Simulator { board: Board, my_mines: MinesMng, adv_mines:MinesMng, play_c: Coordinate, adv_c: Coordinate, torpedo_v: u8, silence_v: u8, mine_v: u8, adv_lost: u8, play_lost: u8, proba_coord: f64, adv_life:u8, play_life:u8, } impl Simulator { fn new(l_board:Board, my_mines: MinesMng, adv_mines:MinesMng, play_c:Coordinate, adv_c:Coordinate, torpedo_v:u8, silence_v:u8, mine_v:u8, proba_coord:f64, play_life:u8, adv_life:u8) -> Simulator { Simulator {board:l_board, my_mines:my_mines, adv_mines:adv_mines, play_c:play_c, adv_c:adv_c, silence_v:silence_v, torpedo_v:torpedo_v, mine_v:mine_v, adv_lost:0, proba_coord:proba_coord, play_lost:0, adv_life:adv_life, play_life:play_life}} fn play_ac_l(&self, va:&Vec::<Action>) -> Option<(Simulator)> { let mut sim_sim = self.clone(); for a in va { match a.ac { Action_type::MOVE => { match sim_sim.board.check_dir(&sim_sim.play_c, &a.dir) { Some(c_valid) => { sim_sim.play_c = c_valid; sim_sim.board.set_visited(&c_valid); match a.ac_load { Action_type::TORPEDO => sim_sim.torpedo_v = cmp::min(sim_sim.torpedo_v+1, 3), Action_type::SILENCE => sim_sim.silence_v = cmp::min(sim_sim.silence_v+1, 6), Action_type::MINE => sim_sim.mine_v = cmp::min(sim_sim.mine_v+1, 3), _ => panic!("Error, must be torpedo, silence or mine"), } }, None => return None, } }, Action_type::SURFACE => { //sim_sim.board.rem_visited(); sim_sim.play_life -=1; }, Action_type::TORPEDO => { if sim_sim.torpedo_v < 3 { return None; } if sim_sim.play_c.dist(&a.coord) > 4 { return None; } let list_torps = sim_sim.board.get_torpedo_pos_from_coord(&sim_sim.play_c); if !list_torps.contains(&a.coord) { return None; } sim_sim.torpedo_v = 0; if a.coord.dist(&sim_sim.adv_c) == 0 { sim_sim.adv_lost = 2; } else if a.coord.l2_dist(&sim_sim.adv_c) == 1 { sim_sim.adv_lost = 1; } if a.coord.dist(&sim_sim.play_c) == 0 { sim_sim.play_lost = 2; } else if a.coord.l2_dist(&sim_sim.play_c) == 1 { sim_sim.play_lost = 1; } } Action_type::SONAR => continue, Action_type::SILENCE => { if sim_sim.silence_v < 6 { return None } let mut loc_pc:Coordinate = sim_sim.play_c; for _ in 0..a.sector { match sim_sim.board.check_dir(&loc_pc, &a.dir) { Some(c_valid) => loc_pc = c_valid, None => return None, } } //ok here we tested all coords and it's OK, now write on the board for _ in 0..a.sector { match sim_sim.board.check_dir(&sim_sim.play_c, &a.dir) { Some(c_valid) => { sim_sim.board.set_visited(&c_valid); sim_sim.play_c = c_valid; }, None => panic!("Can't happen !!"), } } sim_sim.silence_v = 0; }, Action_type::MINE => { if sim_sim.mine_v < 3 { return None; } let mut xl = sim_sim.play_c.x as i8; let mut yl = sim_sim.play_c.y as i8; match a.dir { Direction::N => yl -= 1, Direction::S => yl += 1, Direction::W => xl -= 1, Direction::E => xl += 1, } if xl < 0 || xl >= MAX_X as i8|| yl < 0 || yl >= MAX_Y as i8 || sim_sim.board.get_e(&Coordinate {x:xl as u8, y:yl as u8}) == 10 { return None } let mine_coord = Coordinate {x:xl as u8, y:yl as u8}; if sim_sim.my_mines.list_mines.contains(&mine_coord) { return None } sim_sim.my_mines.list_mines.insert(mine_coord); sim_sim.mine_v = 0; }, Action_type::TRIGGER => continue, } } if sim_sim.play_life as i32 - sim_sim.play_lost as i32 <= 0 { //if we loose, bad action... None } else { Some(sim_sim) } } fn eval_func(&self) -> f64 { if self.play_life as i32 - self.play_lost as i32 <= 0 { //if we loose, bad action... return 0.0; } if self.proba_coord < 0.5 && self.play_lost > 0 { return 0.0 //do not allow to loose life if we are unsure of the position } return self.adv_lost as f64 - self.play_lost as f64; } fn eval_func_move(&self) -> f64 { //-- find available positions let mut grid: [[bool; MAX_X as usize]; MAX_Y as usize] = [[false; MAX_X as usize]; MAX_Y as usize]; let po = self.board._rec_num_pos(&self.play_c, &mut grid); //path with good shape let (mx,my) = self.board.get_visited_stat(); //maximize the number of ressources let maxim = self.torpedo_v + self.mine_v + self.silence_v; //try to have good mines structure let mines = 4.0*self.my_mines.list_mines.len() as f64; //try to avoid adv mines let dc = self.board.get_diag_coord(&self.play_c); let avoid_mines:f64 = dc.iter().map(|&c| self.adv_mines.grid_probas[c.x as usize][c.y as usize]).sum(); return po as f64 + maxim as f64 - (mx-my).abs() + mines - 30.0*avoid_mines; } fn compute_best_move_sequence(&self, with_sil:bool,with_move:bool) -> Option<(Vec::<Action>, Simulator)> { let mut v_move = Vec::<Action>::new(); let mut v_sil = Vec::<Action>::new(); let mut v_mines = Vec::<Action>::new(); let mut ret_val_std = None; let mut max_op = 0.0; for d in &[Direction::N, Direction::S, Direction::W, Direction::E] { v_mines.push(Action { ac: Action_type::MINE, dir:*d, ..Default::default() }); if with_move { v_move.push(Action { ac: Action_type::MOVE, dir:*d, ac_load:Action_type::TORPEDO, ..Default::default() }); v_move.push(Action { ac: Action_type::MOVE, dir:*d, ac_load:Action_type::SILENCE, ..Default::default() }); v_move.push(Action { ac: Action_type::MOVE, dir:*d, ac_load:Action_type::MINE, ..Default::default() }); } if with_sil { for i in 1..5 { v_sil.push(Action { ac: Action_type::SILENCE, dir:*d, sector:i, ..Default::default() }); } } } for a in &v_move{ let v_try = vec![*a]; match self.play_ac_l(&v_try) { Some(sim) => { let ev_f = sim.eval_func_move(); if ev_f > max_op { max_op = ev_f; ret_val_std = Some((v_try, sim)); } } None => continue, } } for a in &v_move{ for m in &v_mines{ let v_try = vec![*a, *m]; match self.play_ac_l(&v_try) { Some(sim) => { let ev_f = sim.eval_func_move(); if ev_f > max_op { max_op = ev_f; ret_val_std = Some((v_try, sim)); } } None => continue, } } } ret_val_std } fn compute_best_sequence(&self, m_play:&MinesMng, m_adv:&MinesMng) -> Option<(Vec::<Action>, Simulator)> { let mut v_move = Vec::<Action>::new(); let mut v_sil = Vec::<Action>::new(); let mut v_torp = Vec::<Action>::new(); let mut v_trig = Vec::<Action>::new(); for d in &[Direction::N, Direction::S, Direction::W, Direction::E] { v_move.push(Action { ac: Action_type::MOVE, dir:*d, ac_load:Action_type::TORPEDO, ..Default::default() }); v_move.push(Action { ac: Action_type::MOVE, dir:*d, ac_load:Action_type::SILENCE, ..Default::default() }); for i in 1..5 { v_sil.push(Action { ac: Action_type::SILENCE, dir:*d, sector:i, ..Default::default() }); } } for a in &self.board.get_diag_coord(&self.adv_c) { v_torp.push(Action { ac: Action_type::TORPEDO, coord:*a, ..Default::default() }); } for c in &m_play.list_mines { v_trig.push(Action { ac: Action_type::TRIGGER, coord:*c, ..Default::default() }); } let mut max_op = 0.0; let mut ret_val:Option::<(Vec::<Action>, Simulator)> = None; for a in &v_torp { let v_try = vec![*a]; match self.play_ac_l(&v_try) { Some(sim) => { let ev_f = sim.eval_func(); if ev_f > max_op { max_op = ev_f; ret_val = Some((v_try, sim)); } } None => continue, } } if self.proba_coord <= 0.2 && (self.silence_v < 6 || self.mine_v < 3){ //proba is to low, need to create silence return None; } if self.proba_coord <= 0.2 && self.silence_v == 6 { eprintln!("Proba <=0.2, only torpedo if assez silence, early return since proba low"); return ret_val } if self.proba_coord > 0.2 { //move then torpedo eprintln!("Proba inf > 0.2, move + torpedo"); for a_move in &v_move { for a in &v_torp { let v_try = vec![*a_move, *a]; match self.play_ac_l(&v_try) { Some(sim) => { let ev_f = sim.eval_func(); if ev_f > max_op { max_op = ev_f; ret_val = Some((v_try, sim)); } } None => continue, } } } } if self.proba_coord > 0.9 { //move silence then torpedo eprintln!("Proba inf > 0.9, move + silence torpedo"); for a_move in &v_move { for a_sil in &v_sil { for a in &v_torp { let v_try = vec![*a_move,*a_sil, *a]; match self.play_ac_l(&v_try) { Some(sim) => { let ev_f = sim.eval_func(); if ev_f > max_op { max_op = ev_f; ret_val = Some((v_try, sim)); } } None => continue, } } } } } ret_val } } //MINES Manager #[derive(Debug, Clone)] struct MinesMng { list_mines: HashSet::<Coordinate>, grid_probas: [[f64; MAX_X as usize]; MAX_Y as usize], } impl MinesMng { fn new() -> MinesMng { MinesMng {list_mines:HashSet::<Coordinate>::new(), grid_probas:[[0.0; MAX_X as usize]; MAX_Y as usize]} } fn add_mine(&mut self, c:&Coordinate) { self.list_mines.insert(*c); } fn get_remove_d1(&mut self, c:&Coordinate) -> Option<Coordinate> { let mut retval = None; self.list_mines.retain(|mc| { if mc.l2_dist(c) <= 1 { retval=Some(*mc); false } else { true } }); retval } //reduce possible mines to freq to coordinate fn update_mines_prob(&mut self, v:&Vec::<PathElem>) { let mut frequency: HashMap<&Coordinate, f64> = HashMap::new(); for pel in v { for m in &pel.mines { *frequency.entry(m).or_insert(0.0) += pel.freq; } } self.grid_probas = [[0.0; MAX_X as usize]; MAX_Y as usize]; let max_v = frequency.len() as f64; for (co_m,freq) in &frequency { self.grid_probas[co_m.x as usize][co_m.y as usize] = (*freq as f64)/max_v; } eprintln!("Mines situations"); eprintln!("Num poss mines {}", frequency.len()); } } //------------ PREDICTOR #[derive(Debug)] struct Predictor { path: Path, my_path: Path, op_life: Vec::<u8>, cur_co: Coordinate, play_board: Board, my_life: Vec::<u8>, torpedo :u8, silence :u8, sonar :u8, mines: u8, actions_issued: Vec::<Action>, } impl Predictor { fn new(board: Board) -> Predictor{ return Predictor {path: Path::new(board), my_path: Path::new(board), op_life:Vec::<u8>::new(), cur_co: Coordinate {x:0,y:0}, actions_issued:Vec::<Action>::new(), my_life:Vec::<u8>::new(), play_board:board, torpedo:0, silence:0, sonar:0, mines:0}; } fn get_possible_pos(&self, path:&Path) -> (usize, Coordinate, (f64, f64), f64, Coordinate) { let mut reduced_v = Path::_reduce_search_space(&path.path_coords); reduced_v.sort_unstable_by(|pela, pelb| pelb.freq.partial_cmp(&pela.freq).unwrap()); //reverse sort eprintln!("Num possible coord {}", reduced_v.len()); eprintln!("Num possible path {}", path.path_coords.len()); //try to keep only the maximum confidences let max_freq:f64 = reduced_v[cmp::min(reduced_v.len()-1, reduced_v.len()-1) as usize].freq; eprintln!("Max k-{} max_freq : {}", cmp::min(4, reduced_v.len()-1), max_freq); let mut xm:f64 = -1.0; let mut ym:f64 = -1.0; let mut tot:f64 = 0.0; for pel in &reduced_v { if pel.freq < max_freq { continue; } let el = pel.coords.last().unwrap(); if xm < 0.0 { xm = pel.freq*el.x as f64; ym = pel.freq*el.y as f64; tot += pel.freq; } else { xm += pel.freq*el.x as f64; ym += pel.freq*el.y as f64; tot += pel.freq; } } xm /= tot; ym /= tot; let round_coord = Coordinate {x:xm.round() as u8, y:ym.round() as u8}; eprintln!("round {:?}", round_coord); if reduced_v.len() < 10 { for pel in &reduced_v { eprintln!("freq : {}, prob {}, val : {:?}",pel.freq, pel.freq/tot, pel.coords.last().unwrap()); } } (reduced_v.len(),round_coord, Path::comp_variance(&reduced_v, max_freq), reduced_v[0].freq/tot, *reduced_v[0].coords.last().unwrap()) } fn get_actions_to_play(&mut self) -> Vec::<Action> { eprintln!("Torpedo val {}",self.torpedo); let mut v_act = Vec::<Action>::new(); let mut v_act_move = Vec::<Action>::new(); let mut proba_my = 0.0; if !self.my_path.path_coords.is_empty() && !self.path.path_coords.is_empty() { eprintln!("*** MY possible pos"); let (my_n_pos_l, _,_, proba_my_loc, _) = self.get_possible_pos(&self.my_path); proba_my = proba_my_loc; eprintln!("mynpos proba {}", proba_my); let (n_pos, coord_mean, variance, prob, max_prob_coord) = self.get_possible_pos(&self.path); let coord = max_prob_coord; eprintln!("*** ADV possible pos np: {}, var: {:?}, prob : {}", n_pos, variance, prob); let dc = self.play_board.get_diag_coord(&self.cur_co); let avoid_mines:f64 = dc.iter().map(|&c| self.path.mines_m.grid_probas[c.x as usize][c.y as usize]).sum(); eprintln!("Avoid mines {}",30.0*avoid_mines); let (_, dir) = self.play_board._rec_best_path(&self.cur_co, &mut [[false; MAX_X as usize]; MAX_Y as usize]); if dir.is_empty() || 30.0*avoid_mines > 100.0 { self.play_board.rem_visited(); *(self.my_life.last_mut().unwrap()) -=1; eprintln!("SURFACE, sector {}",self.cur_co.to_surface()); v_act.push(Action { ac: Action_type::SURFACE, sector:self.cur_co.to_surface(), ..Default::default() }); //println!("{}SURFACE",add_str) } let simul = Simulator::new(self.play_board, self.my_path.mines_m.clone(), self.path.mines_m.clone(), self.cur_co, coord, self.torpedo, self.silence, self.mines, prob, *self.my_life.last().unwrap(), *self.op_life.last().unwrap()); let mut next_sim = simul.clone(); match simul.compute_best_sequence(&self.my_path.mines_m, &self.path.mines_m) { Some((v,sim)) => { eprintln!("FFFFFF {:?} {} {}",v, sim.adv_lost,sim.play_lost); v_act = v; self.torpedo = sim.torpedo_v; self.silence = sim.silence_v; self.mines = sim.mine_v; self.cur_co = sim.play_c; self.play_board = sim.board; //update board, should be ok... self.my_path.mines_m = sim.my_mines.clone(); next_sim = sim; }, None => eprintln!("FFFFFF NOT"), } let has_sil = v_act.iter().any(|&x| x.ac == Action_type::SILENCE); let has_move = v_act.iter().any(|&x| x.ac == Action_type::MOVE); match next_sim.compute_best_move_sequence(!has_sil, !has_move) { Some((v,sim)) => { eprintln!("FFFmove {:?} {} {}",v, sim.adv_lost,sim.play_lost); v_act_move = v; self.torpedo = sim.torpedo_v; self.silence = sim.silence_v; self.mines = sim.mine_v; self.cur_co = sim.play_c; self.play_board = sim.board; //update board, should be ok... self.my_path.mines_m = sim.my_mines; }, None => eprintln!("FFmove NOT"), } if prob > 0.9 { match self.my_path.mines_m.get_remove_d1(&max_prob_coord) { Some(c) => v_act.push(Action { ac: Action_type::TRIGGER, coord:c, ..Default::default() }), None => {} , } } } v_act.extend(&v_act_move); if !v_act.iter().any(|&x| x.ac == Action_type::SILENCE) && self.silence == 6 && proba_my > 0.8 { let (_, dir) = self.play_board._rec_best_path(&self.cur_co, &mut [[false; MAX_X as usize]; MAX_Y as usize]); if !dir.is_empty() { let next_dir = *dir.front().unwrap(); eprintln!("He found me, silence !!"); v_act.push(Action { ac: Action_type::SILENCE, dir:next_dir, sector:1, ..Default::default() }); self.silence = 0; } } if v_act.is_empty() { //for the firsts rounds let (_, dir) = self.play_board._rec_best_path(&self.cur_co, &mut [[false; MAX_X as usize]; MAX_Y as usize]); let next_dir = *dir.front().unwrap(); v_act.push(Action { ac: Action_type::MOVE, dir:next_dir, ac_load:Action_type::TORPEDO, ..Default::default() }); self.torpedo += 1; self.torpedo = cmp::min(self.torpedo,3); } self.actions_issued = v_act.to_vec(); //copy here v_act } fn update_situation(&mut self,opp_life:u8, my_life:u8, x:u8, y:u8, opponent_orders:&Vec::<Action>) { self.path.update_mines_infos(); self.op_life.push(opp_life); self.cur_co = Coordinate {x:x,y:y}; self.play_board.set_visited(&self.cur_co); self.my_life.push(my_life); if self.op_life.len() > 2 { eprintln!("Update ADV coordinate"); let diff = self.op_life[self.op_life.len() - 2] - *self.op_life.last().unwrap(); self.path.process_previous_actions(&self.actions_issued, opponent_orders, diff); } if self.my_life.len() > 2 { eprintln!("Update MY coordinate"); let diff = self.my_life[self.my_life.len() - 2] - *self.my_life.last().unwrap(); self.my_path.process_previous_actions(opponent_orders, &self.actions_issued, diff); } } } macro_rules! parse_input { ($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap()) } /** * Auto-generated code below aims at helping you parse * the standard input according to the problem statement. **/ fn main() { let mut vec = Vec::<String>::new(); let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let inputs = input_line.split(" ").collect::<Vec<_>>(); let width = parse_input!(inputs[0], i32); let height = parse_input!(inputs[1], i32); let my_id = parse_input!(inputs[2], i32); for i in 0..height as usize { let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let line = input_line.trim_end().to_string(); vec.push(line); } let board = Board::new(&vec); //ok dont use this Board since values are copied on the predictor let mut predictor = Predictor::new(board); let st = board.initial_position(); println!("{} {}",st.x,st.y); // game loop loop { let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let inputs = input_line.split(" ").collect::<Vec<_>>(); let x = parse_input!(inputs[0], i32); let y = parse_input!(inputs[1], i32); let my_life = parse_input!(inputs[2], i32); let opp_life = parse_input!(inputs[3], i32); let torpedo_cooldown = parse_input!(inputs[4], i32); let sonar_cooldown = parse_input!(inputs[5], i32); let silence_cooldown = parse_input!(inputs[6], i32); let mine_cooldown = parse_input!(inputs[7], i32); let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let sonar_result = input_line.trim().to_string(); let mut input_line = String::new(); io::stdin().read_line(&mut input_line).unwrap(); let opponent_orders = input_line.trim_end().to_string(); let start = Instant::now(); predictor.update_situation(opp_life as u8, my_life as u8, x as u8, y as u8, &Action::parse_raw(&opponent_orders)); predictor.path.process_actions(&Action::parse_raw(&opponent_orders)); //predictor.path.get_possible_pos(); let v_acts = predictor.get_actions_to_play(); predictor.my_path.process_actions(&v_acts); let duration = start.elapsed(); eprintln!("Total duration : {:?}",duration); println!("{}",&Action::repr_action_v(&v_acts)); } }
use crate::parser::stream::Stream; use crate::parser::*; use crate::token::Keyword; use anyhow::Result; use trace; pub fn parse_statements(stream: &mut Stream) -> Result<Statements> { trace!(stream, "parse_statements", { let mut statements = Vec::new(); loop { if let Some(vardec) = parse_statement(stream)? { statements.push(vardec); } else { break; } } Ok(Statements { statements }) }); } fn parse_statement(stream: &mut Stream) -> Result<Option<Statement>> { trace!(stream, "parse_statements", { parse_let(stream) .or_else(|| parse_if(stream)) .or_else(|| parse_while(stream)) .or_else(|| parse_do(stream)) .or_else(|| parse_return(stream)) .transpose() }); } fn parse_let(stream: &mut Stream) -> Option<Result<Statement>> { trace!(stream, "parse_let", { stream.consume_if_keyword(Keyword::Let).map(|t| { let loc = t.location(); let name = stream.ensure_identifier()?; let accessor = parse_accessor(stream)?; stream.ensure_symbol('=')?; let expr = expr::parse_expr_or_die(stream)?; let stmt = LetStatement { loc, name, accessor, expr, }; stream.ensure_symbol(';')?; Ok(Statement::Let(stmt)) }) }); } fn parse_accessor(stream: &mut Stream) -> Result<Option<Expr>> { trace!(stream, "parse_accessor", { stream .consume_if_symbol('[') .map(|_t| { expr::parse_expr_or_die(stream) .and_then(|expr| stream.ensure_symbol(']').and_then(|_t| Ok(expr))) }) .transpose() }); } fn parse_cond_expr(stream: &mut Stream) -> Result<Expr> { stream.ensure_symbol('(')?; let cond = expr::parse_expr_or_die(stream)?; stream.ensure_symbol(')')?; Ok(cond) } fn parse_block(stream: &mut Stream) -> Result<Statements> { stream.ensure_symbol('{')?; let statements = parse_statements(stream)?; stream.ensure_symbol('}')?; Ok(statements) } fn parse_if(stream: &mut Stream) -> Option<Result<Statement>> { trace!(stream, "parse_if", { stream.consume_if_keyword(Keyword::If).map(|t| { let loc = t.location(); let cond = parse_cond_expr(stream)?; let statements = parse_block(stream)?; let else_branch = stream .consume_if_keyword(Keyword::Else) .map(|_t| parse_block(stream)) .transpose()?; let stmt = IfStatement { loc, cond, statements, else_branch, }; Ok(Statement::If(stmt)) }) }); } fn parse_while(stream: &mut Stream) -> Option<Result<Statement>> { trace!(stream, "parse_while", { stream.consume_if_keyword(Keyword::While).map(|t| { let loc = t.location(); let cond = parse_cond_expr(stream)?; let statements = parse_block(stream)?; let stmt = WhileStatement { loc, cond, statements, }; Ok(Statement::While(stmt)) }) }); } fn parse_do(stream: &mut Stream) -> Option<Result<Statement>> { trace!(stream, "parse_do", { stream.consume_if_keyword(Keyword::Do).map(|t| { let loc = t.location(); let call = expr::parse_subroutine_call(stream)?; stream.ensure_symbol(';')?; let stmt = DoStatement { loc, call }; Ok(Statement::Do(stmt)) }) }); } fn parse_return(stream: &mut Stream) -> Option<Result<Statement>> { trace!(stream, "parse_return", { stream.consume_if_keyword(Keyword::Return).map(|t| { let loc = t.location(); let expr = expr::parse_expr(stream).transpose()?; stream.ensure_symbol(';')?; let stmt = ReturnStatement { loc, expr }; Ok(Statement::Return(stmt)) }) }); }
//! named accounts for synthesized data accounts for bank state, etc. //! use crate::pubkey::Pubkey; pub mod slot_hashes; /// "Sysca11111111111111111111111111111111111111" /// owner pubkey for syscall accounts const ID: [u8; 32] = [ 6, 167, 211, 138, 69, 216, 137, 185, 198, 189, 33, 204, 111, 12, 217, 220, 229, 201, 34, 52, 253, 202, 87, 144, 232, 16, 195, 192, 0, 0, 0, 0, ]; pub fn id() -> Pubkey { Pubkey::new(&ID) } pub fn check_id(id: &Pubkey) -> bool { id.as_ref() == ID } #[cfg(test)] mod tests { use super::*; #[test] fn test_syscall_ids() { let ids = [("Sysca11111111111111111111111111111111111111", id())]; // to get the bytes above: // ids.iter().for_each(|(name, _)| { // dbg!((name, bs58::decode(name).into_vec().unwrap())); // }); assert!(ids.iter().all(|(name, id)| *name == id.to_string())); assert!(check_id(&id())); } }
#[doc = "Reader of register CR"] pub type R = crate::R<u32, super::CR>; #[doc = "Writer for register CR"] pub type W = crate::W<u32, super::CR>; #[doc = "Register CR `reset()`'s with value 0x2000_2000"] impl crate::ResetValue for super::CR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x2000_2000 } } #[doc = "ADC calibration\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADCAL_A { #[doc = "0: Calibration complete"] COMPLETE = 0, #[doc = "1: Start the calibration of the ADC"] CALIBRATION = 1, } impl From<ADCAL_A> for bool { #[inline(always)] fn from(variant: ADCAL_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ADCAL`"] pub type ADCAL_R = crate::R<bool, ADCAL_A>; impl ADCAL_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ADCAL_A { match self.bits { false => ADCAL_A::COMPLETE, true => ADCAL_A::CALIBRATION, } } #[doc = "Checks if the value of the field is `COMPLETE`"] #[inline(always)] pub fn is_complete(&self) -> bool { *self == ADCAL_A::COMPLETE } #[doc = "Checks if the value of the field is `CALIBRATION`"] #[inline(always)] pub fn is_calibration(&self) -> bool { *self == ADCAL_A::CALIBRATION } } #[doc = "Write proxy for field `ADCAL`"] pub struct ADCAL_W<'a> { w: &'a mut W, } impl<'a> ADCAL_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADCAL_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Calibration complete"] #[inline(always)] pub fn complete(self) -> &'a mut W { self.variant(ADCAL_A::COMPLETE) } #[doc = "Start the calibration of the ADC"] #[inline(always)] pub fn calibration(self) -> &'a mut W { self.variant(ADCAL_A::CALIBRATION) } #[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 << 31)) | (((value as u32) & 0x01) << 31); self.w } } #[doc = "Differential mode for calibration\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADCALDIF_A { #[doc = "0: Calibration for single-ended mode"] SINGLEENDED = 0, #[doc = "1: Calibration for differential mode"] DIFFERENTIAL = 1, } impl From<ADCALDIF_A> for bool { #[inline(always)] fn from(variant: ADCALDIF_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ADCALDIF`"] pub type ADCALDIF_R = crate::R<bool, ADCALDIF_A>; impl ADCALDIF_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ADCALDIF_A { match self.bits { false => ADCALDIF_A::SINGLEENDED, true => ADCALDIF_A::DIFFERENTIAL, } } #[doc = "Checks if the value of the field is `SINGLEENDED`"] #[inline(always)] pub fn is_single_ended(&self) -> bool { *self == ADCALDIF_A::SINGLEENDED } #[doc = "Checks if the value of the field is `DIFFERENTIAL`"] #[inline(always)] pub fn is_differential(&self) -> bool { *self == ADCALDIF_A::DIFFERENTIAL } } #[doc = "Write proxy for field `ADCALDIF`"] pub struct ADCALDIF_W<'a> { w: &'a mut W, } impl<'a> ADCALDIF_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADCALDIF_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Calibration for single-ended mode"] #[inline(always)] pub fn single_ended(self) -> &'a mut W { self.variant(ADCALDIF_A::SINGLEENDED) } #[doc = "Calibration for differential mode"] #[inline(always)] pub fn differential(self) -> &'a mut W { self.variant(ADCALDIF_A::DIFFERENTIAL) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Deep-power-down enable\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DEEPPWD_A { #[doc = "0: ADC not in Deep-power down"] DISABLED = 0, #[doc = "1: ADC in Deep-power-down (default reset state)"] ENABLED = 1, } impl From<DEEPPWD_A> for bool { #[inline(always)] fn from(variant: DEEPPWD_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `DEEPPWD`"] pub type DEEPPWD_R = crate::R<bool, DEEPPWD_A>; impl DEEPPWD_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DEEPPWD_A { match self.bits { false => DEEPPWD_A::DISABLED, true => DEEPPWD_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == DEEPPWD_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == DEEPPWD_A::ENABLED } } #[doc = "Write proxy for field `DEEPPWD`"] pub struct DEEPPWD_W<'a> { w: &'a mut W, } impl<'a> DEEPPWD_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DEEPPWD_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "ADC not in Deep-power down"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(DEEPPWD_A::DISABLED) } #[doc = "ADC in Deep-power-down (default reset state)"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(DEEPPWD_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 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "ADC voltage regulator enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADVREGEN_A { #[doc = "0: ADC voltage regulator disabled"] DISABLED = 0, #[doc = "1: ADC voltage regulator enabled"] ENABLED = 1, } impl From<ADVREGEN_A> for bool { #[inline(always)] fn from(variant: ADVREGEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ADVREGEN`"] pub type ADVREGEN_R = crate::R<bool, ADVREGEN_A>; impl ADVREGEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ADVREGEN_A { match self.bits { false => ADVREGEN_A::DISABLED, true => ADVREGEN_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == ADVREGEN_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == ADVREGEN_A::ENABLED } } #[doc = "Write proxy for field `ADVREGEN`"] pub struct ADVREGEN_W<'a> { w: &'a mut W, } impl<'a> ADVREGEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADVREGEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "ADC voltage regulator disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(ADVREGEN_A::DISABLED) } #[doc = "ADC voltage regulator enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(ADVREGEN_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 << 28)) | (((value as u32) & 0x01) << 28); self.w } } #[doc = "ADC stop of injected conversion command\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum JADSTP_A { #[doc = "1: Stop conversion of channel"] STOP = 1, } impl From<JADSTP_A> for bool { #[inline(always)] fn from(variant: JADSTP_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `JADSTP`"] pub type JADSTP_R = crate::R<bool, JADSTP_A>; impl JADSTP_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<bool, JADSTP_A> { use crate::Variant::*; match self.bits { true => Val(JADSTP_A::STOP), i => Res(i), } } #[doc = "Checks if the value of the field is `STOP`"] #[inline(always)] pub fn is_stop(&self) -> bool { *self == JADSTP_A::STOP } } #[doc = "Write proxy for field `JADSTP`"] pub struct JADSTP_W<'a> { w: &'a mut W, } impl<'a> JADSTP_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: JADSTP_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Stop conversion of channel"] #[inline(always)] pub fn stop(self) -> &'a mut W { self.variant(JADSTP_A::STOP) } #[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 = "ADC stop of regular conversion command"] pub type ADSTP_A = JADSTP_A; #[doc = "Reader of field `ADSTP`"] pub type ADSTP_R = crate::R<bool, JADSTP_A>; #[doc = "Write proxy for field `ADSTP`"] pub struct ADSTP_W<'a> { w: &'a mut W, } impl<'a> ADSTP_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADSTP_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Stop conversion of channel"] #[inline(always)] pub fn stop(self) -> &'a mut W { self.variant(JADSTP_A::STOP) } #[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 = "ADC start of injected conversion\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum JADSTART_A { #[doc = "1: Starts conversion of channel"] START = 1, } impl From<JADSTART_A> for bool { #[inline(always)] fn from(variant: JADSTART_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `JADSTART`"] pub type JADSTART_R = crate::R<bool, JADSTART_A>; impl JADSTART_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<bool, JADSTART_A> { use crate::Variant::*; match self.bits { true => Val(JADSTART_A::START), i => Res(i), } } #[doc = "Checks if the value of the field is `START`"] #[inline(always)] pub fn is_start(&self) -> bool { *self == JADSTART_A::START } } #[doc = "Write proxy for field `JADSTART`"] pub struct JADSTART_W<'a> { w: &'a mut W, } impl<'a> JADSTART_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: JADSTART_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Starts conversion of channel"] #[inline(always)] pub fn start(self) -> &'a mut W { self.variant(JADSTART_A::START) } #[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 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "ADC start of regular conversion"] pub type ADSTART_A = JADSTART_A; #[doc = "Reader of field `ADSTART`"] pub type ADSTART_R = crate::R<bool, JADSTART_A>; #[doc = "Write proxy for field `ADSTART`"] pub struct ADSTART_W<'a> { w: &'a mut W, } impl<'a> ADSTART_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADSTART_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Starts conversion of channel"] #[inline(always)] pub fn start(self) -> &'a mut W { self.variant(JADSTART_A::START) } #[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 = "ADC disable command\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADDIS_A { #[doc = "0: Disable ADC conversion and go to power down mode"] DISABLE = 0, } impl From<ADDIS_A> for bool { #[inline(always)] fn from(variant: ADDIS_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ADDIS`"] pub type ADDIS_R = crate::R<bool, ADDIS_A>; impl ADDIS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<bool, ADDIS_A> { use crate::Variant::*; match self.bits { false => Val(ADDIS_A::DISABLE), i => Res(i), } } #[doc = "Checks if the value of the field is `DISABLE`"] #[inline(always)] pub fn is_disable(&self) -> bool { *self == ADDIS_A::DISABLE } } #[doc = "Write proxy for field `ADDIS`"] pub struct ADDIS_W<'a> { w: &'a mut W, } impl<'a> ADDIS_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADDIS_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Disable ADC conversion and go to power down mode"] #[inline(always)] pub fn disable(self) -> &'a mut W { self.variant(ADDIS_A::DISABLE) } #[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 = "ADC enable control\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADEN_A { #[doc = "1: Enable ADC"] ENABLE = 1, } impl From<ADEN_A> for bool { #[inline(always)] fn from(variant: ADEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ADEN`"] pub type ADEN_R = crate::R<bool, ADEN_A>; impl ADEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<bool, ADEN_A> { use crate::Variant::*; match self.bits { true => Val(ADEN_A::ENABLE), i => Res(i), } } #[doc = "Checks if the value of the field is `ENABLE`"] #[inline(always)] pub fn is_enable(&self) -> bool { *self == ADEN_A::ENABLE } } #[doc = "Write proxy for field `ADEN`"] pub struct ADEN_W<'a> { w: &'a mut W, } impl<'a> ADEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Enable ADC"] #[inline(always)] pub fn enable(self) -> &'a mut W { self.variant(ADEN_A::ENABLE) } #[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 } } impl R { #[doc = "Bit 31 - ADC calibration"] #[inline(always)] pub fn adcal(&self) -> ADCAL_R { ADCAL_R::new(((self.bits >> 31) & 0x01) != 0) } #[doc = "Bit 30 - Differential mode for calibration"] #[inline(always)] pub fn adcaldif(&self) -> ADCALDIF_R { ADCALDIF_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 29 - Deep-power-down enable"] #[inline(always)] pub fn deeppwd(&self) -> DEEPPWD_R { DEEPPWD_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 28 - ADC voltage regulator enable"] #[inline(always)] pub fn advregen(&self) -> ADVREGEN_R { ADVREGEN_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 5 - ADC stop of injected conversion command"] #[inline(always)] pub fn jadstp(&self) -> JADSTP_R { JADSTP_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4 - ADC stop of regular conversion command"] #[inline(always)] pub fn adstp(&self) -> ADSTP_R { ADSTP_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - ADC start of injected conversion"] #[inline(always)] pub fn jadstart(&self) -> JADSTART_R { JADSTART_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - ADC start of regular conversion"] #[inline(always)] pub fn adstart(&self) -> ADSTART_R { ADSTART_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - ADC disable command"] #[inline(always)] pub fn addis(&self) -> ADDIS_R { ADDIS_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - ADC enable control"] #[inline(always)] pub fn aden(&self) -> ADEN_R { ADEN_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 31 - ADC calibration"] #[inline(always)] pub fn adcal(&mut self) -> ADCAL_W { ADCAL_W { w: self } } #[doc = "Bit 30 - Differential mode for calibration"] #[inline(always)] pub fn adcaldif(&mut self) -> ADCALDIF_W { ADCALDIF_W { w: self } } #[doc = "Bit 29 - Deep-power-down enable"] #[inline(always)] pub fn deeppwd(&mut self) -> DEEPPWD_W { DEEPPWD_W { w: self } } #[doc = "Bit 28 - ADC voltage regulator enable"] #[inline(always)] pub fn advregen(&mut self) -> ADVREGEN_W { ADVREGEN_W { w: self } } #[doc = "Bit 5 - ADC stop of injected conversion command"] #[inline(always)] pub fn jadstp(&mut self) -> JADSTP_W { JADSTP_W { w: self } } #[doc = "Bit 4 - ADC stop of regular conversion command"] #[inline(always)] pub fn adstp(&mut self) -> ADSTP_W { ADSTP_W { w: self } } #[doc = "Bit 3 - ADC start of injected conversion"] #[inline(always)] pub fn jadstart(&mut self) -> JADSTART_W { JADSTART_W { w: self } } #[doc = "Bit 2 - ADC start of regular conversion"] #[inline(always)] pub fn adstart(&mut self) -> ADSTART_W { ADSTART_W { w: self } } #[doc = "Bit 1 - ADC disable command"] #[inline(always)] pub fn addis(&mut self) -> ADDIS_W { ADDIS_W { w: self } } #[doc = "Bit 0 - ADC enable control"] #[inline(always)] pub fn aden(&mut self) -> ADEN_W { ADEN_W { w: self } } }
use proptest::collection::SizeRange; use proptest::prop_assert_eq; use proptest::strategy::{Just, Strategy}; use proptest::test_runner::{Config, TestRunner}; use liblumen_alloc::erts::term::prelude::*; use crate::erlang::list_to_tuple_1::result; use crate::test::strategy; use crate::test::{with_process, with_process_arc}; #[test] fn without_list_errors_badarg() { with_process_arc(|arc_process| { TestRunner::new(Config::with_source_file(file!())) .run(&strategy::term::is_not_list(arc_process.clone()), |list| { prop_assert_badarg!( result(&arc_process, list), format!("list ({}) is not a list", list) ); Ok(()) }) .unwrap(); }); } #[test] fn with_empty_list_returns_empty_tuple() { with_process(|process| { let list = Term::NIL; assert_eq!(result(process, list), Ok(process.tuple_from_slice(&[]))); }); } #[test] fn with_non_empty_proper_list_returns_tuple() { with_process_arc(|arc_process| { let size_range: SizeRange = strategy::NON_EMPTY_RANGE_INCLUSIVE.clone().into(); TestRunner::new(Config::with_source_file(file!())) .run( &proptest::collection::vec(strategy::term(arc_process.clone()), size_range) .prop_map(|vec| { let list = arc_process.list_from_slice(&vec); let tuple = arc_process.tuple_from_slice(&vec); (list, tuple) }), |(list, tuple)| { prop_assert_eq!(result(&arc_process, list), Ok(tuple)); Ok(()) }, ) .unwrap(); }); } #[test] fn with_improper_list_errors_badarg() { run!( |arc_process| { ( Just(arc_process.clone()), strategy::term::list::improper(arc_process.clone()), ) }, |(arc_process, list)| { prop_assert_badarg!( result(&arc_process, list), format!("list ({}) is improper", list) ); Ok(()) }, ); } #[test] fn with_nested_list_returns_tuple_with_list_element() { with_process(|process| { // erlang doc: `[share, ['Ericsson_B', 163]]` let first_element = Atom::str_to_term("share"); let (second_element, list) = { let second_element = process.cons( Atom::str_to_term("Ericsson_B"), process.cons(process.integer(163), Term::NIL), ); let list = process.cons(first_element, process.cons(second_element, Term::NIL)); (second_element, list) }; assert_eq!( result(process, list), Ok(process.tuple_from_slice(&[first_element, second_element],)) ); }); }
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_upper_case_globals)] use intrinsics::{self, Intrinsic}; use llvm::{self, TypeKind}; use abi::{Abi, FnType, LlvmType, PassMode}; use mir::place::PlaceRef; use mir::operand::{OperandRef, OperandValue}; use base::*; use common::*; use declare; use glue; use type_::Type; use type_of::LayoutLlvmExt; use rustc::ty::{self, Ty}; use rustc::ty::layout::{HasDataLayout, LayoutOf}; use rustc::hir; use syntax::ast; use syntax::symbol::Symbol; use builder::Builder; use value::Value; use rustc::session::Session; use syntax_pos::Span; use std::cmp::Ordering; use std::iter; fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> { let llvm_name = match name { "sqrtf32" => "llvm.sqrt.f32", "sqrtf64" => "llvm.sqrt.f64", "powif32" => "llvm.powi.f32", "powif64" => "llvm.powi.f64", "sinf32" => "llvm.sin.f32", "sinf64" => "llvm.sin.f64", "cosf32" => "llvm.cos.f32", "cosf64" => "llvm.cos.f64", "powf32" => "llvm.pow.f32", "powf64" => "llvm.pow.f64", "expf32" => "llvm.exp.f32", "expf64" => "llvm.exp.f64", "exp2f32" => "llvm.exp2.f32", "exp2f64" => "llvm.exp2.f64", "logf32" => "llvm.log.f32", "logf64" => "llvm.log.f64", "log10f32" => "llvm.log10.f32", "log10f64" => "llvm.log10.f64", "log2f32" => "llvm.log2.f32", "log2f64" => "llvm.log2.f64", "fmaf32" => "llvm.fma.f32", "fmaf64" => "llvm.fma.f64", "fabsf32" => "llvm.fabs.f32", "fabsf64" => "llvm.fabs.f64", "copysignf32" => "llvm.copysign.f32", "copysignf64" => "llvm.copysign.f64", "floorf32" => "llvm.floor.f32", "floorf64" => "llvm.floor.f64", "ceilf32" => "llvm.ceil.f32", "ceilf64" => "llvm.ceil.f64", "truncf32" => "llvm.trunc.f32", "truncf64" => "llvm.trunc.f64", "rintf32" => "llvm.rint.f32", "rintf64" => "llvm.rint.f64", "nearbyintf32" => "llvm.nearbyint.f32", "nearbyintf64" => "llvm.nearbyint.f64", "roundf32" => "llvm.round.f32", "roundf64" => "llvm.round.f64", "assume" => "llvm.assume", "abort" => "llvm.trap", _ => return None }; Some(cx.get_intrinsic(&llvm_name)) } /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs, /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics, /// add them to librustc_codegen_llvm/context.rs pub fn codegen_intrinsic_call( bx: &Builder<'a, 'll, 'tcx>, callee_ty: Ty<'tcx>, fn_ty: &FnType<'tcx, Ty<'tcx>>, args: &[OperandRef<'ll, 'tcx>], llresult: &'ll Value, span: Span, ) { let cx = bx.cx; let tcx = cx.tcx; let (def_id, substs) = match callee_ty.sty { ty::TyFnDef(def_id, substs) => (def_id, substs), _ => bug!("expected fn item type, found {}", callee_ty) }; let sig = callee_ty.fn_sig(tcx); let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig); let arg_tys = sig.inputs(); let ret_ty = sig.output(); let name = &*tcx.item_name(def_id).as_str(); let llret_ty = cx.layout_of(ret_ty).llvm_type(cx); let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align); let simple = get_simple_intrinsic(cx, name); let llval = match name { _ if simple.is_some() => { bx.call(simple.unwrap(), &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None) } "unreachable" => { return; }, "likely" => { let expect = cx.get_intrinsic(&("llvm.expect.i1")); bx.call(expect, &[args[0].immediate(), C_bool(cx, true)], None) } "unlikely" => { let expect = cx.get_intrinsic(&("llvm.expect.i1")); bx.call(expect, &[args[0].immediate(), C_bool(cx, false)], None) } "try" => { try_intrinsic(bx, cx, args[0].immediate(), args[1].immediate(), args[2].immediate(), llresult); return; } "breakpoint" => { let llfn = cx.get_intrinsic(&("llvm.debugtrap")); bx.call(llfn, &[], None) } "size_of" => { let tp_ty = substs.type_at(0); C_usize(cx, cx.size_of(tp_ty).bytes()) } "size_of_val" => { let tp_ty = substs.type_at(0); if let OperandValue::Pair(_, meta) = args[0].val { let (llsize, _) = glue::size_and_align_of_dst(bx, tp_ty, Some(meta)); llsize } else { C_usize(cx, cx.size_of(tp_ty).bytes()) } } "min_align_of" => { let tp_ty = substs.type_at(0); C_usize(cx, cx.align_of(tp_ty).abi()) } "min_align_of_val" => { let tp_ty = substs.type_at(0); if let OperandValue::Pair(_, meta) = args[0].val { let (_, llalign) = glue::size_and_align_of_dst(bx, tp_ty, Some(meta)); llalign } else { C_usize(cx, cx.align_of(tp_ty).abi()) } } "pref_align_of" => { let tp_ty = substs.type_at(0); C_usize(cx, cx.align_of(tp_ty).pref()) } "type_name" => { let tp_ty = substs.type_at(0); let ty_name = Symbol::intern(&tp_ty.to_string()).as_str(); C_str_slice(cx, ty_name) } "type_id" => { C_u64(cx, cx.tcx.type_id_hash(substs.type_at(0))) } "init" => { let ty = substs.type_at(0); if !cx.layout_of(ty).is_zst() { // Just zero out the stack slot. // If we store a zero constant, LLVM will drown in vreg allocation for large data // structures, and the generated code will be awful. (A telltale sign of this is // large quantities of `mov [byte ptr foo],0` in the generated code.) memset_intrinsic(bx, false, ty, llresult, C_u8(cx, 0), C_usize(cx, 1)); } return; } // Effectively no-ops "uninit" => { return; } "needs_drop" => { let tp_ty = substs.type_at(0); C_bool(cx, bx.cx.type_needs_drop(tp_ty)) } "offset" => { let ptr = args[0].immediate(); let offset = args[1].immediate(); bx.inbounds_gep(ptr, &[offset]) } "arith_offset" => { let ptr = args[0].immediate(); let offset = args[1].immediate(); bx.gep(ptr, &[offset]) } "copy_nonoverlapping" => { copy_intrinsic(bx, false, false, substs.type_at(0), args[1].immediate(), args[0].immediate(), args[2].immediate()) } "copy" => { copy_intrinsic(bx, true, false, substs.type_at(0), args[1].immediate(), args[0].immediate(), args[2].immediate()) } "write_bytes" => { memset_intrinsic(bx, false, substs.type_at(0), args[0].immediate(), args[1].immediate(), args[2].immediate()) } "volatile_copy_nonoverlapping_memory" => { copy_intrinsic(bx, false, true, substs.type_at(0), args[0].immediate(), args[1].immediate(), args[2].immediate()) } "volatile_copy_memory" => { copy_intrinsic(bx, true, true, substs.type_at(0), args[0].immediate(), args[1].immediate(), args[2].immediate()) } "volatile_set_memory" => { memset_intrinsic(bx, true, substs.type_at(0), args[0].immediate(), args[1].immediate(), args[2].immediate()) } "volatile_load" | "unaligned_volatile_load" => { let tp_ty = substs.type_at(0); let mut ptr = args[0].immediate(); if let PassMode::Cast(ty) = fn_ty.ret.mode { ptr = bx.pointercast(ptr, ty.llvm_type(cx).ptr_to()); } let load = bx.volatile_load(ptr); let align = if name == "unaligned_volatile_load" { 1 } else { cx.align_of(tp_ty).abi() as u32 }; unsafe { llvm::LLVMSetAlignment(load, align); } to_immediate(bx, load, cx.layout_of(tp_ty)) }, "volatile_store" => { let dst = args[0].deref(bx.cx); args[1].val.volatile_store(bx, dst); return; }, "unaligned_volatile_store" => { let dst = args[0].deref(bx.cx); args[1].val.unaligned_volatile_store(bx, dst); return; }, "prefetch_read_data" | "prefetch_write_data" | "prefetch_read_instruction" | "prefetch_write_instruction" => { let expect = cx.get_intrinsic(&("llvm.prefetch")); let (rw, cache_type) = match name { "prefetch_read_data" => (0, 1), "prefetch_write_data" => (1, 1), "prefetch_read_instruction" => (0, 0), "prefetch_write_instruction" => (1, 0), _ => bug!() }; bx.call(expect, &[ args[0].immediate(), C_i32(cx, rw), args[1].immediate(), C_i32(cx, cache_type) ], None) }, "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" | "bitreverse" | "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" | "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "exact_div" => { let ty = arg_tys[0]; match int_type_width_signed(ty, cx) { Some((width, signed)) => match name { "ctlz" | "cttz" => { let y = C_bool(bx.cx, false); let llfn = cx.get_intrinsic(&format!("llvm.{}.i{}", name, width)); bx.call(llfn, &[args[0].immediate(), y], None) } "ctlz_nonzero" | "cttz_nonzero" => { let y = C_bool(bx.cx, true); let llvm_name = &format!("llvm.{}.i{}", &name[..4], width); let llfn = cx.get_intrinsic(llvm_name); bx.call(llfn, &[args[0].immediate(), y], None) } "ctpop" => bx.call(cx.get_intrinsic(&format!("llvm.ctpop.i{}", width)), &[args[0].immediate()], None), "bswap" => { if width == 8 { args[0].immediate() // byte swap a u8/i8 is just a no-op } else { bx.call(cx.get_intrinsic(&format!("llvm.bswap.i{}", width)), &[args[0].immediate()], None) } } "bitreverse" => { bx.call(cx.get_intrinsic(&format!("llvm.bitreverse.i{}", width)), &[args[0].immediate()], None) } "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => { let intrinsic = format!("llvm.{}{}.with.overflow.i{}", if signed { 's' } else { 'u' }, &name[..3], width); let llfn = bx.cx.get_intrinsic(&intrinsic); // Convert `i1` to a `bool`, and write it to the out parameter let pair = bx.call(llfn, &[ args[0].immediate(), args[1].immediate() ], None); let val = bx.extract_value(pair, 0); let overflow = bx.zext(bx.extract_value(pair, 1), Type::bool(cx)); let dest = result.project_field(bx, 0); bx.store(val, dest.llval, dest.align); let dest = result.project_field(bx, 1); bx.store(overflow, dest.llval, dest.align); return; }, "overflowing_add" => bx.add(args[0].immediate(), args[1].immediate()), "overflowing_sub" => bx.sub(args[0].immediate(), args[1].immediate()), "overflowing_mul" => bx.mul(args[0].immediate(), args[1].immediate()), "exact_div" => if signed { bx.exactsdiv(args[0].immediate(), args[1].immediate()) } else { bx.exactudiv(args[0].immediate(), args[1].immediate()) }, "unchecked_div" => if signed { bx.sdiv(args[0].immediate(), args[1].immediate()) } else { bx.udiv(args[0].immediate(), args[1].immediate()) }, "unchecked_rem" => if signed { bx.srem(args[0].immediate(), args[1].immediate()) } else { bx.urem(args[0].immediate(), args[1].immediate()) }, "unchecked_shl" => bx.shl(args[0].immediate(), args[1].immediate()), "unchecked_shr" => if signed { bx.ashr(args[0].immediate(), args[1].immediate()) } else { bx.lshr(args[0].immediate(), args[1].immediate()) }, _ => bug!(), }, None => { span_invalid_monomorphization_error( tcx.sess, span, &format!("invalid monomorphization of `{}` intrinsic: \ expected basic integer type, found `{}`", name, ty)); return; } } }, "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => { let sty = &arg_tys[0].sty; match float_type_width(sty) { Some(_width) => match name { "fadd_fast" => bx.fadd_fast(args[0].immediate(), args[1].immediate()), "fsub_fast" => bx.fsub_fast(args[0].immediate(), args[1].immediate()), "fmul_fast" => bx.fmul_fast(args[0].immediate(), args[1].immediate()), "fdiv_fast" => bx.fdiv_fast(args[0].immediate(), args[1].immediate()), "frem_fast" => bx.frem_fast(args[0].immediate(), args[1].immediate()), _ => bug!(), }, None => { span_invalid_monomorphization_error( tcx.sess, span, &format!("invalid monomorphization of `{}` intrinsic: \ expected basic float type, found `{}`", name, sty)); return; } } }, "discriminant_value" => { args[0].deref(bx.cx).codegen_get_discr(bx, ret_ty) } name if name.starts_with("simd_") => { match generic_simd_intrinsic(bx, name, callee_ty, args, ret_ty, llret_ty, span) { Ok(llval) => llval, Err(()) => return } } // This requires that atomic intrinsics follow a specific naming pattern: // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst name if name.starts_with("atomic_") => { use llvm::AtomicOrdering::*; let split: Vec<&str> = name.split('_').collect(); let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak"; let (order, failorder) = match split.len() { 2 => (SequentiallyConsistent, SequentiallyConsistent), 3 => match split[2] { "unordered" => (Unordered, Unordered), "relaxed" => (Monotonic, Monotonic), "acq" => (Acquire, Acquire), "rel" => (Release, Monotonic), "acqrel" => (AcquireRelease, Acquire), "failrelaxed" if is_cxchg => (SequentiallyConsistent, Monotonic), "failacq" if is_cxchg => (SequentiallyConsistent, Acquire), _ => cx.sess().fatal("unknown ordering in atomic intrinsic") }, 4 => match (split[2], split[3]) { ("acq", "failrelaxed") if is_cxchg => (Acquire, Monotonic), ("acqrel", "failrelaxed") if is_cxchg => (AcquireRelease, Monotonic), _ => cx.sess().fatal("unknown ordering in atomic intrinsic") }, _ => cx.sess().fatal("Atomic intrinsic not in correct format"), }; let invalid_monomorphization = |ty| { span_invalid_monomorphization_error(tcx.sess, span, &format!("invalid monomorphization of `{}` intrinsic: \ expected basic integer type, found `{}`", name, ty)); }; match split[1] { "cxchg" | "cxchgweak" => { let ty = substs.type_at(0); if int_type_width_signed(ty, cx).is_some() { let weak = if split[1] == "cxchgweak" { llvm::True } else { llvm::False }; let pair = bx.atomic_cmpxchg( args[0].immediate(), args[1].immediate(), args[2].immediate(), order, failorder, weak); let val = bx.extract_value(pair, 0); let success = bx.zext(bx.extract_value(pair, 1), Type::bool(bx.cx)); let dest = result.project_field(bx, 0); bx.store(val, dest.llval, dest.align); let dest = result.project_field(bx, 1); bx.store(success, dest.llval, dest.align); return; } else { return invalid_monomorphization(ty); } } "load" => { let ty = substs.type_at(0); if int_type_width_signed(ty, cx).is_some() { let align = cx.align_of(ty); bx.atomic_load(args[0].immediate(), order, align) } else { return invalid_monomorphization(ty); } } "store" => { let ty = substs.type_at(0); if int_type_width_signed(ty, cx).is_some() { let align = cx.align_of(ty); bx.atomic_store(args[1].immediate(), args[0].immediate(), order, align); return; } else { return invalid_monomorphization(ty); } } "fence" => { bx.atomic_fence(order, llvm::SynchronizationScope::CrossThread); return; } "singlethreadfence" => { bx.atomic_fence(order, llvm::SynchronizationScope::SingleThread); return; } // These are all AtomicRMW ops op => { let atom_op = match op { "xchg" => llvm::AtomicXchg, "xadd" => llvm::AtomicAdd, "xsub" => llvm::AtomicSub, "and" => llvm::AtomicAnd, "nand" => llvm::AtomicNand, "or" => llvm::AtomicOr, "xor" => llvm::AtomicXor, "max" => llvm::AtomicMax, "min" => llvm::AtomicMin, "umax" => llvm::AtomicUMax, "umin" => llvm::AtomicUMin, _ => cx.sess().fatal("unknown atomic operation") }; let ty = substs.type_at(0); if int_type_width_signed(ty, cx).is_some() { bx.atomic_rmw(atom_op, args[0].immediate(), args[1].immediate(), order) } else { return invalid_monomorphization(ty); } } } } "nontemporal_store" => { let dst = args[0].deref(bx.cx); args[1].val.nontemporal_store(bx, dst); return; } _ => { let intr = match Intrinsic::find(&name) { Some(intr) => intr, None => bug!("unknown intrinsic '{}'", name), }; fn one<T>(x: Vec<T>) -> T { assert_eq!(x.len(), 1); x.into_iter().next().unwrap() } fn ty_to_type(cx: &CodegenCx<'ll, '_>, t: &intrinsics::Type) -> Vec<&'ll Type> { use intrinsics::Type::*; match *t { Void => vec![Type::void(cx)], Integer(_signed, _width, llvm_width) => { vec![Type::ix(cx, llvm_width as u64)] } Float(x) => { match x { 32 => vec![Type::f32(cx)], 64 => vec![Type::f64(cx)], _ => bug!() } } Pointer(ref t, ref llvm_elem, _const) => { let t = llvm_elem.as_ref().unwrap_or(t); let elem = one(ty_to_type(cx, t)); vec![elem.ptr_to()] } Vector(ref t, ref llvm_elem, length) => { let t = llvm_elem.as_ref().unwrap_or(t); let elem = one(ty_to_type(cx, t)); vec![Type::vector(elem, length as u64)] } Aggregate(false, ref contents) => { let elems = contents.iter() .map(|t| one(ty_to_type(cx, t))) .collect::<Vec<_>>(); vec![Type::struct_(cx, &elems, false)] } Aggregate(true, ref contents) => { contents.iter() .flat_map(|t| ty_to_type(cx, t)) .collect() } } } // This allows an argument list like `foo, (bar, baz), // qux` to be converted into `foo, bar, baz, qux`, integer // arguments to be truncated as needed and pointers to be // cast. fn modify_as_needed( bx: &Builder<'a, 'll, 'tcx>, t: &intrinsics::Type, arg: &OperandRef<'ll, 'tcx>, ) -> Vec<&'ll Value> { match *t { intrinsics::Type::Aggregate(true, ref contents) => { // We found a tuple that needs squishing! So // run over the tuple and load each field. // // This assumes the type is "simple", i.e. no // destructors, and the contents are SIMD // etc. assert!(!bx.cx.type_needs_drop(arg.layout.ty)); let (ptr, align) = match arg.val { OperandValue::Ref(ptr, align) => (ptr, align), _ => bug!() }; let arg = PlaceRef::new_sized(ptr, arg.layout, align); (0..contents.len()).map(|i| { arg.project_field(bx, i).load(bx).immediate() }).collect() } intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => { let llvm_elem = one(ty_to_type(bx.cx, llvm_elem)); vec![bx.pointercast(arg.immediate(), llvm_elem.ptr_to())] } intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => { let llvm_elem = one(ty_to_type(bx.cx, llvm_elem)); vec![bx.bitcast(arg.immediate(), Type::vector(llvm_elem, length as u64))] } intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => { // the LLVM intrinsic uses a smaller integer // size than the C intrinsic's signature, so // we have to trim it down here. vec![bx.trunc(arg.immediate(), Type::ix(bx.cx, llvm_width as u64))] } _ => vec![arg.immediate()], } } let inputs = intr.inputs.iter() .flat_map(|t| ty_to_type(cx, t)) .collect::<Vec<_>>(); let outputs = one(ty_to_type(cx, &intr.output)); let llargs: Vec<_> = intr.inputs.iter().zip(args).flat_map(|(t, arg)| { modify_as_needed(bx, t, arg) }).collect(); assert_eq!(inputs.len(), llargs.len()); let val = match intr.definition { intrinsics::IntrinsicDef::Named(name) => { let f = declare::declare_cfn(cx, name, Type::func(&inputs, outputs)); bx.call(f, &llargs, None) } }; match *intr.output { intrinsics::Type::Aggregate(flatten, ref elems) => { // the output is a tuple so we need to munge it properly assert!(!flatten); for i in 0..elems.len() { let dest = result.project_field(bx, i); let val = bx.extract_value(val, i as u64); bx.store(val, dest.llval, dest.align); } return; } _ => val, } } }; if !fn_ty.ret.is_ignore() { if let PassMode::Cast(ty) = fn_ty.ret.mode { let ptr = bx.pointercast(result.llval, ty.llvm_type(cx).ptr_to()); bx.store(llval, ptr, result.align); } else { OperandRef::from_immediate_or_packed_pair(bx, llval, result.layout) .val.store(bx, result); } } } fn copy_intrinsic( bx: &Builder<'a, 'll, 'tcx>, allow_overlap: bool, volatile: bool, ty: Ty<'tcx>, dst: &'ll Value, src: &'ll Value, count: &'ll Value, ) -> &'ll Value { let cx = bx.cx; let (size, align) = cx.size_and_align_of(ty); let size = C_usize(cx, size.bytes()); let align = C_i32(cx, align.abi() as i32); let operation = if allow_overlap { "memmove" } else { "memcpy" }; let name = format!("llvm.{}.p0i8.p0i8.i{}", operation, cx.data_layout().pointer_size.bits()); let dst_ptr = bx.pointercast(dst, Type::i8p(cx)); let src_ptr = bx.pointercast(src, Type::i8p(cx)); let llfn = cx.get_intrinsic(&name); bx.call(llfn, &[dst_ptr, src_ptr, bx.mul(size, count), align, C_bool(cx, volatile)], None) } fn memset_intrinsic( bx: &Builder<'a, 'll, 'tcx>, volatile: bool, ty: Ty<'tcx>, dst: &'ll Value, val: &'ll Value, count: &'ll Value ) -> &'ll Value { let cx = bx.cx; let (size, align) = cx.size_and_align_of(ty); let size = C_usize(cx, size.bytes()); let align = C_i32(cx, align.abi() as i32); let dst = bx.pointercast(dst, Type::i8p(cx)); call_memset(bx, dst, val, bx.mul(size, count), align, volatile) } fn try_intrinsic( bx: &Builder<'a, 'll, 'tcx>, cx: &CodegenCx<'ll, 'tcx>, func: &'ll Value, data: &'ll Value, local_ptr: &'ll Value, dest: &'ll Value, ) { if bx.sess().no_landing_pads() { bx.call(func, &[data], None); let ptr_align = bx.tcx().data_layout.pointer_align; bx.store(C_null(Type::i8p(&bx.cx)), dest, ptr_align); } else if wants_msvc_seh(bx.sess()) { codegen_msvc_try(bx, cx, func, data, local_ptr, dest); } else { codegen_gnu_try(bx, cx, func, data, local_ptr, dest); } } // MSVC's definition of the `rust_try` function. // // This implementation uses the new exception handling instructions in LLVM // which have support in LLVM for SEH on MSVC targets. Although these // instructions are meant to work for all targets, as of the time of this // writing, however, LLVM does not recommend the usage of these new instructions // as the old ones are still more optimized. fn codegen_msvc_try( bx: &Builder<'a, 'll, 'tcx>, cx: &CodegenCx<'ll, 'tcx>, func: &'ll Value, data: &'ll Value, local_ptr: &'ll Value, dest: &'ll Value, ) { let llfn = get_rust_try_fn(cx, &mut |bx| { let cx = bx.cx; bx.set_personality_fn(bx.cx.eh_personality()); let normal = bx.build_sibling_block("normal"); let catchswitch = bx.build_sibling_block("catchswitch"); let catchpad = bx.build_sibling_block("catchpad"); let caught = bx.build_sibling_block("caught"); let func = llvm::get_param(bx.llfn(), 0); let data = llvm::get_param(bx.llfn(), 1); let local_ptr = llvm::get_param(bx.llfn(), 2); // We're generating an IR snippet that looks like: // // declare i32 @rust_try(%func, %data, %ptr) { // %slot = alloca i64* // invoke %func(%data) to label %normal unwind label %catchswitch // // normal: // ret i32 0 // // catchswitch: // %cs = catchswitch within none [%catchpad] unwind to caller // // catchpad: // %tok = catchpad within %cs [%type_descriptor, 0, %slot] // %ptr[0] = %slot[0] // %ptr[1] = %slot[1] // catchret from %tok to label %caught // // caught: // ret i32 1 // } // // This structure follows the basic usage of throw/try/catch in LLVM. // For example, compile this C++ snippet to see what LLVM generates: // // #include <stdint.h> // // int bar(void (*foo)(void), uint64_t *ret) { // try { // foo(); // return 0; // } catch(uint64_t a[2]) { // ret[0] = a[0]; // ret[1] = a[1]; // return 1; // } // } // // More information can be found in libstd's seh.rs implementation. let i64p = Type::i64(cx).ptr_to(); let ptr_align = bx.tcx().data_layout.pointer_align; let slot = bx.alloca(i64p, "slot", ptr_align); bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None); normal.ret(C_i32(cx, 0)); let cs = catchswitch.catch_switch(None, None, 1); catchswitch.add_handler(cs, catchpad.llbb()); let tcx = cx.tcx; let tydesc = match tcx.lang_items().msvc_try_filter() { Some(did) => ::consts::get_static(cx, did), None => bug!("msvc_try_filter not defined"), }; let tok = catchpad.catch_pad(cs, &[tydesc, C_i32(cx, 0), slot]); let addr = catchpad.load(slot, ptr_align); let i64_align = bx.tcx().data_layout.i64_align; let arg1 = catchpad.load(addr, i64_align); let val1 = C_i32(cx, 1); let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), i64_align); let local_ptr = catchpad.bitcast(local_ptr, i64p); catchpad.store(arg1, local_ptr, i64_align); catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), i64_align); catchpad.catch_ret(tok, caught.llbb()); caught.ret(C_i32(cx, 1)); }); // Note that no invoke is used here because by definition this function // can't panic (that's what it's catching). let ret = bx.call(llfn, &[func, data, local_ptr], None); let i32_align = bx.tcx().data_layout.i32_align; bx.store(ret, dest, i32_align); } // Definition of the standard "try" function for Rust using the GNU-like model // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke // instructions). // // This codegen is a little surprising because we always call a shim // function instead of inlining the call to `invoke` manually here. This is done // because in LLVM we're only allowed to have one personality per function // definition. The call to the `try` intrinsic is being inlined into the // function calling it, and that function may already have other personality // functions in play. By calling a shim we're guaranteed that our shim will have // the right personality function. fn codegen_gnu_try( bx: &Builder<'a, 'll, 'tcx>, cx: &CodegenCx<'ll, 'tcx>, func: &'ll Value, data: &'ll Value, local_ptr: &'ll Value, dest: &'ll Value, ) { let llfn = get_rust_try_fn(cx, &mut |bx| { let cx = bx.cx; // Codegens the shims described above: // // bx: // invoke %func(%args...) normal %normal unwind %catch // // normal: // ret 0 // // catch: // (ptr, _) = landingpad // store ptr, %local_ptr // ret 1 // // Note that the `local_ptr` data passed into the `try` intrinsic is // expected to be `*mut *mut u8` for this to actually work, but that's // managed by the standard library. let then = bx.build_sibling_block("then"); let catch = bx.build_sibling_block("catch"); let func = llvm::get_param(bx.llfn(), 0); let data = llvm::get_param(bx.llfn(), 1); let local_ptr = llvm::get_param(bx.llfn(), 2); bx.invoke(func, &[data], then.llbb(), catch.llbb(), None); then.ret(C_i32(cx, 0)); // Type indicator for the exception being thrown. // // The first value in this tuple is a pointer to the exception object // being thrown. The second value is a "selector" indicating which of // the landing pad clauses the exception's type had been matched to. // rust_try ignores the selector. let lpad_ty = Type::struct_(cx, &[Type::i8p(cx), Type::i32(cx)], false); let vals = catch.landing_pad(lpad_ty, bx.cx.eh_personality(), 1); catch.add_clause(vals, C_null(Type::i8p(cx))); let ptr = catch.extract_value(vals, 0); let ptr_align = bx.tcx().data_layout.pointer_align; catch.store(ptr, catch.bitcast(local_ptr, Type::i8p(cx).ptr_to()), ptr_align); catch.ret(C_i32(cx, 1)); }); // Note that no invoke is used here because by definition this function // can't panic (that's what it's catching). let ret = bx.call(llfn, &[func, data, local_ptr], None); let i32_align = bx.tcx().data_layout.i32_align; bx.store(ret, dest, i32_align); } // Helper function to give a Block to a closure to codegen a shim function. // This is currently primarily used for the `try` intrinsic functions above. fn gen_fn<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, name: &str, inputs: Vec<Ty<'tcx>>, output: Ty<'tcx>, codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>), ) -> &'ll Value { let rust_fn_ty = cx.tcx.mk_fn_ptr(ty::Binder::bind(cx.tcx.mk_fn_sig( inputs.into_iter(), output, false, hir::Unsafety::Unsafe, Abi::Rust ))); let llfn = declare::define_internal_fn(cx, name, rust_fn_ty); let bx = Builder::new_block(cx, llfn, "entry-block"); codegen(bx); llfn } // Helper function used to get a handle to the `__rust_try` function used to // catch exceptions. // // This function is only generated once and is then cached. fn get_rust_try_fn<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>), ) -> &'ll Value { if let Some(llfn) = cx.rust_try_fn.get() { return llfn; } // Define the type up front for the signature of the rust_try function. let tcx = cx.tcx; let i8p = tcx.mk_mut_ptr(tcx.types.i8); let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig( iter::once(i8p), tcx.mk_nil(), false, hir::Unsafety::Unsafe, Abi::Rust ))); let output = tcx.types.i32; let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen); cx.rust_try_fn.set(Some(rust_try)); return rust_try } fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) { span_err!(a, b, E0511, "{}", c); } fn generic_simd_intrinsic( bx: &Builder<'a, 'll, 'tcx>, name: &str, callee_ty: Ty<'tcx>, args: &[OperandRef<'ll, 'tcx>], ret_ty: Ty<'tcx>, llret_ty: &'ll Type, span: Span ) -> Result<&'ll Value, ()> { // macros for error handling: macro_rules! emit_error { ($msg: tt) => { emit_error!($msg, ) }; ($msg: tt, $($fmt: tt)*) => { span_invalid_monomorphization_error( bx.sess(), span, &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg), name, $($fmt)*)); } } macro_rules! return_error { ($($fmt: tt)*) => { { emit_error!($($fmt)*); return Err(()); } } } macro_rules! require { ($cond: expr, $($fmt: tt)*) => { if !$cond { return_error!($($fmt)*); } }; } macro_rules! require_simd { ($ty: expr, $position: expr) => { require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty) } } let tcx = bx.tcx(); let sig = tcx.normalize_erasing_late_bound_regions( ty::ParamEnv::reveal_all(), &callee_ty.fn_sig(tcx), ); let arg_tys = sig.inputs(); // every intrinsic takes a SIMD vector as its first argument require_simd!(arg_tys[0], "input"); let in_ty = arg_tys[0]; let in_elem = arg_tys[0].simd_type(tcx); let in_len = arg_tys[0].simd_size(tcx); let comparison = match name { "simd_eq" => Some(hir::BinOpKind::Eq), "simd_ne" => Some(hir::BinOpKind::Ne), "simd_lt" => Some(hir::BinOpKind::Lt), "simd_le" => Some(hir::BinOpKind::Le), "simd_gt" => Some(hir::BinOpKind::Gt), "simd_ge" => Some(hir::BinOpKind::Ge), _ => None }; if let Some(cmp_op) = comparison { require_simd!(ret_ty, "return"); let out_len = ret_ty.simd_size(tcx); require!(in_len == out_len, "expected return type with length {} (same as input type `{}`), \ found `{}` with length {}", in_len, in_ty, ret_ty, out_len); require!(llret_ty.element_type().kind() == TypeKind::Integer, "expected return type with integer elements, found `{}` with non-integer `{}`", ret_ty, ret_ty.simd_type(tcx)); return Ok(compare_simd_types(bx, args[0].immediate(), args[1].immediate(), in_elem, llret_ty, cmp_op)) } if name.starts_with("simd_shuffle") { let n: usize = match name["simd_shuffle".len()..].parse() { Ok(n) => n, Err(_) => span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?") }; require_simd!(ret_ty, "return"); let out_len = ret_ty.simd_size(tcx); require!(out_len == n, "expected return type of length {}, found `{}` with length {}", n, ret_ty, out_len); require!(in_elem == ret_ty.simd_type(tcx), "expected return element type `{}` (element of input `{}`), \ found `{}` with element type `{}`", in_elem, in_ty, ret_ty, ret_ty.simd_type(tcx)); let total_len = in_len as u128 * 2; let vector = args[2].immediate(); let indices: Option<Vec<_>> = (0..n) .map(|i| { let arg_idx = i; let val = const_get_elt(vector, i as u64); match const_to_opt_u128(val, true) { None => { emit_error!("shuffle index #{} is not a constant", arg_idx); None } Some(idx) if idx >= total_len => { emit_error!("shuffle index #{} is out of bounds (limit {})", arg_idx, total_len); None } Some(idx) => Some(C_i32(bx.cx, idx as i32)), } }) .collect(); let indices = match indices { Some(i) => i, None => return Ok(C_null(llret_ty)) }; return Ok(bx.shuffle_vector(args[0].immediate(), args[1].immediate(), C_vector(&indices))) } if name == "simd_insert" { require!(in_elem == arg_tys[2], "expected inserted type `{}` (element of input `{}`), found `{}`", in_elem, in_ty, arg_tys[2]); return Ok(bx.insert_element(args[0].immediate(), args[2].immediate(), args[1].immediate())) } if name == "simd_extract" { require!(ret_ty == in_elem, "expected return type `{}` (element of input `{}`), found `{}`", in_elem, in_ty, ret_ty); return Ok(bx.extract_element(args[0].immediate(), args[1].immediate())) } if name == "simd_select" { let m_elem_ty = in_elem; let m_len = in_len; let v_len = arg_tys[1].simd_size(tcx); require!(m_len == v_len, "mismatched lengths: mask length `{}` != other vector length `{}`", m_len, v_len ); match m_elem_ty.sty { ty::TyInt(_) => {}, _ => { return_error!("mask element type is `{}`, expected `i_`", m_elem_ty); } } // truncate the mask to a vector of i1s let i1 = Type::i1(bx.cx); let i1xn = Type::vector(i1, m_len as u64); let m_i1s = bx.trunc(args[0].immediate(), i1xn); return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate())); } fn simd_simple_float_intrinsic( name: &str, in_elem: &::rustc::ty::TyS, in_ty: &::rustc::ty::TyS, in_len: usize, bx: &Builder<'a, 'll, 'tcx>, span: Span, args: &[OperandRef<'ll, 'tcx>], ) -> Result<&'ll Value, ()> { macro_rules! emit_error { ($msg: tt) => { emit_error!($msg, ) }; ($msg: tt, $($fmt: tt)*) => { span_invalid_monomorphization_error( bx.sess(), span, &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg), name, $($fmt)*)); } } macro_rules! return_error { ($($fmt: tt)*) => { { emit_error!($($fmt)*); return Err(()); } } } let ety = match in_elem.sty { ty::TyFloat(f) if f.bit_width() == 32 => { if in_len < 2 || in_len > 16 { return_error!( "unsupported floating-point vector `{}` with length `{}` \ out-of-range [2, 16]", in_ty, in_len); } "f32" }, ty::TyFloat(f) if f.bit_width() == 64 => { if in_len < 2 || in_len > 8 { return_error!("unsupported floating-point vector `{}` with length `{}` \ out-of-range [2, 8]", in_ty, in_len); } "f64" }, ty::TyFloat(f) => { return_error!("unsupported element type `{}` of floating-point vector `{}`", f, in_ty); }, _ => { return_error!("`{}` is not a floating-point type", in_ty); } }; let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety); let intrinsic = bx.cx.get_intrinsic(&llvm_name); let c = bx.call(intrinsic, &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(), None); unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) }; return Ok(c); } if name == "simd_fsqrt" { return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args); } if name == "simd_fsin" { return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args); } if name == "simd_fcos" { return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args); } if name == "simd_fabs" { return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args); } if name == "simd_floor" { return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args); } if name == "simd_ceil" { return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args); } if name == "simd_fexp" { return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args); } if name == "simd_fexp2" { return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args); } if name == "simd_flog10" { return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args); } if name == "simd_flog2" { return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args); } if name == "simd_flog" { return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args); } if name == "simd_fpowi" { return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args); } if name == "simd_fpow" { return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args); } if name == "simd_fma" { return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args); } // FIXME: use: // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81 fn llvm_vector_str(elem_ty: ty::Ty, vec_len: usize, no_pointers: usize) -> String { let p0s: String = "p0".repeat(no_pointers); match elem_ty.sty { ty::TyInt(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()), ty::TyUint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()), ty::TyFloat(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()), _ => unreachable!(), } } fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty, vec_len: usize, mut no_pointers: usize) -> &'ll Type { // FIXME: use cx.layout_of(ty).llvm_type() ? let mut elem_ty = match elem_ty.sty { ty::TyInt(v) => Type::int_from_ty(cx, v), ty::TyUint(v) => Type::uint_from_ty(cx, v), ty::TyFloat(v) => Type::float_from_ty(cx, v), _ => unreachable!(), }; while no_pointers > 0 { elem_ty = elem_ty.ptr_to(); no_pointers -= 1; } Type::vector(elem_ty, vec_len as u64) } if name == "simd_gather" { // simd_gather(values: <N x T>, pointers: <N x *_ T>, // mask: <N x i{M}>) -> <N x T> // * N: number of elements in the input vectors // * T: type of the element to load // * M: any integer width is supported, will be truncated to i1 // All types must be simd vector types require_simd!(in_ty, "first"); require_simd!(arg_tys[1], "second"); require_simd!(arg_tys[2], "third"); require_simd!(ret_ty, "return"); // Of the same length: require!(in_len == arg_tys[1].simd_size(tcx), "expected {} argument with length {} (same as input type `{}`), \ found `{}` with length {}", "second", in_len, in_ty, arg_tys[1], arg_tys[1].simd_size(tcx)); require!(in_len == arg_tys[2].simd_size(tcx), "expected {} argument with length {} (same as input type `{}`), \ found `{}` with length {}", "third", in_len, in_ty, arg_tys[2], arg_tys[2].simd_size(tcx)); // The return type must match the first argument type require!(ret_ty == in_ty, "expected return type `{}`, found `{}`", in_ty, ret_ty); // This counts how many pointers fn ptr_count(t: ty::Ty) -> usize { match t.sty { ty::TyRawPtr(p) => 1 + ptr_count(p.ty), _ => 0, } } // Non-ptr type fn non_ptr(t: ty::Ty) -> ty::Ty { match t.sty { ty::TyRawPtr(p) => non_ptr(p.ty), _ => t, } } // The second argument must be a simd vector with an element type that's a pointer // to the element type of the first argument let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty { ty::TyRawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx))), _ => { require!(false, "expected element type `{}` of second argument `{}` \ to be a pointer to the element type `{}` of the first \ argument `{}`, found `{}` != `*_ {}`", arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty, arg_tys[1].simd_type(tcx).sty, in_elem); unreachable!(); } }; assert!(pointer_count > 0); assert!(pointer_count - 1 == ptr_count(arg_tys[0].simd_type(tcx))); assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx))); // The element type of the third argument must be a signed integer type of any width: match arg_tys[2].simd_type(tcx).sty { ty::TyInt(_) => (), _ => { require!(false, "expected element type `{}` of third argument `{}` \ to be a signed integer type", arg_tys[2].simd_type(tcx).sty, arg_tys[2]); } } // Alignment of T, must be a constant integer value: let alignment_ty = Type::i32(bx.cx); let alignment = C_i32(bx.cx, bx.cx.align_of(in_elem).abi() as i32); // Truncate the mask vector to a vector of i1s: let (mask, mask_ty) = { let i1 = Type::i1(bx.cx); let i1xn = Type::vector(i1, in_len as u64); (bx.trunc(args[2].immediate(), i1xn), i1xn) }; // Type of the vector of pointers: let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count); let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count); // Type of the vector of elements: let llvm_elem_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count - 1); let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1); let llvm_intrinsic = format!("llvm.masked.gather.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str); let f = declare::declare_cfn(bx.cx, &llvm_intrinsic, Type::func(&[llvm_pointer_vec_ty, alignment_ty, mask_ty, llvm_elem_vec_ty], llvm_elem_vec_ty)); llvm::SetUnnamedAddr(f, false); let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()], None); return Ok(v); } if name == "simd_scatter" { // simd_scatter(values: <N x T>, pointers: <N x *mut T>, // mask: <N x i{M}>) -> () // * N: number of elements in the input vectors // * T: type of the element to load // * M: any integer width is supported, will be truncated to i1 // All types must be simd vector types require_simd!(in_ty, "first"); require_simd!(arg_tys[1], "second"); require_simd!(arg_tys[2], "third"); // Of the same length: require!(in_len == arg_tys[1].simd_size(tcx), "expected {} argument with length {} (same as input type `{}`), \ found `{}` with length {}", "second", in_len, in_ty, arg_tys[1], arg_tys[1].simd_size(tcx)); require!(in_len == arg_tys[2].simd_size(tcx), "expected {} argument with length {} (same as input type `{}`), \ found `{}` with length {}", "third", in_len, in_ty, arg_tys[2], arg_tys[2].simd_size(tcx)); // This counts how many pointers fn ptr_count(t: ty::Ty) -> usize { match t.sty { ty::TyRawPtr(p) => 1 + ptr_count(p.ty), _ => 0, } } // Non-ptr type fn non_ptr(t: ty::Ty) -> ty::Ty { match t.sty { ty::TyRawPtr(p) => non_ptr(p.ty), _ => t, } } // The second argument must be a simd vector with an element type that's a pointer // to the element type of the first argument let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty { ty::TyRawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable => (ptr_count(arg_tys[1].simd_type(tcx)), non_ptr(arg_tys[1].simd_type(tcx))), _ => { require!(false, "expected element type `{}` of second argument `{}` \ to be a pointer to the element type `{}` of the first \ argument `{}`, found `{}` != `*mut {}`", arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty, arg_tys[1].simd_type(tcx).sty, in_elem); unreachable!(); } }; assert!(pointer_count > 0); assert!(pointer_count - 1 == ptr_count(arg_tys[0].simd_type(tcx))); assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx))); // The element type of the third argument must be a signed integer type of any width: match arg_tys[2].simd_type(tcx).sty { ty::TyInt(_) => (), _ => { require!(false, "expected element type `{}` of third argument `{}` \ to be a signed integer type", arg_tys[2].simd_type(tcx).sty, arg_tys[2]); } } // Alignment of T, must be a constant integer value: let alignment_ty = Type::i32(bx.cx); let alignment = C_i32(bx.cx, bx.cx.align_of(in_elem).abi() as i32); // Truncate the mask vector to a vector of i1s: let (mask, mask_ty) = { let i1 = Type::i1(bx.cx); let i1xn = Type::vector(i1, in_len as u64); (bx.trunc(args[2].immediate(), i1xn), i1xn) }; let ret_t = Type::void(bx.cx); // Type of the vector of pointers: let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count); let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count); // Type of the vector of elements: let llvm_elem_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count - 1); let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1); let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}", llvm_elem_vec_str, llvm_pointer_vec_str); let f = declare::declare_cfn(bx.cx, &llvm_intrinsic, Type::func(&[llvm_elem_vec_ty, llvm_pointer_vec_ty, alignment_ty, mask_ty], ret_t)); llvm::SetUnnamedAddr(f, false); let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask], None); return Ok(v); } macro_rules! arith_red { ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => { if name == $name { require!(ret_ty == in_elem, "expected return type `{}` (element of input `{}`), found `{}`", in_elem, in_ty, ret_ty); return match in_elem.sty { ty::TyInt(_) | ty::TyUint(_) => { let r = bx.$integer_reduce(args[0].immediate()); if $ordered { // if overflow occurs, the result is the // mathematical result modulo 2^n: if name.contains("mul") { Ok(bx.mul(args[1].immediate(), r)) } else { Ok(bx.add(args[1].immediate(), r)) } } else { Ok(bx.$integer_reduce(args[0].immediate())) } }, ty::TyFloat(f) => { // ordered arithmetic reductions take an accumulator let acc = if $ordered { let acc = args[1].immediate(); // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734 // * if the accumulator of the fadd isn't 0, incorrect // code is generated // * if the accumulator of the fmul isn't 1, incorrect // code is generated match const_get_real(acc) { None => return_error!("accumulator of {} is not a constant", $name), Some((v, loses_info)) => { if $name.contains("mul") && v != 1.0_f64 { return_error!("accumulator of {} is not 1.0", $name); } else if $name.contains("add") && v != 0.0_f64 { return_error!("accumulator of {} is not 0.0", $name); } else if loses_info { return_error!("accumulator of {} loses information", $name); } } } acc } else { // unordered arithmetic reductions do not: match f.bit_width() { 32 => C_undef(Type::f32(bx.cx)), 64 => C_undef(Type::f64(bx.cx)), v => { return_error!(r#" unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#, $name, in_ty, in_elem, v, ret_ty ) } } }; Ok(bx.$float_reduce(acc, args[0].immediate())) } _ => { return_error!( "unsupported {} from `{}` with element `{}` to `{}`", $name, in_ty, in_elem, ret_ty ) }, } } } } arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true); arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true); arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false); arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false); macro_rules! minmax_red { ($name:tt: $int_red:ident, $float_red:ident) => { if name == $name { require!(ret_ty == in_elem, "expected return type `{}` (element of input `{}`), found `{}`", in_elem, in_ty, ret_ty); return match in_elem.sty { ty::TyInt(_i) => { Ok(bx.$int_red(args[0].immediate(), true)) }, ty::TyUint(_u) => { Ok(bx.$int_red(args[0].immediate(), false)) }, ty::TyFloat(_f) => { Ok(bx.$float_red(args[0].immediate())) } _ => { return_error!("unsupported {} from `{}` with element `{}` to `{}`", $name, in_ty, in_elem, ret_ty) }, } } } } minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin); minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax); minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast); minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast); macro_rules! bitwise_red { ($name:tt : $red:ident, $boolean:expr) => { if name == $name { let input = if !$boolean { require!(ret_ty == in_elem, "expected return type `{}` (element of input `{}`), found `{}`", in_elem, in_ty, ret_ty); args[0].immediate() } else { match in_elem.sty { ty::TyInt(_) | ty::TyUint(_) => {}, _ => { return_error!("unsupported {} from `{}` with element `{}` to `{}`", $name, in_ty, in_elem, ret_ty) } } // boolean reductions operate on vectors of i1s: let i1 = Type::i1(bx.cx); let i1xn = Type::vector(i1, in_len as u64); bx.trunc(args[0].immediate(), i1xn) }; return match in_elem.sty { ty::TyInt(_) | ty::TyUint(_) => { let r = bx.$red(input); Ok( if !$boolean { r } else { bx.zext(r, Type::bool(bx.cx)) } ) }, _ => { return_error!("unsupported {} from `{}` with element `{}` to `{}`", $name, in_ty, in_elem, ret_ty) }, } } } } bitwise_red!("simd_reduce_and": vector_reduce_and, false); bitwise_red!("simd_reduce_or": vector_reduce_or, false); bitwise_red!("simd_reduce_xor": vector_reduce_xor, false); bitwise_red!("simd_reduce_all": vector_reduce_and, true); bitwise_red!("simd_reduce_any": vector_reduce_or, true); if name == "simd_cast" { require_simd!(ret_ty, "return"); let out_len = ret_ty.simd_size(tcx); require!(in_len == out_len, "expected return type with length {} (same as input type `{}`), \ found `{}` with length {}", in_len, in_ty, ret_ty, out_len); // casting cares about nominal type, not just structural type let out_elem = ret_ty.simd_type(tcx); if in_elem == out_elem { return Ok(args[0].immediate()); } enum Style { Float, Int(/* is signed? */ bool), Unsupported } let (in_style, in_width) = match in_elem.sty { // vectors of pointer-sized integers should've been // disallowed before here, so this unwrap is safe. ty::TyInt(i) => (Style::Int(true), i.bit_width().unwrap()), ty::TyUint(u) => (Style::Int(false), u.bit_width().unwrap()), ty::TyFloat(f) => (Style::Float, f.bit_width()), _ => (Style::Unsupported, 0) }; let (out_style, out_width) = match out_elem.sty { ty::TyInt(i) => (Style::Int(true), i.bit_width().unwrap()), ty::TyUint(u) => (Style::Int(false), u.bit_width().unwrap()), ty::TyFloat(f) => (Style::Float, f.bit_width()), _ => (Style::Unsupported, 0) }; match (in_style, out_style) { (Style::Int(in_is_signed), Style::Int(_)) => { return Ok(match in_width.cmp(&out_width) { Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty), Ordering::Equal => args[0].immediate(), Ordering::Less => if in_is_signed { bx.sext(args[0].immediate(), llret_ty) } else { bx.zext(args[0].immediate(), llret_ty) } }) } (Style::Int(in_is_signed), Style::Float) => { return Ok(if in_is_signed { bx.sitofp(args[0].immediate(), llret_ty) } else { bx.uitofp(args[0].immediate(), llret_ty) }) } (Style::Float, Style::Int(out_is_signed)) => { return Ok(if out_is_signed { bx.fptosi(args[0].immediate(), llret_ty) } else { bx.fptoui(args[0].immediate(), llret_ty) }) } (Style::Float, Style::Float) => { return Ok(match in_width.cmp(&out_width) { Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty), Ordering::Equal => args[0].immediate(), Ordering::Less => bx.fpext(args[0].immediate(), llret_ty) }) } _ => {/* Unsupported. Fallthrough. */} } require!(false, "unsupported cast from `{}` with element `{}` to `{}` with element `{}`", in_ty, in_elem, ret_ty, out_elem); } macro_rules! arith { ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => { $(if name == stringify!($name) { match in_elem.sty { $($(ty::$p(_))|* => { return Ok(bx.$call(args[0].immediate(), args[1].immediate())) })* _ => {}, } require!(false, "unsupported operation on `{}` with element `{}`", in_ty, in_elem) })* } } arith! { simd_add: TyUint, TyInt => add, TyFloat => fadd; simd_sub: TyUint, TyInt => sub, TyFloat => fsub; simd_mul: TyUint, TyInt => mul, TyFloat => fmul; simd_div: TyUint => udiv, TyInt => sdiv, TyFloat => fdiv; simd_rem: TyUint => urem, TyInt => srem, TyFloat => frem; simd_shl: TyUint, TyInt => shl; simd_shr: TyUint => lshr, TyInt => ashr; simd_and: TyUint, TyInt => and; simd_or: TyUint, TyInt => or; simd_xor: TyUint, TyInt => xor; simd_fmax: TyFloat => maxnum; simd_fmin: TyFloat => minnum; } span_bug!(span, "unknown SIMD intrinsic"); } // Returns the width of an int Ty, and if it's signed or not // Returns None if the type is not an integer // FIXME: there’s multiple of this functions, investigate using some of the already existing // stuffs. fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> { match ty.sty { ty::TyInt(t) => Some((match t { ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64, ast::IntTy::I8 => 8, ast::IntTy::I16 => 16, ast::IntTy::I32 => 32, ast::IntTy::I64 => 64, ast::IntTy::I128 => 128, }, true)), ty::TyUint(t) => Some((match t { ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64, ast::UintTy::U8 => 8, ast::UintTy::U16 => 16, ast::UintTy::U32 => 32, ast::UintTy::U64 => 64, ast::UintTy::U128 => 128, }, false)), _ => None, } } // Returns the width of a float TypeVariant // Returns None if the type is not a float fn float_type_width<'tcx>(sty: &ty::TypeVariants<'tcx>) -> Option<u64> { match *sty { ty::TyFloat(t) => Some(t.bit_width() as u64), _ => None, } }
#[doc = r"Value read from the register"] pub struct R { bits: u8, } #[doc = r"Value to write to the register"] pub struct W { bits: u8, } impl super::LPMIM { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u8 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct USB_LPMIM_STALLR { bits: bool, } impl USB_LPMIM_STALLR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_LPMIM_STALLW<'a> { w: &'a mut W, } impl<'a> _USB_LPMIM_STALLW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u8) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct USB_LPMIM_NYR { bits: bool, } impl USB_LPMIM_NYR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_LPMIM_NYW<'a> { w: &'a mut W, } impl<'a> _USB_LPMIM_NYW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u8) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct USB_LPMIM_ACKR { bits: bool, } impl USB_LPMIM_ACKR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_LPMIM_ACKW<'a> { w: &'a mut W, } impl<'a> _USB_LPMIM_ACKW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u8) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct USB_LPMIM_NCR { bits: bool, } impl USB_LPMIM_NCR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_LPMIM_NCW<'a> { w: &'a mut W, } impl<'a> _USB_LPMIM_NCW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u8) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct USB_LPMIM_RESR { bits: bool, } impl USB_LPMIM_RESR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_LPMIM_RESW<'a> { w: &'a mut W, } impl<'a> _USB_LPMIM_RESW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u8) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct USB_LPMIM_ERRR { bits: bool, } impl USB_LPMIM_ERRR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _USB_LPMIM_ERRW<'a> { w: &'a mut W, } impl<'a> _USB_LPMIM_ERRW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u8) & 1) << 5; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { self.bits } #[doc = "Bit 0 - LPM STALL Interrupt Mask"] #[inline(always)] pub fn usb_lpmim_stall(&self) -> USB_LPMIM_STALLR { let bits = ((self.bits >> 0) & 1) != 0; USB_LPMIM_STALLR { bits } } #[doc = "Bit 1 - LPM NY Interrupt Mask"] #[inline(always)] pub fn usb_lpmim_ny(&self) -> USB_LPMIM_NYR { let bits = ((self.bits >> 1) & 1) != 0; USB_LPMIM_NYR { bits } } #[doc = "Bit 2 - LPM ACK Interrupt Mask"] #[inline(always)] pub fn usb_lpmim_ack(&self) -> USB_LPMIM_ACKR { let bits = ((self.bits >> 2) & 1) != 0; USB_LPMIM_ACKR { bits } } #[doc = "Bit 3 - LPM NC Interrupt Mask"] #[inline(always)] pub fn usb_lpmim_nc(&self) -> USB_LPMIM_NCR { let bits = ((self.bits >> 3) & 1) != 0; USB_LPMIM_NCR { bits } } #[doc = "Bit 4 - LPM Resume Interrupt Mask"] #[inline(always)] pub fn usb_lpmim_res(&self) -> USB_LPMIM_RESR { let bits = ((self.bits >> 4) & 1) != 0; USB_LPMIM_RESR { bits } } #[doc = "Bit 5 - LPM Error Interrupt Mask"] #[inline(always)] pub fn usb_lpmim_err(&self) -> USB_LPMIM_ERRR { let bits = ((self.bits >> 5) & 1) != 0; USB_LPMIM_ERRR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u8) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - LPM STALL Interrupt Mask"] #[inline(always)] pub fn usb_lpmim_stall(&mut self) -> _USB_LPMIM_STALLW { _USB_LPMIM_STALLW { w: self } } #[doc = "Bit 1 - LPM NY Interrupt Mask"] #[inline(always)] pub fn usb_lpmim_ny(&mut self) -> _USB_LPMIM_NYW { _USB_LPMIM_NYW { w: self } } #[doc = "Bit 2 - LPM ACK Interrupt Mask"] #[inline(always)] pub fn usb_lpmim_ack(&mut self) -> _USB_LPMIM_ACKW { _USB_LPMIM_ACKW { w: self } } #[doc = "Bit 3 - LPM NC Interrupt Mask"] #[inline(always)] pub fn usb_lpmim_nc(&mut self) -> _USB_LPMIM_NCW { _USB_LPMIM_NCW { w: self } } #[doc = "Bit 4 - LPM Resume Interrupt Mask"] #[inline(always)] pub fn usb_lpmim_res(&mut self) -> _USB_LPMIM_RESW { _USB_LPMIM_RESW { w: self } } #[doc = "Bit 5 - LPM Error Interrupt Mask"] #[inline(always)] pub fn usb_lpmim_err(&mut self) -> _USB_LPMIM_ERRW { _USB_LPMIM_ERRW { w: self } } }
fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let m: usize = rd.get(); let mut h: Vec<u64> = (0..n).map(|_| rd.get()).collect(); let w: Vec<u64> = (0..m).map(|_| rd.get()).collect(); h.sort(); let mut a = vec![0; n]; for i in 0..n { if i % 2 == 1 { a[i] = h[i] - h[i - 1]; if i >= 2 { a[i] += a[i - 2]; } } } let mut b = vec![0; n]; for i in (2..n).rev() { if i % 2 == 0 { b[i] = h[i] - h[i - 1]; if i + 2 < n { b[i] += b[i + 2]; } } } // println!("{:?}", a); // println!("{:?}", b); let mut ans = std::u64::MAX; for w in w { let i = h.lower_bound(&w); let mut s = 0; if i % 2 == 0 { s += h[i] - w; if i >= 1 { s += a[i - 1]; } if i + 2 < n { s += b[i + 2]; } } else { s += w - h[i - 1]; if i >= 2 { s += a[i - 2]; } if i + 1 < n { s += b[i + 1]; } } ans = std::cmp::min(ans, s); } println!("{}", ans); } use std::ops::Range; /// ソート済の列に対して二分法で"境目"を探します。 pub trait BinarySearch<T> { fn lower_bound(&self, x: &T) -> usize; fn upper_bound(&self, x: &T) -> usize; fn split_by(&self, x: &T) -> (Range<usize>, Range<usize>, Range<usize>); } impl<T: Ord> BinarySearch<T> for [T] { /// ソートされた列 `a` の中で `x` **以上**である最初の要素の位置を返します。全ての要素が `x` 未満のときは `a.len()` を返します。 /// /// # Examples /// ``` /// use binary_search::BinarySearch; /// let a = vec![1, 2, 2, 3]; /// assert_eq!(a.lower_bound(&2), 1); /// assert_eq!(a.lower_bound(&9), a.len()); /// ``` fn lower_bound(&self, x: &T) -> usize { if self[0] >= *x { return 0; } let mut lf = 0; let mut rg = self.len(); // self[lf] < x while rg - lf > 1 { let md = (rg + lf) / 2; if self[md] < *x { lf = md; } else { rg = md; } } rg } /// ソートされた列 `a` の中で `x` **より大きい**最初の要素の位置を返します。全ての要素が `x` 以下のときは `a.len()` を返します。 /// /// # Examples /// ``` /// use binary_search::BinarySearch; /// let a = vec![1, 2, 2, 3]; /// assert_eq!(a.upper_bound(&2), 3); /// assert_eq!(a.upper_bound(&3), a.len()); /// assert_eq!(a.upper_bound(&9), a.len()); /// ``` fn upper_bound(&self, x: &T) -> usize { if self[0] > *x { return 0; } let mut lf = 0; let mut rg = self.len(); // self[lf] <= x while rg - lf > 1 { let md = (rg + lf) / 2; if self[md] <= *x { lf = md; } else { rg = md; } } rg } /// ソートされた列 `a` を /// /// - `x` 未満 /// - `x` と等しい /// - `x` より大きい /// /// に分ける添字の範囲を tuple で返します。 /// /// # Examples /// ``` /// use binary_search::BinarySearch; /// let a = vec![1, 2, 2, 3]; /// assert_eq!(a.split_by(&0), (0..0, 0..0, 0..a.len())); /// assert_eq!(a.split_by(&2), (0..1, 1..3, 3..a.len())); /// assert_eq!(a.split_by(&9), (0..a.len(), a.len()..a.len(), a.len()..a.len())); /// ``` fn split_by(&self, x: &T) -> (Range<usize>, Range<usize>, Range<usize>) { let i = self.lower_bound(x); let j = self.upper_bound(x); (0..i, i..j, j..self.len()) } } pub struct ProconReader<R: std::io::Read> { reader: R, } impl<R: std::io::Read> ProconReader<R> { pub fn new(reader: R) -> Self { Self { reader } } pub fn get<T: std::str::FromStr>(&mut self) -> T { use std::io::Read; let buf = self .reader .by_ref() .bytes() .map(|b| b.unwrap()) .skip_while(|&byte| byte == b' ' || byte == b'\n' || byte == b'\r') .take_while(|&byte| byte != b' ' && byte != b'\n' && byte != b'\r') .collect::<Vec<_>>(); std::str::from_utf8(&buf) .unwrap() .parse() .ok() .expect("Parse Error.") } }
// 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::{ models::{AddModInfo, DisplayInfo, Suggestion}, story_context_store::ContextEntity, suggestions_manager::SearchSuggestionsProvider, }, failure::Error, fidl_fuchsia_sys_index::{ComponentIndexMarker, ComponentIndexProxy}, fuchsia_component::client::{launch, launcher, App}, fuchsia_syslog::macros::*, futures::future::LocalFutureObj, regex::Regex, }; const COMPONENT_INDEX_URL: &str = "fuchsia-pkg://fuchsia.com/component_index#meta/component_index.cmx"; pub struct PackageSuggestionsProvider {} impl PackageSuggestionsProvider { pub fn new() -> Self { PackageSuggestionsProvider {} } /// Starts and connects to the index service. fn get_index_service(&self) -> Result<(App, ComponentIndexProxy), Error> { let app = launch(&launcher()?, COMPONENT_INDEX_URL.to_string(), None)?; let service = app.connect_to_service::<ComponentIndexMarker>()?; Ok((app, service)) } /// Generate a suggestion to open the a package given its url. /// (example url: fuchsia-pkg://fuchsia.com/package#meta/package.cmx) fn package_url_to_suggestion(url: String) -> Option<Suggestion> { let mut display_info = DisplayInfo::new(); let re = Regex::new(r"fuchsia-pkg://fuchsia.com/(?P<name>.+)#meta/.+").unwrap(); let caps = re.captures(&url)?; display_info.title = Some(format!("open {}", &caps["name"])); Some(Suggestion::new( AddModInfo::new_raw(&url, None /* story_name */, None /* mod_name */), display_info, )) } } // TODO: move this provider to Ermine once we support registering external providers. // The provider should generate a suggestion to open the terminal // "Run package.cmx on terminal" executing `run fuchsia-pkg://fuchsia.com/package#package.cmx` impl SearchSuggestionsProvider for PackageSuggestionsProvider { fn request<'a>( &'a self, query: &'a str, _context: &'a Vec<&'a ContextEntity>, ) -> LocalFutureObj<'a, Result<Vec<Suggestion>, Error>> { LocalFutureObj::new(Box::new(async move { if query.is_empty() { return Ok(vec![]); } let (_app, index_service) = self.get_index_service().map_err(|e| { fx_log_err!("Failed to connect to index service"); e })?; let index_response = index_service.fuzzy_search(query).await.map_err(|e| { fx_log_err!("Fuzzy search error from component index: {:?}", e); e })?; index_response .map(|results| { results .into_iter() .filter_map(&PackageSuggestionsProvider::package_url_to_suggestion) .collect::<Vec<Suggestion>>() }) .or_else(|e| { fx_log_err!("Fuzzy search error from component index: {:?}", e); Ok(vec![]) }) })) } } #[cfg(test)] mod tests { use {super::*, crate::models::SuggestedAction, fuchsia_async as fasync}; #[fasync::run_singlethreaded(test)] async fn test_request() -> Result<(), Error> { let package_suggestions_provider = PackageSuggestionsProvider::new(); let context = vec![]; let results = package_suggestions_provider.request("discovermgr", &context).await?; assert_eq!(results.len(), 2); for result in results.into_iter() { let title = result.display_info().title.as_ref().unwrap(); match result.action() { SuggestedAction::AddMod(action) => { let handler = action.intent.handler.as_ref().unwrap(); if title == "open discovermgr" { assert_eq!( handler, "fuchsia-pkg://fuchsia.com/discovermgr#meta/discovermgr.cmx" ); } else if title == "open discovermgr_tests" { assert_eq!( handler, "fuchsia-pkg://fuchsia.com/discovermgr_tests#meta/discovermgr_bin_test.cmx" ); } else { assert!(false, format!("unexpected result {:?}", result)); } } SuggestedAction::RestoreStory(_) => { assert!(false); } } } Ok(()) } #[test] fn test_package_url_to_suggestion() { let url = "fuchsia-pkg://fuchsia.com/my_component#meta/my_component.cmx"; let suggestion = PackageSuggestionsProvider::package_url_to_suggestion(url.to_string()).unwrap(); match suggestion.action() { SuggestedAction::AddMod(action) => { assert_eq!(action.intent.handler, Some(url.to_string())); } SuggestedAction::RestoreStory(_) => { assert!(false); } } assert_eq!(suggestion.display_info().title, Some("open my_component".to_string())); } #[test] fn test_package_url_to_suggestion_malformed_url() { let url = "fuchsia-pkg://fuchsia/my_component.cmx".to_string(); assert!(PackageSuggestionsProvider::package_url_to_suggestion(url).is_none()); } }
use super::{ ConstGmEvent, ConstGmObject, ConstGmObjectOverrideProperty, ConstGmObjectProperty, EventType, }; use crate::{FilesystemPath, ResourceVersion, Tags, ViewPath}; use serde::{Deserialize, Serialize}; use serde_repr::{Deserialize_repr, Serialize_repr}; use smart_default::SmartDefault; #[derive(Debug, Serialize, Deserialize, SmartDefault, PartialEq, Clone, PartialOrd)] #[serde(rename_all = "camelCase")] pub struct Object { // Ids: /// The Id of the Sprite being used for this object. pub sprite_id: Option<FilesystemPath>, /// If the object is marked as solid for the collision system. pub solid: bool, /// If the object is visible. pub visible: bool, /// The Id used for the Collision Mask, if not the SpriteId. pub sprite_mask_id: Option<FilesystemPath>, /// If the object is "persistent", meaning if Gms2 will keep the object /// between room change events. pub persistent: bool, /// The id of the parent object for the Inhertance in Gms2. pub parent_object_id: Option<FilesystemPath>, // Physics /// Is this a physics object? pub physics_object: bool, /// Enabled if the objects is a physics sensor. pub physics_sensor: bool, /// The shape of the physics, which is needed to understand the shape /// points. pub physics_shape: PhysicsShape, /// What numerical group it belongs to. 0 is a special non-group value. pub physics_group: usize, /// The density. pub physics_density: f64, /// The restitution. pub physics_restitution: f64, /// The linear damping. pub physics_linear_damping: f64, /// The angular damping set. pub physics_angular_damping: f64, /// The friction set. pub physics_friction: f64, /// Whether this object should start awake or not. pub physics_start_awake: bool, /// Whether this physics object is kinematic or not. pub physics_kinematic: bool, /// The shape points of the physics shape. pub physics_shape_points: Vec<PhysicsVec2>, // Event list and Properties pub event_list: Vec<ObjectEvent>, /// The properties which were made in this object directly. pub properties: Vec<ObjectProperty>, /// The properties which were made in a parent object AND overriden. If the /// parent object's properties have not been overriden, then they will /// not appear anywhere in this object's `yy` files and must /// be found recursively. pub overridden_properties: Vec<ObjectOverrideProperty>, // View Data /// The parent in the Gms2 virtual file system, ie. the parent which /// a user would see in the Navigation Pane in Gms2. This has no /// relationship to the actual operating system's filesystem. pub parent: ViewPath, /// The resource version of this yy file. At default 1.0. pub resource_version: ResourceVersion, /// The name of the object. This is the human readable name used in the IDE. pub name: String, /// The tags given to the object. pub tags: Tags, /// Const id tag of the object, given by Gms2. pub resource_type: ConstGmObject, } #[derive(Debug, Serialize, Deserialize, SmartDefault, PartialEq, Eq, Clone, Ord, PartialOrd)] #[serde(rename_all = "camelCase")] pub struct ObjectEvent { /// Is this event used in DragNDrop, the thing no one uses? pub is_dn_d: bool, /// The type of the event. In the JSON, this is represented with two enums, /// but we use Serde to succesfully parse this into idiomatic Rust enums. #[serde(flatten)] pub event_type: EventType, /// The Id of the thing to collide with. pub collision_object_id: Option<FilesystemPath>, /// The version of the `.yy` file. pub resource_version: ResourceVersion, /// The "name" of the Event, which appears to always be null or an empty /// string #[serde(with = "serde_with::rust::string_empty_as_none")] pub name: Option<String>, /// The tags for the event, which probably should always be empty. pub tags: Tags, /// The constant resource type for GmEvents. pub resource_type: ConstGmEvent, } /// Object "properties" are set in the Gms2 window and allow the user to /// override those properties either in child objects of a parent, or in the /// Room (or both!). This allows for simple customization in the room editor. #[derive(Debug, Serialize, Deserialize, SmartDefault, PartialEq, Clone, PartialOrd)] #[serde(rename_all = "camelCase")] pub struct ObjectProperty { /// The type of property which is preset. Some, or all, of the rest of the /// information in this struct will be used based on the property type. pub var_type: ObjectPropertyTypes, /// The serialized value of the property type. This corresponds exactly to /// what the Gms2 box will have inside it as a string. pub value: String, /// If the range Ui option is enabled for this type. This is ignored unless /// `var_type` is `Real` or `Integer`. pub range_enabled: bool, /// The minimum range. Minimin should be less than max, but does not error /// if so. pub range_min: f64, /// The maximum range. Minimin should be less than max, but does not error /// if so. pub range_max: f64, /// The items which can be selected when `var_type` is set to `List`. /// Ignored in any other `var_type`. pub list_items: Vec<String>, /// If set to true when `var_type` is set to `List`, allows the User to /// select multiple options. pub multiselect: bool, /// Not sure what this is supposed to be. In the meantime, we've typed it as /// a blank array. pub filters: Vec<String>, /// The ResourceVersion, default value. pub resource_version: ResourceVersion, /// The name of the property, such as "room_to_transition_to". pub name: String, /// The tags assigned to the property. Probably shouldn't be assigned. pub tags: Tags, /// The resource type const of the property. pub resource_type: ConstGmObjectProperty, } /// Object "properties" are set in the Gms2 window and allow the user to /// override those properties either in child objects of a parent, or in the /// Room (or both!). This allows for simple customization in the room editor. #[derive(Debug, Serialize, Deserialize, SmartDefault, PartialEq, Clone, PartialOrd)] #[serde(rename_all = "camelCase")] pub struct ObjectOverrideProperty { /// This is **not** a real filesystem path, but instead just looks like one. /// Eventually, this will receive better typing. @todo /// The `name` is the name of the prperty, and the `path` is to the /// ORIGINATOR of the property. pub property_id: FilesystemPath, /// The path to the object which this property last overrides. pub object_id: FilesystemPath, /// The serialized value of the property type. This corresponds exactly to /// what the Gms2 box will have inside it as a string. pub value: String, /// The resource version for this property override pub resource_version: ResourceVersion, /// The name of the property, which appears to **always** be an empty /// string. pub name: String, /// The tags assigned to the property. Probably shouldn't be assigned. pub tags: Tags, /// The resource type const of the property. pub resource_type: ConstGmObjectOverrideProperty, } /// The types of object "Properties" as set in the Gms2 Widget pane by users. #[derive( Debug, Serialize_repr, Deserialize_repr, SmartDefault, PartialEq, Clone, Copy, Eq, Ord, PartialOrd, )] #[repr(u8)] pub enum ObjectPropertyTypes { #[default] Real, Integer, String, Boolean, Expression, Asset, List, Colour, } /// The types of physics object as specified in the Gms2 editor. #[derive( Debug, Serialize_repr, Deserialize_repr, SmartDefault, PartialEq, Clone, Copy, Eq, Ord, PartialOrd, )] #[repr(u8)] pub enum PhysicsShape { Circle, #[default] Box, ConvexShape, } /// The types of physics object as specified in the Gms2 editor. #[derive(Debug, Serialize, Deserialize, Default, PartialEq, Clone, Copy, PartialOrd)] pub struct PhysicsVec2 { pub x: f32, pub y: f32, } #[cfg(test)] mod tests { use crate::{object_yy::*, utils::TrailingCommaUtility, ViewPathLocation}; use include_dir::{include_dir, Dir, DirEntry}; use pretty_assertions::assert_eq; #[test] fn trivial_sprite_parsing() { let all_objects: Dir = include_dir!("data/objects"); let tcu = TrailingCommaUtility::new(); for object_file in all_objects.find("**/*.yy").unwrap() { if let DirEntry::File(file) = object_file { println!("parsing {}", file.path); let our_str = std::str::from_utf8(file.contents()).unwrap(); let our_str = tcu.clear_trailing_comma(our_str); serde_json::from_str::<Object>(&our_str).unwrap(); } } } #[test] fn deep_equality() { let object1 = include_str!("../../../data/objects/obj_animate_then_die.yy"); let parsed_object: Object = serde_json::from_str(&TrailingCommaUtility::clear_trailing_comma_once(object1)) .unwrap(); let object = Object { sprite_id: None, solid: false, visible: true, sprite_mask_id: None, persistent: false, parent_object_id: None, physics_object: false, physics_sensor: false, physics_shape: PhysicsShape::Box, physics_group: 1, physics_density: 0.5, physics_restitution: 0.1, physics_linear_damping: 0.1, physics_angular_damping: 0.1, physics_friction: 0.2, physics_start_awake: true, physics_kinematic: false, physics_shape_points: vec![], event_list: vec![ObjectEvent { is_dn_d: false, event_type: EventType::Other(OtherEvent::AnimationEnd), collision_object_id: None, resource_version: ResourceVersion::default(), name: None, tags: vec![], resource_type: ConstGmEvent::Const, }], properties: vec![], overridden_properties: vec![], parent: ViewPath { name: "ui".to_string(), path: ViewPathLocation("folders/Objects/ui.yy".to_owned()), }, resource_version: ResourceVersion::default(), name: "obj_animate_then_die".to_string(), tags: vec![], resource_type: ConstGmObject::Const, }; assert_eq!(parsed_object, object); } }
use crate::extensions::{self as ext}; use crate::keypackage::Timespec; use crate::keypackage::{self as kp, KeyPackage, OwnedKeyPackage}; use crate::message::*; use crate::tree::*; use crate::utils::{encode_vec_u8_u8, read_vec_u8_u8}; use ra_client::EnclaveCertVerifier; use rustls::internal::msgs::codec::{self, Codec, Reader}; use sha2::{Digest, Sha256}; use std::collections::BTreeSet; pub struct EpochSecrets {} impl EpochSecrets { pub fn generate_new_epoch_secrets( &self, _commit_secret: Vec<u8>, _updated_group_context: &GroupContext, ) -> Self { todo!() } pub fn compute_confirmation(&self, _confirmed_transcript: &[u8]) -> Vec<u8> { todo!() } } /// auxiliary structure to hold group context + tree pub struct GroupAux { pub context: GroupContext, pub tree: Tree, pub secrets: EpochSecrets, pub owned_kp: OwnedKeyPackage, } impl GroupAux { fn new(context: GroupContext, tree: Tree, owned_kp: OwnedKeyPackage) -> Self { GroupAux { context, tree, secrets: EpochSecrets {}, owned_kp, } } fn get_sender(&self) -> Sender { Sender { sender_type: SenderType::Member, sender: self.tree.my_pos as u32, } } fn get_signed_add(&self, kp: &KeyPackage) -> MLSPlaintext { let sender = self.get_sender(); let add_content = MLSPlaintextCommon { group_id: self.context.group_id.clone(), epoch: self.context.epoch, sender, authenticated_data: vec![], content: ContentType::Proposal(Proposal::Add(Add { key_package: kp.clone(), })), }; let to_be_signed = MLSPlaintextTBS { context: self.context.clone(), content: add_content.clone(), } .get_encoding(); let signature = self.owned_kp.private_key.sign(&to_be_signed); MLSPlaintext { content: add_content, signature, } } fn get_confirmed_transcript_hash(&self, _commit: &Commit) -> Vec<u8> { todo!() } fn get_signed_commit(&self, plain: &MLSPlaintextCommon) -> MLSPlaintext { let to_be_signed = MLSPlaintextTBS { context: self.context.clone(), // TODO: current or next context? content: plain.clone(), } .get_encoding(); let signature = self.owned_kp.private_key.sign(&to_be_signed); MLSPlaintext { content: plain.clone(), signature, } } fn get_welcome_msg(&self) -> Welcome { todo!() } fn init_commit(&mut self, add_proposals: &[MLSPlaintext]) -> (MLSPlaintext, Welcome) { let add_proposals_ids: Vec<ProposalId> = vec![]; //todo!(); let mut updated_tree = self.tree.clone(); updated_tree.update(&add_proposals, &[], &[]); let commit_secret = vec![0; self.tree.cs.hash_len()]; let commit = Commit { updates: vec![], removes: vec![], adds: add_proposals_ids, path: None, }; let updated_epoch = self.context.epoch + 1; let confirmed_transcript_hash = self.get_confirmed_transcript_hash(&commit); let mut updated_group_context = self.context.clone(); updated_group_context.epoch = updated_epoch; updated_group_context.tree_hash = updated_tree.compute_tree_hash(); updated_group_context.confirmed_transcript_hash = confirmed_transcript_hash; let epoch_secrets = self .secrets .generate_new_epoch_secrets(commit_secret, &updated_group_context); let confirmation = epoch_secrets.compute_confirmation(&updated_group_context.confirmed_transcript_hash); let sender = self.get_sender(); let commit_content = MLSPlaintextCommon { group_id: self.context.group_id.clone(), epoch: self.context.epoch, sender, authenticated_data: vec![], content: ContentType::Commit { commit, confirmation, }, }; ( self.get_signed_commit(&commit_content), self.get_welcome_msg(), ) } pub fn init_group( creator_kp: OwnedKeyPackage, others: &[KeyPackage], ra_verifier: &EnclaveCertVerifier, genesis_time: Timespec, ) -> Result<(Self, Vec<MLSPlaintext>, MLSPlaintext, Welcome), kp::Error> { let mut kps = BTreeSet::new(); for kp in others.iter() { if kps.contains(kp) { return Err(kp::Error::DuplicateKeyPackage); } else { kp.verify(&ra_verifier, genesis_time)?; kps.insert(kp.clone()); } } if kps.contains(&creator_kp.keypackage) { Err(kp::Error::DuplicateKeyPackage) } else { creator_kp.keypackage.verify(&ra_verifier, genesis_time)?; let (context, tree) = GroupContext::init(creator_kp.keypackage.clone())?; let mut group = GroupAux::new(context, tree, creator_kp); let add_proposals: Vec<MLSPlaintext> = others.iter().map(|kp| group.get_signed_add(kp)).collect(); let (commit, welcome) = group.init_commit(&add_proposals); Ok((group, add_proposals, commit, welcome)) } } } #[allow(non_camel_case_types)] #[repr(u16)] #[derive(Clone)] pub enum CipherSuite { MLS10_128_DHKEMP256_AES128GCM_SHA256_P256 = 2, } impl CipherSuite { /// TODO: use generic array? pub fn hash(&self, data: &[u8]) -> Vec<u8> { match self { CipherSuite::MLS10_128_DHKEMP256_AES128GCM_SHA256_P256 => Sha256::digest(data).to_vec(), } } pub fn hash_len(&self) -> usize { match self { CipherSuite::MLS10_128_DHKEMP256_AES128GCM_SHA256_P256 => 32, } } } const TDBE_GROUP_ID: &[u8] = b"Crypto.com Chain Council Node Transaction Data Bootstrap Enclave"; /// spec: draft-ietf-mls-protocol.md#group-state #[derive(Clone, Debug)] pub struct GroupContext { /// 0..255 bytes -- application-defined id pub group_id: Vec<u8>, /// version of the group key /// (incremented by 1 for each Commit message /// that is processed) pub epoch: u64, /// commitment to the contents of the /// group's ratchet tree and the credentials /// for the members of the group /// 0..255 pub tree_hash: Vec<u8>, /// field contains a running hash over /// the messages that led to this state. /// 0..255 pub confirmed_transcript_hash: Vec<u8>, /// 0..2^16-1 pub extensions: Vec<ext::ExtensionEntry>, } impl Codec for GroupContext { fn encode(&self, bytes: &mut Vec<u8>) { encode_vec_u8_u8(bytes, &self.group_id); self.epoch.encode(bytes); encode_vec_u8_u8(bytes, &self.tree_hash); encode_vec_u8_u8(bytes, &self.confirmed_transcript_hash); codec::encode_vec_u16(bytes, &self.extensions); } fn read(r: &mut Reader) -> Option<Self> { let group_id = read_vec_u8_u8(r)?; let epoch = u64::read(r)?; let tree_hash = read_vec_u8_u8(r)?; let confirmed_transcript_hash = read_vec_u8_u8(r)?; let extensions = codec::read_vec_u16(r)?; Some(Self { group_id, epoch, tree_hash, confirmed_transcript_hash, extensions, }) } } impl GroupContext { pub fn init(creator_kp: KeyPackage) -> Result<(Self, Tree), kp::Error> { let extensions = creator_kp.payload.extensions.clone(); let tree = Tree::init(creator_kp)?; Ok(( GroupContext { group_id: TDBE_GROUP_ID.to_vec(), epoch: 0, tree_hash: tree.compute_tree_hash(), confirmed_transcript_hash: vec![], extensions, }, tree, )) } } #[cfg(test)] mod test { use super::*; use crate::credential::Credential; use crate::extensions::{self as ext, MLSExtension}; use crate::key::PrivateKey; use crate::keypackage::{ KeyPackage, KeyPackagePayload, OwnedKeyPackage, MLS10_128_DHKEMP256_AES128GCM_SHA256_P256, PROTOCOL_VERSION_MLS10, }; use rustls::internal::msgs::codec::Codec; fn get_fake_keypackage() -> OwnedKeyPackage { let keypair = ring::signature::EcdsaKeyPair::generate_pkcs8( &ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING, &ring::rand::SystemRandom::new(), ) .unwrap(); let extensions = vec![ ext::SupportedVersionsExt(vec![PROTOCOL_VERSION_MLS10]).entry(), ext::SupportedCipherSuitesExt(vec![MLS10_128_DHKEMP256_AES128GCM_SHA256_P256]).entry(), ext::LifeTimeExt::new(0, 100).entry(), ]; let private_key = PrivateKey::from_pkcs8(keypair.as_ref()).expect("invalid private key"); let payload = KeyPackagePayload { version: PROTOCOL_VERSION_MLS10, cipher_suite: MLS10_128_DHKEMP256_AES128GCM_SHA256_P256, init_key: private_key.public_key(), credential: Credential::X509(vec![]), extensions, }; // sign payload let signature = private_key.sign(&payload.get_encoding()); OwnedKeyPackage { keypackage: KeyPackage { payload, signature }, private_key, } } #[test] fn test_sign_verify_add() { let creator_kp = get_fake_keypackage(); let to_be_added = get_fake_keypackage().keypackage; let (context, tree) = GroupContext::init(creator_kp.keypackage.clone()).unwrap(); let group_aux = GroupAux::new(context, tree, creator_kp); let plain = group_aux.get_signed_add(&to_be_added); assert!(plain .verify_signature( &group_aux.context, &group_aux.owned_kp.private_key.public_key() ) .is_ok()); } }
//! File Appender use {Append, Filter, Named}; use config::appender::Appender; use config::filter::FilterType; use log::LogRecord; use std::error::Error; use std::fmt; use std::fs::OpenOptions; use std::io::Write; use std::path::PathBuf; use std::sync::{Arc, Mutex}; /// FileAppender Struct pub struct FileAppender { /// Appender name. name: String, /// The path to the file where log events should be written. path: PathBuf, /// Set to true if you would rather truncate the file before writing, rather than appending. truncate: Option<bool>, /// Filter associated with this appender. filter: Option<FilterType>, /// OpenOptions for writing to file. oo: Arc<Mutex<OpenOptions>>, } impl Default for FileAppender { fn default() -> FileAppender { use std::env; FileAppender { name: String::new(), path: env::temp_dir().join("tsurgol.log"), truncate: None, filter: None, oo: Arc::new(Mutex::new(OpenOptions::new())), } } } impl fmt::Debug for FileAppender { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("FileAppender") .field("name", &self.name) .field("path", &self.path) .field("truncate", &self.truncate) .finish() } } impl FileAppender { /// Create a new default FileAppender. pub fn new() -> FileAppender { Default::default() } /// Set the name of the file appender. pub fn name(mut self, name: String) -> FileAppender { self.name = name; self } /// Set the file thate will be written to. pub fn path(mut self, path: PathBuf) -> FileAppender { self.path = path; self } /// Set the truncate flag. pub fn truncate(mut self, truncate: Option<bool>) -> FileAppender { self.truncate = truncate; self } /// Set the OpenOptions pub fn oo(mut self, oo: Arc<Mutex<OpenOptions>>) -> FileAppender { self.oo = oo; self } /// An optional list of filter to be applied at the appender level. pub fn filter(mut self, filter: Option<FilterType>) -> FileAppender { self.filter = filter; self } } impl Named for FileAppender { fn name(&self) -> String { self.name.clone() } } impl Append for FileAppender { fn append(&mut self, record: &LogRecord) -> Result<(), Box<Error>> { if let Ok(mut lck) = self.oo.lock() { if let Ok(mut f) = lck.open(&self.path) { try!(f.write_fmt(*record.args())); try!(f.write(b"\n")); try!(f.flush()); // Reset the truncate and append options, so truncate only happens once. lck.truncate(false).append(true); } } Ok(()) } } impl Into<Appender> for FileAppender { fn into(self) -> Appender { let fv = match self.filter { Some(ref f) => f.clone().into(), None => Vec::new(), }; Appender { appender: Box::new(self), filters: fv, } } } #[cfg(feature = "rustc-serialize")] mod rs { use rustc_serialize::{Decodable, Decoder}; use std::path::PathBuf; use super::*; impl Decodable for FileAppender { fn decode<D: Decoder>(d: &mut D) -> Result<FileAppender, D::Error> { d.read_struct("FileAppender", 4, |d| { let name = try!(d.read_struct_field("name", 1, |d| Decodable::decode(d))); let pathstr = try!(d.read_struct_field("path", 2, |d| Decodable::decode(d))); let truncate = try!(d.read_struct_field("truncate", 3, |d| Decodable::decode(d))); let filter = try!(d.read_struct_field("filters", 4, |d| Decodable::decode(d))); let path = PathBuf::from(pathstr); let mut oo = OpenOptions::new(); oo.create(true).write(true); match truncate { Some(t) => { if t { oo.truncate(true); } else { oo.append(true); } } None => { oo.append(true); } } Ok(FileAppender::new() .name(nm) .path(p) .truncate(truncate) .filter(filter) .oo(Arc::new(Mutex::new(oo)))) }) } } } #[cfg(feature = "serde")] mod serde { use config::filter::FilterType; use super::*; use serde::{Deserialize, Deserializer}; use serde::de::{MapVisitor, Visitor}; use std::fs::OpenOptions; use std::path::PathBuf; use std::sync::{Arc, Mutex}; enum FileAppenderField { Name, FPath, Truncate, Filter, } impl Deserialize for FileAppenderField { fn deserialize<D>(deserializer: &mut D) -> Result<FileAppenderField, D::Error> where D: Deserializer { struct FileAppenderFieldVisitor; impl Visitor for FileAppenderFieldVisitor { type Value = FileAppenderField; fn visit_str<E>(&mut self, value: &str) -> Result<FileAppenderField, E> where E: ::serde::de::Error { match value { "name" => Ok(FileAppenderField::Name), "path" => Ok(FileAppenderField::FPath), "truncate" => Ok(FileAppenderField::Truncate), "filter" => Ok(FileAppenderField::Filter), _ => Err(::serde::de::Error::syntax("Unexpected field!")), } } } deserializer.visit(FileAppenderFieldVisitor) } } impl Deserialize for FileAppender { fn deserialize<D>(deserializer: &mut D) -> Result<FileAppender, D::Error> where D: Deserializer { static FIELDS: &'static [&'static str] = &["name", "path", "truncate", "filter"]; deserializer.visit_struct("FileAppender", FIELDS, FileAppenderVisitor) } } struct FileAppenderVisitor; impl Visitor for FileAppenderVisitor { type Value = FileAppender; fn visit_map<V>(&mut self, mut visitor: V) -> Result<FileAppender, V::Error> where V: MapVisitor { let mut name: Option<String> = None; let mut path: Option<PathBuf> = None; let mut truncate: Option<bool> = None; let mut filter: Option<FilterType> = None; loop { match try!(visitor.visit_key()) { Some(FileAppenderField::Name) => { name = Some(try!(visitor.visit_value())); } Some(FileAppenderField::FPath) => { path = Some(try!(visitor.visit_value())); } Some(FileAppenderField::Truncate) => { truncate = Some(try!(visitor.visit_value())); } Some(FileAppenderField::Filter) => { filter = Some(try!(visitor.visit_value())); } None => { break; } } } let nm = match name { Some(n) => n, None => return visitor.missing_field("name"), }; let p = match path { Some(pa) => pa, None => return visitor.missing_field("path"), }; let mut oo = OpenOptions::new(); oo.create(true).write(true); match truncate { Some(t) => { if t { oo.truncate(true); } else { oo.append(true); } } None => { oo.append(true); } } try!(visitor.end()); Ok(FileAppender::new() .name(nm) .path(p) .truncate(truncate) .filter(filter) .oo(Arc::new(Mutex::new(oo)))) } } } #[cfg(test)] mod test { use {Named, decode}; use std::env; use super::*; const BASE_CONFIG: &'static str = r#" name = "file" path = "a/path/to/somewhere" "#; const ALL_CONFIG: &'static str = r#" name = "file" path = "a/path/to/nowhere" [filter.threshold] level = "Warn" "#; static VALIDS: &'static [&'static str] = &[BASE_CONFIG, ALL_CONFIG]; const INVALID_CONFIG_0: &'static str = r#""#; const INVALID_CONFIG_1: &'static str = r#" name = 1 "#; const INVALID_CONFIG_2: &'static str = r#" name = "no path" "#; const INVALID_CONFIG_3: &'static str = r#" yoda = "log, you will" "#; const INVALID_CONFIG_4: &'static str = r#" name = "file" path = 1 "#; const INVALID_CONFIG_5: &'static str = r#" name = "file" path = "some/path" filter = 1 "#; static INVALIDS: &'static [&'static str] = &[INVALID_CONFIG_0, INVALID_CONFIG_1, INVALID_CONFIG_2, INVALID_CONFIG_3, INVALID_CONFIG_4, INVALID_CONFIG_5]; #[test] fn test_default() { let def: FileAppender = Default::default(); assert!(Named::name(&def).is_empty()); assert!(def.path == env::temp_dir().join("tsurgol.log")); assert!(def.filter.is_none()); } #[test] fn test_valid_configs() { let mut results = Vec::new(); for valid in VALIDS { match decode::<FileAppender>(valid) { Ok(_) => { results.push(true); } Err(_) => { assert!(false); } }; } assert!(results.iter().all(|x| *x)); } #[test] fn test_invalid_configs() { let mut results = Vec::new(); for invalid in INVALIDS { match decode::<FileAppender>(invalid) { Ok(_) => { assert!(false); } Err(_) => { results.push(true); } }; } assert!(results.iter().all(|x| *x)); } }
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::GString; use glib_sys; use libc; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use webkit2_webextension_sys; use DOMElement; use DOMEventTarget; use DOMHTMLCollection; use DOMHTMLElement; use DOMNode; use DOMObject; glib_wrapper! { pub struct DOMHTMLFormElement(Object<webkit2_webextension_sys::WebKitDOMHTMLFormElement, webkit2_webextension_sys::WebKitDOMHTMLFormElementClass, DOMHTMLFormElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget; match fn { get_type => || webkit2_webextension_sys::webkit_dom_html_form_element_get_type(), } } pub const NONE_DOMHTML_FORM_ELEMENT: Option<&DOMHTMLFormElement> = None; pub trait DOMHTMLFormElementExt: 'static { #[cfg_attr(feature = "v2_22", deprecated)] fn get_accept_charset(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_action(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_elements(&self) -> Option<DOMHTMLCollection>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_encoding(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_enctype(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_length(&self) -> libc::c_long; #[cfg_attr(feature = "v2_22", deprecated)] fn get_method(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_name(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_target(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn reset(&self); #[cfg_attr(feature = "v2_22", deprecated)] fn set_accept_charset(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_action(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_encoding(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_enctype(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_method(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_name(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_target(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn submit(&self); fn connect_property_accept_charset_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId; fn connect_property_action_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_elements_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_encoding_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_enctype_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_length_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_method_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_name_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_target_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<DOMHTMLFormElement>> DOMHTMLFormElementExt for O { fn get_accept_charset(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_form_element_get_accept_charset( self.as_ref().to_glib_none().0, ), ) } } fn get_action(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_form_element_get_action( self.as_ref().to_glib_none().0, ), ) } } fn get_elements(&self) -> Option<DOMHTMLCollection> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_form_element_get_elements( self.as_ref().to_glib_none().0, ), ) } } fn get_encoding(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_form_element_get_encoding( self.as_ref().to_glib_none().0, ), ) } } fn get_enctype(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_form_element_get_enctype( self.as_ref().to_glib_none().0, ), ) } } fn get_length(&self) -> libc::c_long { unsafe { webkit2_webextension_sys::webkit_dom_html_form_element_get_length( self.as_ref().to_glib_none().0, ) } } fn get_method(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_form_element_get_method( self.as_ref().to_glib_none().0, ), ) } } fn get_name(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_form_element_get_name( self.as_ref().to_glib_none().0, ), ) } } fn get_target(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_form_element_get_target( self.as_ref().to_glib_none().0, ), ) } } fn reset(&self) { unsafe { webkit2_webextension_sys::webkit_dom_html_form_element_reset( self.as_ref().to_glib_none().0, ); } } fn set_accept_charset(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_form_element_set_accept_charset( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_action(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_form_element_set_action( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_encoding(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_form_element_set_encoding( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_enctype(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_form_element_set_enctype( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_method(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_form_element_set_method( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_name(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_form_element_set_name( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_target(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_form_element_set_target( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn submit(&self) { unsafe { webkit2_webextension_sys::webkit_dom_html_form_element_submit( self.as_ref().to_glib_none().0, ); } } fn connect_property_accept_charset_notify<F: Fn(&Self) + 'static>( &self, f: F, ) -> SignalHandlerId { unsafe extern "C" fn notify_accept_charset_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFormElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFormElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFormElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::accept-charset\0".as_ptr() as *const _, Some(transmute( notify_accept_charset_trampoline::<Self, F> as usize, )), Box_::into_raw(f), ) } } fn connect_property_action_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_action_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFormElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFormElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFormElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::action\0".as_ptr() as *const _, Some(transmute(notify_action_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_elements_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_elements_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFormElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFormElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFormElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::elements\0".as_ptr() as *const _, Some(transmute(notify_elements_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_encoding_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_encoding_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFormElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFormElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFormElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::encoding\0".as_ptr() as *const _, Some(transmute(notify_encoding_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_enctype_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_enctype_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFormElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFormElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFormElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::enctype\0".as_ptr() as *const _, Some(transmute(notify_enctype_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_length_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_length_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFormElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFormElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFormElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::length\0".as_ptr() as *const _, Some(transmute(notify_length_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_method_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_method_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFormElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFormElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFormElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::method\0".as_ptr() as *const _, Some(transmute(notify_method_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_name_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_name_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFormElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFormElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFormElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::name\0".as_ptr() as *const _, Some(transmute(notify_name_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_target_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_target_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLFormElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLFormElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLFormElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::target\0".as_ptr() as *const _, Some(transmute(notify_target_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } } impl fmt::Display for DOMHTMLFormElement { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "DOMHTMLFormElement") } }
// 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 { bitflags::bitflags, failure::{format_err, Error, ResultExt}, fidl_fuchsia_bluetooth as bt, fidl_fuchsia_bluetooth_bredr::*, fuchsia_syslog::{fx_log_err, fx_log_info}, fuchsia_zircon as zx, futures::{ future::{self, BoxFuture, FutureExt}, stream::{BoxStream, StreamExt}, }, std::{fmt::Debug, string::String}, }; use crate::types::PeerId; bitflags! { #[allow(dead_code)] pub struct AvcrpTargetFeatures: u16 { const CATEGORY1 = 1 << 0; const CATEGORY2 = 1 << 1; const CATEGORY3 = 1 << 2; const CATEGORY4 = 1 << 3; const PLAYERSETTINGS = 1 << 4; const GROUPNAVIGATION = 1 << 5; const SUPPORTSBROWSING = 1 << 6; const SUPPORTSMULTIPLEMEDIAPLAYERS = 1 << 7; const SUPPORTSCOVERART = 1 << 8; // 9-15 Reserved } } bitflags! { #[allow(dead_code)] pub struct AvcrpControllerFeatures: u16 { const CATEGORY1 = 1 << 0; const CATEGORY2 = 1 << 1; const CATEGORY3 = 1 << 2; const CATEGORY4 = 1 << 3; // 4-5 RESERVED const SUPPORTSBROWSING = 1 << 6; const SUPPORTSCOVERARTGETIMAGEPROPERTIES = 1 << 7; const SUPPORTSCOVERARTGETIMAGE = 1 << 8; const SUPPORTSCOVERARTGETLINKEDTHUMBNAIL = 1 << 9; // 10-15 RESERVED } } const SDP_SUPPORTED_FEATURES: u16 = 0x0311; const AV_REMOTE_TARGET_CLASS: &str = "0000110c-0000-1000-8000-00805f9b34fb"; const AV_REMOTE_CLASS: &str = "0000110e-0000-1000-8000-00805f9b34fb"; const AV_REMOTE_CONTROLLER_CLASS: &str = "0000110f-0000-1000-8000-00805f9b34fb"; /// Make the SDP definition for the AVRCP service. /// TODO(1346): We need two entries in SDP in the future. One for target and one for controller. /// We are using using one unified profile for both because of limitations in BrEdr service. fn make_profile_service_definition() -> ServiceDefinition { let service_class_uuids: Vec<String> = vec![ String::from(AV_REMOTE_TARGET_CLASS), String::from(AV_REMOTE_CLASS), String::from(AV_REMOTE_CONTROLLER_CLASS), ]; ServiceDefinition { service_class_uuids, // AVRCP UUID protocol_descriptors: vec![ ProtocolDescriptor { protocol: ProtocolIdentifier::L2Cap, params: vec![DataElement { type_: DataElementType::UnsignedInteger, size: 2, data: DataElementData::Integer(PSM_AVCTP), }], }, ProtocolDescriptor { protocol: ProtocolIdentifier::Avctp, params: vec![DataElement { type_: DataElementType::UnsignedInteger, size: 2, data: DataElementData::Integer(0x0103), // Indicate v1.3 }], }, ], profile_descriptors: vec![ProfileDescriptor { profile_id: ServiceClassProfileIdentifier::AvRemoteControl, major_version: 1, minor_version: 6, }], additional_protocol_descriptors: None, information: vec![Information { language: "en".to_string(), name: Some("AVRCP".to_string()), description: Some("AVRCP".to_string()), provider: Some("Fuchsia".to_string()), }], additional_attributes: Some(vec![Attribute { id: SDP_SUPPORTED_FEATURES, // SDP Attribute "SUPPORTED FEATURES" element: DataElement { type_: DataElementType::UnsignedInteger, size: 2, data: DataElementData::Integer(i64::from( AvcrpTargetFeatures::CATEGORY1.bits() | AvcrpTargetFeatures::CATEGORY2.bits(), )), }, }]), } } #[derive(Debug, PartialEq, Hash, Clone, Copy)] pub struct AvrcpProtocolVersion(pub u8, pub u8); #[derive(Debug, PartialEq, Clone)] pub enum AvrcpService { Target { features: AvcrpTargetFeatures, psm: u16, protocol_version: AvrcpProtocolVersion, }, Controller { features: AvcrpControllerFeatures, psm: u16, protocol_version: AvrcpProtocolVersion, }, } #[derive(Debug, PartialEq)] pub enum AvrcpProfileEvent { ///Incoming connection on the control channel PSM. ///TODO(2744): add browse channel. IncomingControlConnection { peer_id: PeerId, channel: zx::Socket, }, ServicesDiscovered { peer_id: PeerId, services: Vec<AvrcpService>, }, } pub trait ProfileService: Debug { fn connect_to_device<'a>( &'a self, peer_id: &'a PeerId, psm: u16, ) -> BoxFuture<Result<zx::Socket, Error>>; fn take_event_stream(&self) -> BoxStream<Result<AvrcpProfileEvent, Error>>; } #[derive(Debug)] pub struct ProfileServiceImpl { profile_svc: ProfileProxy, service_id: u64, } impl ProfileServiceImpl { pub async fn connect_and_register_service() -> Result<ProfileServiceImpl, Error> { let profile_svc = fuchsia_component::client::connect_to_service::<ProfileMarker>() .context("Failed to connect to Bluetooth profile service")?; const SEARCH_ATTRIBUTES: [u16; 5] = [ ATTR_SERVICE_CLASS_ID_LIST, ATTR_PROTOCOL_DESCRIPTOR_LIST, ATTR_ADDITIONAL_PROTOCOL_DESCRIPTOR_LIST, ATTR_BLUETOOTH_PROFILE_DESCRIPTOR_LIST, SDP_SUPPORTED_FEATURES, ]; profile_svc.add_search( ServiceClassProfileIdentifier::AvRemoteControl, &mut SEARCH_ATTRIBUTES.to_vec().into_iter(), )?; let mut service_def = make_profile_service_definition(); let (status, service_id) = profile_svc .add_service(&mut service_def, SecurityLevel::EncryptionOptional, false) .await?; fx_log_info!("Registered Service ID {}", service_id); match status.error { Some(e) => Err(format_err!("Couldn't add AVRCP service: {:?}", e)), _ => Ok(ProfileServiceImpl { profile_svc, service_id }), } } } impl ProfileService for ProfileServiceImpl { fn connect_to_device( &self, peer_id: &PeerId, psm: u16, ) -> BoxFuture<Result<zx::Socket, Error>> { let peer_id = peer_id.clone(); async move { let (status, socket) = self .profile_svc .connect_l2cap(&peer_id, psm) .await .map_err(|e| format_err!("Profile service error: {:?}", e))?; let status: bt::Status = status; if let Some(error) = status.error { return Err(format_err!("Error connecting to device: {} {:?}", peer_id, *error)); } match socket { Some(sock) => Ok(sock), // Hopefully we should have an error if we don't have a socket. None => Err(format_err!("No socket returned from profile service {}", peer_id)), } } .boxed() } fn take_event_stream(&self) -> BoxStream<Result<AvrcpProfileEvent, Error>> { let event_stream: ProfileEventStream = self.profile_svc.take_event_stream(); let expected_service_id = self.service_id; event_stream .filter_map(move |event| { future::ready(match event { Ok(ProfileEvent::OnConnected { device_id: peer_id, service_id, channel, protocol: _, }) => { if expected_service_id != service_id { fx_log_err!("Unexpected service id received {}", service_id); None } else { Some(Ok(AvrcpProfileEvent::IncomingControlConnection { peer_id: PeerId::from(peer_id), channel, })) } } Ok(ProfileEvent::OnServiceFound { peer_id, profile, attributes }) => { fx_log_info!("Service found on {}: {:#?}", peer_id, profile); let mut features: Option<u16> = None; let mut service_uuids: Option<Vec<String>> = None; for attr in attributes { fx_log_info!("attribute: {:#?} ", attr); match attr.id { ATTR_SERVICE_CLASS_ID_LIST => { if let DataElementData::Sequence(seq) = attr.element.data { let uuids: Vec<String> = seq .into_iter() .flatten() .filter_map(|item| { if let DataElementData::Uuid(uuid) = item.data { Some(uuid) } else { None } }) .collect(); if uuids.len() > 0 { service_uuids = Some(uuids); } } } SDP_SUPPORTED_FEATURES => { if let DataElementData::Integer(value) = attr.element.data { features = Some(value as u16); } } _ => {} } } if service_uuids.is_none() || features.is_none() { None } else { let service_uuids = service_uuids.expect("service_uuids should not be none"); let mut services = vec![]; if service_uuids.contains(&AV_REMOTE_TARGET_CLASS.to_string()) { if let Some(feature_flags) = AvcrpTargetFeatures::from_bits(features.unwrap()) { services.push(AvrcpService::Target { features: feature_flags, psm: PSM_AVCTP as u16, // TODO: Parse this out instead of assuming it's default protocol_version: AvrcpProtocolVersion( profile.major_version, profile.minor_version, ), }) } } else if service_uuids.contains(&AV_REMOTE_CLASS.to_string()) || service_uuids.contains(&AV_REMOTE_CONTROLLER_CLASS.to_string()) { if let Some(feature_flags) = AvcrpControllerFeatures::from_bits(features.unwrap()) { services.push(AvrcpService::Controller { features: feature_flags, psm: PSM_AVCTP as u16, // TODO: Parse this out instead of assuming it's default protocol_version: AvrcpProtocolVersion( profile.major_version, profile.minor_version, ), }) } } if services.is_empty() { None } else { Some(Ok(AvrcpProfileEvent::ServicesDiscovered { peer_id, services, })) } } } Err(e) => Some(Err(Error::from(e))), }) }) .boxed() } }
use AsLua; use AsMutLua; use Push; use PushGuard; use LuaRead; /// Represents any value that can be stored by Lua #[derive(Clone, Debug, PartialEq)] pub enum AnyLuaValue { LuaString(String), LuaNumber(f64), LuaBoolean(bool), LuaArray(Vec<(AnyLuaValue, AnyLuaValue)>), /// The "Other" element is (hopefully) temporary and will be replaced by "Function" and "Userdata". /// A panic! will trigger if you try to push a Other. LuaOther } impl<L> Push<L> for AnyLuaValue where L: AsMutLua { fn push_to_lua(self, lua: L) -> PushGuard<L> { match self { AnyLuaValue::LuaString(val) => val.push_to_lua(lua), AnyLuaValue::LuaNumber(val) => val.push_to_lua(lua), AnyLuaValue::LuaBoolean(val) => val.push_to_lua(lua), AnyLuaValue::LuaArray(_val) => unimplemented!(),//val.push_to_lua(lua), // FIXME: reached recursion limit during monomorphization AnyLuaValue::LuaOther => panic!("can't push a AnyLuaValue of type Other") } } } impl<L> LuaRead<L> for AnyLuaValue where L: AsLua { fn lua_read_at_position(lua: L, index: i32) -> Result<AnyLuaValue, L> { let lua = match LuaRead::lua_read_at_position(&lua, index) { Ok(v) => return Ok(AnyLuaValue::LuaNumber(v)), Err(lua) => lua }; let lua = match LuaRead::lua_read_at_position(&lua, index) { Ok(v) => return Ok(AnyLuaValue::LuaBoolean(v)), Err(lua) => lua }; let _lua = match LuaRead::lua_read_at_position(&lua, index) { Ok(v) => return Ok(AnyLuaValue::LuaString(v)), Err(lua) => lua }; /*let _lua = match LuaRead::lua_read_at_position(&lua, index) { Ok(v) => return Ok(AnyLuaValue::LuaArray(v)), Err(lua) => lua };*/ Ok(AnyLuaValue::LuaOther) } }
//! A set implemented on a trie. Unlike `std::collections::HashSet` the elements in this set are not //! hashed but are instead serialized. use crate::collections::next_trie_id; use crate::env; use borsh::{BorshDeserialize, BorshSerialize}; use near_vm_logic::types::IteratorIndex; use std::marker::PhantomData; #[derive(BorshSerialize, BorshDeserialize)] pub struct Set<T> { len: u64, prefix: Vec<u8>, #[borsh_skip] element: PhantomData<T>, } impl<T> Set<T> { /// Returns the number of elements in the set, also referred to as its 'size'. pub fn len(&self) -> u64 { self.len } } impl<T> Default for Set<T> { fn default() -> Self { Self::new(next_trie_id()) } } impl<T> Set<T> { /// Create new set with zero elements. Use `id` as a unique identifier. pub fn new(id: Vec<u8>) -> Self { Self { len: 0, prefix: id, element: PhantomData } } } impl<T> Set<T> where T: BorshSerialize + BorshDeserialize, { /// Serializes element into an array of bytes. fn serialize_element(&self, element: &T) -> Vec<u8> { let mut res = self.prefix.clone(); let data = element.try_to_vec().expect("Element should be serializable with Borsh."); res.extend(data); res } /// Deserializes element, taking prefix into account. fn deserialize_element(prefix: &[u8], raw_element: &[u8]) -> T { let element = &raw_element[prefix.len()..]; T::try_from_slice(element).expect("Element should be deserializable with Borsh.") } /// An iterator visiting all elements. The iterator element type is `T`. pub fn iter<'a>(&'a self) -> impl Iterator<Item = T> + 'a { let prefix = self.prefix.clone(); self.raw_elements().map(move |k| Self::deserialize_element(&prefix, &k)) } /// Returns `true` if the set contains a value pub fn contains(&self, element: &T) -> bool { let raw_element = self.serialize_element(element); env::storage_read(&raw_element).is_some() } /// Removes an element from the set, returning `true` if the element was present. pub fn remove(&mut self, element: &T) -> bool { let raw_element = self.serialize_element(element); if env::storage_remove(&raw_element) { self.len -= 1; true } else { false } } /// Inserts an element into the set. If element was already present returns `true`. pub fn insert(&mut self, element: &T) -> bool { let raw_element = self.serialize_element(element); if env::storage_write(&raw_element, &[]) { true } else { self.len += 1; false } } /// Copies elements into an `std::vec::Vec`. pub fn to_vec(&self) -> std::vec::Vec<T> { self.iter().collect() } /// Raw serialized elements. fn raw_elements(&self) -> IntoSetRawElements { let iterator_id = env::storage_iter_prefix(&self.prefix); IntoSetRawElements { iterator_id } } /// Clears the set, removing all elements. pub fn clear(&mut self) { let elements: Vec<Vec<u8>> = self.raw_elements().collect(); for element in elements { env::storage_remove(&element); } self.len = 0; } pub fn extend<IT: IntoIterator<Item = T>>(&mut self, iter: IT) { for el in iter { let element = self.serialize_element(&el); if !env::storage_write(&element, &[]) { self.len += 1; } } } } /// Non-consuming iterator over raw serialized elements of `Set<T>`. pub struct IntoSetRawElements { iterator_id: IteratorIndex, } impl Iterator for IntoSetRawElements { type Item = Vec<u8>; fn next(&mut self) -> Option<Self::Item> { if env::storage_iter_next(self.iterator_id) { env::storage_iter_key_read() } else { None } } }
/* * Firecracker API * * RESTful public-facing API. The API is accessible through HTTP calls on specific URLs carrying JSON modeled data. The transport medium is a Unix Domain Socket. * * The version of the OpenAPI document: 0.25.0 * Contact: compute-capsule@amazon.com * Generated by: https://openapi-generator.tech */ /// InstanceInfo : Describes MicroVM instance information. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct InstanceInfo { /// Application name. #[serde(rename = "app_name")] pub app_name: String, /// MicroVM / instance ID. #[serde(rename = "id")] pub id: String, /// The current detailed state (Not started, Running, Paused) of the Firecracker instance. This value is read-only for the control-plane. #[serde(rename = "state")] pub state: State, /// MicroVM hypervisor build version. #[serde(rename = "vmm_version")] pub vmm_version: String, } impl InstanceInfo { /// Describes MicroVM instance information. pub fn new(app_name: String, id: String, state: State, vmm_version: String) -> InstanceInfo { InstanceInfo { app_name, id, state, vmm_version, } } } /// The current detailed state (Not started, Running, Paused) of the Firecracker instance. This value is read-only for the control-plane. #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum State { #[serde(rename = "Not started")] NotStarted, #[serde(rename = "Running")] Running, #[serde(rename = "Paused")] Paused, }
use super::*; mod with_different_process; #[test] fn with_same_process_adds_process_message_to_mailbox_and_returns_ok() { run!( |arc_process| { ( Just(arc_process.clone()), strategy::term(arc_process.clone()), valid_options(arc_process), ) }, |(arc_process, message, options)| { let destination = registered_name(); prop_assert_eq!( erlang::register_2::result( arc_process.clone(), destination, arc_process.pid_term(), ), Ok(true.into()) ); prop_assert_eq!( result(&arc_process, destination, message, options), Ok(Atom::str_to_term("ok")) ); assert!(has_process_message(&arc_process, message)); Ok(()) }, ); }
use super::{PyType, PyTypeRef}; use crate::{ builtins::PyTupleRef, class::PyClassImpl, function::{ArgIntoBool, OptionalArg, PosArgs}, protocol::{PyIter, PyIterReturn}, types::{Constructor, IterNext, Iterable, SelfIter}, AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, }; use rustpython_common::atomic::{self, PyAtomic, Radium}; #[pyclass(module = false, name = "zip", traverse)] #[derive(Debug)] pub struct PyZip { iterators: Vec<PyIter>, #[pytraverse(skip)] strict: PyAtomic<bool>, } impl PyPayload for PyZip { fn class(ctx: &Context) -> &'static Py<PyType> { ctx.types.zip_type } } #[derive(FromArgs)] pub struct PyZipNewArgs { #[pyarg(named, optional)] strict: OptionalArg<bool>, } impl Constructor for PyZip { type Args = (PosArgs<PyIter>, PyZipNewArgs); fn py_new(cls: PyTypeRef, (iterators, args): Self::Args, vm: &VirtualMachine) -> PyResult { let iterators = iterators.into_vec(); let strict = Radium::new(args.strict.unwrap_or(false)); PyZip { iterators, strict } .into_ref_with_type(vm, cls) .map(Into::into) } } #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyZip { #[pymethod(magic)] fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> { let cls = zelf.class().to_owned(); let iterators = zelf .iterators .iter() .map(|obj| obj.clone().into()) .collect::<Vec<_>>(); let tuple_iter = vm.ctx.new_tuple(iterators); Ok(if zelf.strict.load(atomic::Ordering::Acquire) { vm.new_tuple((cls, tuple_iter, true)) } else { vm.new_tuple((cls, tuple_iter)) }) } #[pymethod(magic)] fn setstate(zelf: PyRef<Self>, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { if let Ok(obj) = ArgIntoBool::try_from_object(vm, state) { zelf.strict.store(obj.into(), atomic::Ordering::Release); } Ok(()) } } impl SelfIter for PyZip {} impl IterNext for PyZip { fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> { if zelf.iterators.is_empty() { return Ok(PyIterReturn::StopIteration(None)); } let mut next_objs = Vec::new(); for (idx, iterator) in zelf.iterators.iter().enumerate() { let item = match iterator.next(vm)? { PyIterReturn::Return(obj) => obj, PyIterReturn::StopIteration(v) => { if zelf.strict.load(atomic::Ordering::Acquire) { if idx > 0 { let plural = if idx == 1 { " " } else { "s 1-" }; return Err(vm.new_value_error(format!( "zip() argument {} is shorter than argument{}{}", idx + 1, plural, idx ))); } for (idx, iterator) in zelf.iterators[1..].iter().enumerate() { if let PyIterReturn::Return(_obj) = iterator.next(vm)? { let plural = if idx == 0 { " " } else { "s 1-" }; return Err(vm.new_value_error(format!( "zip() argument {} is longer than argument{}{}", idx + 2, plural, idx + 1 ))); } } } return Ok(PyIterReturn::StopIteration(v)); } }; next_objs.push(item); } Ok(PyIterReturn::Return(vm.ctx.new_tuple(next_objs).into())) } } pub fn init(ctx: &Context) { PyZip::extend_class(ctx, ctx.types.zip_type); }
use std::num::NonZeroU64; use bytemuck::{Pod, Zeroable}; #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Zeroable, Pod)] #[repr(transparent)] pub struct EntityId(pub u64); /// Returned by `query_begin`. Contains pointers /// to the data yielded by the query. #[derive(Copy, Clone, Debug, Zeroable, Pod)] #[repr(C)] pub struct QueryData { /// The number of (entity, component_1, ..., component_n) pairs /// yielded by this query. pub num_entities: u32, /// Pointer to an array of `num_entities` entities. pub entities_ptr: u32, /// Pointer to an array of component pointers, one for /// each component in the call to `query_begin`. Each component /// pointer points to `num_entities` components of the corresponding type, /// serialized using the component's `to_bytes` method. pub component_ptrs: u32, /// Pointer to an array of `u32`s, one for each component. /// Each `u32` is the number of bytes in the corresponding /// component buffer. pub component_lens: u32, } /// Returned by `entity_get_component`. #[derive(Copy, Clone, Debug)] #[repr(transparent)] pub struct GetComponentResult(NonZeroU64); impl GetComponentResult { pub fn new(ptr: u32, len: u32) -> Self { Self(NonZeroU64::new(((ptr as u64) << 32) | len as u64).expect("null pointer or length")) } pub fn to_bits(self) -> u64 { self.0.get() } pub fn ptr(self) -> u32 { (self.0.get() >> 32) as u32 } pub fn len(self) -> u32 { self.0.get() as u32 } }
use regex::Regex; use std::collections::HashMap; mod utils; fn main() { let data = utils::load_input("./data/day_7.txt").unwrap(); let re = Regex::new(r"\b(?P<container>[a-z]+ [a-z]+) bags \b(?:contain no|contain(?P<list>(?: \d+ [a-z]+ [a-z]+ bags?.)+))").unwrap(); let re_list = Regex::new(r"(\d) ([a-z]+ [a-z]+)").unwrap(); // HashMap to store all the rules let mut bag_rules: HashMap<String, Vec<(String, u32)>> = HashMap::new(); for cap in re.captures_iter(&data) { let list = match cap.name("list") { Some(list) => { let mut v: Vec<(String, u32)> = [].to_vec(); for item in re_list.captures_iter(list.as_str()) { v.push((item[2].to_string(), item[1].parse().unwrap())); } v } None => [].to_vec(), }; bag_rules.insert(cap["container"].to_string(), list); } let mut sum: usize = 0; for (bag_color, _list) in bag_rules.iter() { if bag_contains("shiny gold", &bag_color, &bag_rules) { sum += 1 } } let sum_2 = count_bags("shiny gold", &bag_rules) - 1; // minus the shiny gold bag println!("Answer 1/2: {}", sum); println!("Answer 2/2: {}", sum_2); } fn count_bags(bag_color: &str, bag_rules: &HashMap<String, Vec<(String, u32)>>) -> u64 { let bag_infos = match bag_rules.get(bag_color) { Some(b) => b, None => { return 1; } }; let mut sum = 1; // current bag for info in bag_infos { sum += info.1 as u64 * count_bags(info.0.as_str(), bag_rules); } sum } fn bag_contains( needle: &str, bag_color: &str, bag_rules: &HashMap<String, Vec<(String, u32)>>, ) -> bool { let bag_infos: Vec<&str> = match bag_rules.get(bag_color) { Some(colors) => colors.iter().map(|x| x.0.as_str()).collect(), None => { return false; } }; if bag_infos.contains(&needle) { return true; } for bag_color in bag_infos { if bag_contains(needle, bag_color, bag_rules) { return true; } } return false; }
// 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 fuchsia_inspect::Inspector; use fuchsia_inspect_contrib::nodes::BoundedListNode; use parking_lot::Mutex; use std::sync::Arc; use wlan_inspect::iface_mgr::{IfaceTreeHolder, IfacesTrees}; pub const VMO_SIZE_BYTES: usize = 1000 * 1024; const MAX_DEAD_IFACE_NODES: usize = 2; /// Limit was chosen arbitrary. 20 events seem enough to log multiple PHY/iface create or /// destroy events. const DEVICE_EVENTS_LIMIT: usize = 20; pub struct WlanstackTree { pub inspector: Inspector, pub device_events: Mutex<BoundedListNode>, ifaces_trees: Mutex<IfacesTrees>, } impl WlanstackTree { pub fn new(inspector: Inspector) -> Self { let device_events = inspector.root().create_child("device_events"); let ifaces_trees = IfacesTrees::new(MAX_DEAD_IFACE_NODES); Self { inspector, device_events: Mutex::new(BoundedListNode::new(device_events, DEVICE_EVENTS_LIMIT)), ifaces_trees: Mutex::new(ifaces_trees), } } pub fn create_iface_child(&self, iface_id: u16) -> Arc<IfaceTreeHolder> { self.ifaces_trees.lock().create_iface_child(self.inspector.root(), iface_id) } pub fn notify_iface_removed(&self, iface_id: u16) { self.ifaces_trees.lock().notify_iface_removed(iface_id) } }
#![feature(asm)] #![feature(globs)] use self::bitboard::base::BB; use self::stringable::*; use self::iterable::*; use self::square::*; use self::piece::*; use self::mv::*; use self::fen::*; mod bitboard; mod board; mod piece; mod square; mod mv; mod piecelist; mod fen; mod castling; mod side; mod stringable; mod iterable; #[allow(dead_code)] fn main() { let bb: BB = 123 as BB; let bb_str = bb.to_s(); println!("{}", bb); println!("{}", std::mem::size_of::<[u8, ..100]>()) }
use std::io::Read; fn read<T: std::str::FromStr>() -> T { let token: String = std::io::stdin() .bytes() .map(|c| c.ok().unwrap() as char) .skip_while(|c| c.is_whitespace()) .take_while(|c| !c.is_whitespace()) .collect(); token.parse().ok().unwrap() } fn main() { let s: String = read(); let tot = s .chars() .map(|c| c.to_digit(10).unwrap()) .map(|x| if x == 0 { 10 } else { x }) .sum::<u32>(); println!("{}", tot); }
extern crate cgmath; extern crate gl; extern crate glfw; use std::ffi::CStr; use std::mem; use std::os::raw::c_void; use std::ptr; use cgmath::*; use rand::Rng; use crate::shader::Shader; use self::gl::types::*; pub struct BulletInstance { pub position: Vector3<f32>, pub direction: Vector3<f32>, pub clicks:i32, } impl BulletInstance { pub fn dead(&mut self) { self.clicks = 99999999; } } pub struct Bullet { our_shader: Shader, vao: u32, colour:Vector3<f32>, pub instances: Vec<BulletInstance>, } impl Bullet { pub fn new() -> Bullet { let (our_shader, _vbo, vao) = unsafe { let our_shader = Shader::new( "resources/bullet_texture.vs", "resources/bullet_texture.fs"); let size = 0.03; let vertices: [f32; 180] = [ // positions // texture coords -size, -size, -size, 0.0, 0.0, size, -size, -size, 1.0, 0.0, size, size, -size, 1.0, 1.0, size, size, -size, 1.0, 1.0, -size, size, -size, 0.0, 1.0, -size, -size, -size, 0.0, 0.0, -size, -size, size, 0.0, 0.0, size, -size, size, 1.0, 0.0, size, size, size, 1.0, 1.0, size, size, size, 1.0, 1.0, -size, size, size, 0.0, 1.0, -size, -size, size, 0.0, 0.0, -size, size, size, 1.0, 0.0, -size, size, -size, 1.0, 1.0, -size, -size, -size, 0.0, 1.0, -size, -size, -size, 0.0, 1.0, -size, -size, size, 0.0, 0.0, -size, size, size, 1.0, 0.0, size, size, size, 1.0, 0.0, size, size, -size, 1.0, 1.0, size, -size, -size, 0.0, 1.0, size, -size, -size, 0.0, 1.0, size, -size, size, 0.0, 0.0, size, size, size, 1.0, 0.0, -size, -size, -size, 0.0, 1.0, size, -size, -size, 1.0, 1.0, size, -size, size, 1.0, 0.0, size, -size, size, 1.0, 0.0, -size, -size, size, 0.0, 0.0, -size, -size, -size, 0.0, 1.0, -size, size, -size, 0.0, 1.0, size, size, -size, 1.0, 1.0, size, size, size, 1.0, 0.0, size, size, size, 1.0, 0.0, -size, size, size, 0.0, 0.0, -size, size, -size, 0.0, 1.0 ]; let (mut vbo, mut vao) = (0, 0); gl::GenVertexArrays(1, &mut vao); gl::GenBuffers(1, &mut vbo); gl::BindVertexArray(vao); gl::BindBuffer(gl::ARRAY_BUFFER, vbo); gl::BufferData(gl::ARRAY_BUFFER, (vertices.len() * mem::size_of::<GLfloat>()) as GLsizeiptr, &vertices[0] as *const f32 as *const c_void, gl::STATIC_DRAW); let stride = 5 * mem::size_of::<GLfloat>() as GLsizei; gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, stride, ptr::null()); gl::EnableVertexAttribArray(0); gl::VertexAttribPointer(1, 2, gl::FLOAT, gl::FALSE, stride, (3 * mem::size_of::<GLfloat>()) as *const c_void); gl::EnableVertexAttribArray(1); our_shader.useProgram(); (our_shader, vbo, vao) }; Bullet { our_shader: our_shader, vao, colour:vec3(1.0,1.0,0.0), instances: Vec::<BulletInstance>::new(), } } pub fn new_instance(&mut self, direction: Vector3<f32>, position: Vector3<f32>) { let instance = BulletInstance { position, direction, clicks:0, }; self.instances.push(instance); } pub fn update_bullets(&mut self, delta_time:f32) { let speed = 8.0f32; let mut i = self.instances.len(); while i >= 1 { i=i-1; let mut b = self.instances.get_mut(i).unwrap(); b.position -= b.direction * delta_time * speed; b.clicks = b.clicks +1; if b.clicks > 200 { self.instances.remove(i); } } } pub fn render(&mut self, view:&Matrix4<f32>, projection:&Matrix4<f32>) { let mut rng = rand::thread_rng(); unsafe { self.our_shader.useProgram(); self.our_shader.setMat4(c_str!("view"), view); self.our_shader.setMat4(c_str!("projection"), projection); gl::BindVertexArray(self.vao); } self.colour.x = self.colour.x + rng.gen_range(0.1,0.4); self.colour.y = self.colour.y + rng.gen_range(0.0,0.4); if self.colour.x > 1.0 { self.colour.x = 0.5; } if self.colour.y > 1.0 { self.colour.y = 0.5; } for i in 0..self.instances.len() { let b = self.instances.get(i).unwrap(); let matrix = Matrix4::<f32>::from_translation(b.position ); unsafe { self.our_shader.setMat4(c_str!("model"), &matrix); self.our_shader.setVec3(c_str!("colour"), self.colour.x+0.4,self.colour.y,self.colour.z); gl::DrawArrays(gl::TRIANGLES, 0, 36); } } } }
fn main() { let s1 = "abc"; let s2 = b"abc"; println!("{}", s1); println!("{:?}", s2); let s3 = "テスト"; println!("{}", s3); println!("{:?}", "テスト".as_bytes()); }
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[repr(C, packed)] struct QuerySectionEntryFooter { /// A two octet code which specifies the type of the query. /// /// The values for this field include all codes valid for a `TYPE` field, together with some more general codes which can match more than one type of Resource Record (RR). qtype: QueryTypeOrDataType, /// A two octet code that specifies the class of the query. /// /// For example, the `QCLASS` field is `IN` for the Internet. qclass: [u8; 2], } impl QuerySectionEntryFooter { #[inline(always)] fn query_type_or_data_type(&self) -> QueryTypeOrDataType { self.qtype } #[inline(always)] fn query_class(&self) -> Result<QueryClass, DnsProtocolError> { let (upper, lower) = unsafe { transmute::<_, (u8, u8)>(self.qclass) }; if likely!(upper == 0x00) { if likely!(lower == 0x01) { return Ok(QueryClass::Internet) } } Err(ClassIsReservedUnassignedOrObsolete(self.qclass)) } }
use std::time; #[derive(Debug)] pub struct FrameClock { clock: time::Instant, previous: u64, elapsed: u64, } impl FrameClock { pub fn new() -> FrameClock { FrameClock { clock: time::Instant::now(), previous: 0, elapsed: u64::max_value(), } } pub fn get_fps(&self) -> u64 { if self.elapsed == 0 { return 0; } 1_000 / self.elapsed } pub fn elapsed(&self) -> u64 { self.get_duration() } pub fn get_last_frame_duration(&self) -> u64 { self.elapsed } fn get_duration(&self) -> u64 { let t = self.clock.elapsed(); (t.as_secs() * 1_000) + (t.subsec_nanos() / 1_000_000) as u64 } pub fn tick(&mut self) { let current = self.get_duration(); self.elapsed = current - self.previous; self.previous = current; } } #[cfg(test)] mod tests { #[test] fn test_fps() { // TODO assert!(1 == 1); } }
use crate::{DocBase, VarType}; pub fn gen_doc() -> Vec<DocBase> { vec![ DocBase { var_type: VarType::Variable, name: "year", signatures: vec![], description: "Current bar year in exchange timezone.", example: "", returns: "", arguments: "", remarks: "", links: "", }, DocBase { var_type: VarType::Function, name: "year", signatures: vec![], description: "", example: "", returns: "Year (in exchange timezone) for provided UNIX time.", arguments: "**time (series(int))** UNIX time in milliseconds.", remarks: "UNIX time is the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970.", links: "", }, ] }
use parser::ast::*; use evaluator::object::*; pub struct BuiltinsFunctions; impl Default for BuiltinsFunctions { fn default() -> Self { Self::new() } } impl BuiltinsFunctions { pub fn new() -> Self { BuiltinsFunctions {} } pub fn get_builtins(&self) -> Vec<(Ident, Object)> { vec![ add_builtin("print", 1, bprint_fn), add_builtin("len", 1, blen_fn), add_builtin("head", 1, bhead_fn), add_builtin("tail", 1, btail_fn), add_builtin("cons", 2, bcons_fn), ] } } fn add_builtin(name: &str, param_num: usize, func: BuiltinFunction) -> (Ident, Object) { let name_string = String::from(name); ( Ident(name_string.clone()), Object::Builtin(name_string, param_num, func), ) } fn bprint_fn(args: Vec<Object>) -> Result<Object, String> { match args.get(0) { Some(&Object::String(ref t)) => { println!("{}", t); Ok(Object::Null) } Some(o) => { println!("{}", o); Ok(Object::Null) } _ => Err(String::from("invalid arguments for print")), } } fn blen_fn(args: Vec<Object>) -> Result<Object, String> { match args.get(0) { Some(&Object::String(ref s)) => Ok(Object::Integer(s.len() as i64)), Some(&Object::Array(ref arr)) => Ok(Object::Integer(arr.len() as i64)), _ => Err(String::from("invalid arguments for len")), } } fn bhead_fn(args: Vec<Object>) -> Result<Object, String> { match args.get(0) { Some(&Object::Array(ref arr)) => { match arr.first() { None => Err(String::from("empty array")), Some(x) => Ok(x.clone()), } } _ => Err(String::from("invalid arguments for head")), } } fn btail_fn(args: Vec<Object>) -> Result<Object, String> { match args.get(0) { Some(&Object::Array(ref arr)) => { match arr.len() { 0 => Err(String::from("empty array")), _ => { let tail = &arr[1..]; Ok(Object::Array(tail.to_vec())) } } } _ => Err(String::from("invalid arguments for tail")), } } fn bcons_fn(args: Vec<Object>) -> Result<Object, String> { let mut args = args.iter(); match (args.next(), args.next()) { (Some(o), Some(&Object::Array(ref os))) => { let mut vectors = vec![o.clone()]; for object in os { vectors.push(object.clone()); } Ok(Object::Array(vectors)) } _ => Err(String::from("invalid arguments for cons")), } }
pub trait Predicate<V> { fn apply(&self, value: &V) -> bool; }
#[cfg(target_os = "macos")] mod macos; #[cfg(target_os = "macos")] pub use macos::get_page_cache_info; #[cfg(target_os = "macos")] pub use macos::read_advise; #[cfg(target_os = "macos")] pub use macos::read_ahead; // pub const PAGE_SIZE: usize = ???; include!(concat!(env!("OUT_DIR"), "/os_consts.rs")); #[allow(dead_code)] pub struct PageCacheInfo { total: usize, cached: usize, } #[allow(dead_code)] impl PageCacheInfo { pub fn total(&self) -> usize { self.total } pub fn cached(&self) -> usize { self.cached } pub fn ratio(&self) -> f32 { self.cached as f32 / self.total as f32 } }
use crate::{sealed::Sealed, tuple::push::TuplePush}; /// Popes element from the **end** of the tuple, producing new tuple. /// /// Return tuple of remaining tuple and poped element. /// /// ## Examples /// ``` /// use fntools::tuple::pop::TuplePop; /// /// assert_eq!((999,).pop(), ((), 999)); /// assert_eq!((47, "str", 14usize).pop(), ((47, "str"), 14usize)); /// ``` /// /// ```compile_fail /// use fntools::tuple_pop::TuplePop; /// /// // There is nothing you can pop from empty tuple, /// // so this code won't be compiled /// assert_eq!(().pop(), ()); /// ``` pub trait TuplePop: Sized + Sealed { /// Remaining part of the tuple, after popping an element type Rem: TuplePush<Self::Pop, Res = Self>; /// Poped element type Pop; /// Pop element from tuple. fn pop(self) -> (Self::Rem, Self::Pop); } impl<T> TuplePop for (T,) { type Pop = T; type Rem = (); #[inline] fn pop(self) -> (Self::Rem, Self::Pop) { ((), self.0) } } macro_rules! tuple_impl { ($( $types:ident, )*) => { impl<T, $( $types, )*> TuplePop for ($( $types, )* T) { type Rem = ($( $types, )*); type Pop = T; #[inline] #[allow(non_snake_case)] fn pop(self) -> (Self::Rem, Self::Pop) { let ($( $types, )* pop) = self; (($( $types, )*), pop) } } }; } for_tuples!(A, B, C, D, E, F, G, H, I, J, K, # tuple_impl);
use std::io::Read; fn main() { let mut buf = String::new(); // 標準入力から全部bufに読み込む std::io::stdin().read_to_string(&mut buf).unwrap(); // 行ごとのiterが取れる let mut iter = buf.split_whitespace(); let y: usize = iter.next().unwrap().parse().unwrap(); let x: usize = iter.next().unwrap().parse().unwrap(); let squares: Vec<Vec<char>> = (0..y) .map(|_| { let str: String = iter.next().unwrap().parse().unwrap(); str.chars().collect::<Vec<char>>() }) .collect(); let mut result: Vec<Vec<char>> = Vec::new(); for (i, line) in squares.iter().enumerate() { let mut result_line: Vec<char> = Vec::new(); for (j, &square) in line.iter().enumerate() { let mut count = 0; if square == '#' { result_line.push('#'); continue; } count += check_count(&squares[i], j, x); if i != 0 { count += check_count(&squares[i - 1], j, x); } if i < y - 1 { count += check_count(&squares[i + 1], j, x); } result_line.push(std::char::from_digit(count, 10).unwrap()); } result.push(result_line); } result .iter() .map(|line| line.iter().collect::<String>()) .for_each(|line| println!("{}", line)); /*for line in result { for word in line { print!("{}", word); } print!("\n"); }*/ } fn check_count(line: &Vec<char>, current_index: usize, line_length: usize) -> u32 { let mut count = 0; if current_index != 0 { if line[current_index - 1] == '#' { count += 1; } } if line[current_index] == '#' { count += 1; } if current_index < line_length - 1 { if line[current_index + 1] == '#' { count += 1; } }; count }
use serde_json::Value; use rbatis_core::convert::StmtConvert; use rbatis_core::db::DriverType; use crate::sql::Date; impl Date for DriverType { fn date_convert(&self, value: &Value, index: usize) -> rbatis_core::Result<(String, Value)> { let mut sql = String::new(); match self { DriverType::Postgres => { sql = format!("cast({} as timestamp)", self.stmt_convert(index).as_str()); } _ => { sql = self.stmt_convert(index); } } return Ok((sql, value.to_owned())); } } #[test] pub fn test_date() {}
//! # General traits pub mod trait_impl; /// Data type of the start and end coordinates pub type Coordinate = i64; /// Data type of the chromosomes pub type Chrom = String; /// Returns a tuple of the form /// (chromosome, start_inclusive, end_exclusive, value) pub trait ToChromStartEndVal<V> { fn to_chrom_start_end_val( &self, ) -> (Chrom, Coordinate, Coordinate, Option<V>); }
// RGB standard library // Written in 2020 by // Dr. Maxim Orlovsky <orlovsky@pandoracore.com> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the MIT License // along with this software. // If not, see <https://opensource.org/licenses/MIT>. use lnpbp::rgb::prelude::*; use crate::error::ServiceErrorDomain; pub trait Store { type Error: ::std::error::Error + Into<ServiceErrorDomain>; fn schema_ids(&self) -> Result<Vec<SchemaId>, Self::Error>; fn schema(&self, id: &SchemaId) -> Result<Schema, Self::Error>; fn has_schema(&self, id: &SchemaId) -> Result<bool, Self::Error>; fn add_schema(&self, schema: &Schema) -> Result<bool, Self::Error>; fn remove_schema(&self, id: &SchemaId) -> Result<bool, Self::Error>; fn contract_ids(&self) -> Result<Vec<ContractId>, Self::Error>; fn genesis(&self, id: &ContractId) -> Result<Genesis, Self::Error>; fn has_genesis(&self, id: &ContractId) -> Result<bool, Self::Error>; fn add_genesis(&self, genesis: &Genesis) -> Result<bool, Self::Error>; fn remove_genesis(&self, id: &ContractId) -> Result<bool, Self::Error>; fn anchor(&self, id: &AnchorId) -> Result<Anchor, Self::Error>; fn has_anchor(&self, id: &AnchorId) -> Result<bool, Self::Error>; fn add_anchor(&self, anchor: &Anchor) -> Result<bool, Self::Error>; fn remove_anchor(&self, id: &AnchorId) -> Result<bool, Self::Error>; fn transition(&self, id: &NodeId) -> Result<Transition, Self::Error>; fn has_transition(&self, id: &NodeId) -> Result<bool, Self::Error>; fn add_transition(&self, transition: &Transition) -> Result<bool, Self::Error>; fn remove_transition(&self, id: &NodeId) -> Result<bool, Self::Error>; }
use hello_macro::HelloMacro; use hello_macro_derive::HelloMacro; fn main() { macro_rules(); derive_macro(); attribute_like_macros(); function_like_macros(); } fn macro_rules() { #[macro_export] macro_rules! my_vec { ( $( $x:expr ),* ) => { { let mut temp_vec = Vec::new(); $( temp_vec.push($x); )* temp_vec } }; } let vec = my_vec![1, 2, 3]; println!("macro_rules: vec is: {:?}", vec); } fn derive_macro() { #[derive(HelloMacro)] struct Pancakes; Pancakes::hello_macro(); } fn attribute_like_macros() { /* Attribute-like macros are similar to custom derive macros, but instead of generating code for the derive attribute, they allow you to create new attributes. #[route(GET, "/")] fn index() { This #[route] attribute would be defined by the framework as a procedural macro. The signature of the macro definition function would look like this: #[proc_macro_attribute] pub fn route(attr: TokenStream, item: TokenStream) -> TokenStream { Here, we have two parameters of type TokenStream. The first is for the contents of the attribute: the GET, "/" part. The second is the body of the item the attribute is attached to: in this case, fn index() {} and the rest of the function’s body. */ } /* Function-like macros define macros that look like function calls. Similarly to macro_rules! macros, they’re more flexible than functions. Function-like macros take a TokenStream parameter and their definition manipulates that TokenStream using Rust code as the other two types of procedural macros do. */ fn function_like_macros() { /* An example of a function-like macro is an sql! macro that might be called like so: let sql = sql!(SELECT * FROM posts WHERE id=1); This macro would parse the SQL statement inside it and check that it’s syntactically correct, which is much more complex processing than a macro_rules! macro can do. The sql! macro would be defined like this: #[proc_macro] pub fn sql(input: TokenStream) -> TokenStream { */ }
//! Implements the traits that are required to hook up low level Tokio IO to the Tokio //! protocol API. //! //! The main struct that it exposes is the `H2ClientTokioTransport`, which is the bridge between //! the semantic representation of an HTTP/2 request/response and the lower-level IO. //! //! Also exposes the `H2ClientTokioProto` that allows an existing `Io` instance to be bound //! to the HTTP/2 Tokio transport, as implemented by `H2ClientTokioTransport`. use super::{ Http2Error, TokioSyncError, HttpRequestHeaders, HttpRequestBody, HttpResponseHeaders, HttpResponseBody }; use client::connectors::H2ConnectorParams; use io::{FrameSender, FrameReceiver}; use std::rc::Rc; use std::cell::RefCell; use std::io::{self, Read}; use std::collections::{HashMap,VecDeque}; use futures::{Async, AsyncSink, Future, Poll, StartSend}; use futures::future::{self}; use futures::sink::Sink; use futures::stream::{Stream}; use futures::task; use tokio_core::io::{Io, self as tokio_io}; use tokio_service::Service; use tokio_proto::streaming::multiplex::{ClientProto, Transport, Frame}; use solicit::http::{ HttpScheme, Header, StaticHeader, OwnedHeader, StreamId }; use solicit::http::connection::{HttpConnection, SendStatus}; use solicit::http::session::{ Client as ClientMarker, Stream as SolicitStream, DefaultSessionState, SessionState, StreamDataError, StreamDataChunk, StreamState, }; use solicit::http::client::{self, ClientConnection, RequestStream}; /// An enum that represents different response parts that can be generated by an HTTP/2 stream /// for an associated request. enum ResponseChunk { /// Yielded by the stream when it first receives the response headers. Headers(HttpResponseHeaders), /// Yielded by the stream for each body chunk. It wraps the actual byte chunk. Body(HttpResponseBody), /// Signals that there will be no more body chunks yielded by the stream. EndOfBody, } /// A helper struct that is used by the `H2Stream` to place its `ResponseChunk`s into a shared /// buffer of `ResponseChunk`s that the `H2ClientTokioTransport` can yield. #[derive(Clone)] struct ResponseChunkSender { request_id: u64, result_stream: Rc<RefCell<VecDeque<(u64, ResponseChunk)>>>, } impl ResponseChunkSender { /// Places the given `ResponseChunk` into the shared buffer. pub fn send_chunk(&mut self, chunk: ResponseChunk) { self.result_stream.borrow_mut().push_back((self.request_id, chunk)); } } /// A helper struct that exposes the receiving end of the shared buffer of `ResponseChunk`s that /// the `H2ClientTokioTransport` should yield. struct ResponseChunkReceiver { ready_responses: Rc<RefCell<VecDeque<(u64, ResponseChunk)>>>, } impl ResponseChunkReceiver { /// Creates a new `ResponseChunkReceiver` pub fn new() -> ResponseChunkReceiver { ResponseChunkReceiver { ready_responses: Rc::new(RefCell::new(VecDeque::new())), } } /// Creates a `ResponseChunkSender` that is bound to a Tokio request with the given ID. pub fn get_sender(&self, request_id: u64) -> ResponseChunkSender { ResponseChunkSender { request_id: request_id, result_stream: self.ready_responses.clone(), } } /// Gets the next `ResponseChunk` that is available in the shared buffer. If there is no /// available chunk, it returns `None`. pub fn get_next_chunk(&mut self) -> Option<(u64, ResponseChunk)> { let mut ready_responses = self.ready_responses.borrow_mut(); ready_responses.pop_front() } } /// A struct that represents an HTTP/2 stream. /// Each HTTP/2 stream corresponds to a single (Tokio/HTTP) request. /// /// This struct implements the `solicit` `Stream` trait. This allows us to provide a custom handler /// for various events that occur on individual streams, without implementing the entire session /// layer. Most importantly, instead of accumulating the entire body of the response, this `Stream` /// implementation will yield the chunks immediately into a shared buffer of `ResponseChunk`s. The /// `H2ClientTokioTransport` will then, in turn, provide this response chunk to Tokio as soon as /// possible. Tokio will then handle adapting this to a `futures` `Stream` of chunks that will /// finally be available to external clients. /// /// All `H2Stream` instances can share the same underlying buffer of `ResponseChunk`s (which is /// abstracted away by the `ResponseChunkSender`). This is possible because there can be no /// concurrency between processing streams and yielding results, as it all happens on the event /// loop. struct H2Stream { /// The ID of the stream, if already assigned by the connection. stream_id: Option<StreamId>, /// The current stream state. state: StreamState, /// The outgoing data associated to the stream. The `Cursor` points into the `Vec` at the /// position where the data has been sent out. out_buf: Option<io::Cursor<Vec<u8>>>, /// A queue of data chunks that should be sent after the current out buffer is exhausted. out_queue: VecDeque<Vec<u8>>, /// A boolean indicating whether the stream should be closed (locally) after the out buffer /// and queue have been cleared out. should_close: bool, /// A `ResponseChunkSender` that allows the stream to notify the `H2ClientTokioTransport` when /// it has received a relevant part of the response. sender: ResponseChunkSender, } impl H2Stream { /// Create a new `H2Stream` for a Tokio request with the given ID, which will place all /// `ResponseChunk`s that it generates due to incoming h2 stream events. pub fn new(sender: ResponseChunkSender) -> H2Stream { H2Stream { stream_id: None, state: StreamState::Open, out_buf: None, out_queue: VecDeque::new(), should_close: false, sender: sender, } } /// Add a chunk of data that the h2 stream should send to the server. Fails if the stream has /// already been instructed that it should be locally closed (via `set_should_close`) even if /// it still hasn't actually become locally closed (i.e. not everything that's been buffered /// has been sent out to the server yet). pub fn add_data(&mut self, data: Vec<u8>) -> Result<(), Http2Error> { if self.should_close { // Adding data after we already closed the stream is not valid, because we cannot make // sure to send it. return Err(Http2Error::TokioSync(TokioSyncError::DataChunkAfterEndOfBody)); } self.out_queue.push_back(data); Ok(()) } /// Places the stream in a state where once the previously buffered chunks have been sent, the /// stream will be closed. No more chunks should be queued after this is called. pub fn set_should_close(&mut self) { self.should_close = true; } /// Prepare the `out_buf` by placing the next element off the `out_queue` in it, if we have /// exhausted the previous buffer. If the buffer hasn't yet been exhausted, it has no effect. fn prepare_out_buf(&mut self) { if self.out_buf.is_none() { self.out_buf = self.out_queue.pop_front().map(|vec| io::Cursor::new(vec)); } } } impl SolicitStream for H2Stream { fn new_data_chunk(&mut self, data: &[u8]) { let body_chunk = ResponseChunk::Body(HttpResponseBody { body: data.to_vec() }); self.sender.send_chunk(body_chunk); } fn set_headers<'n, 'v>(&mut self, headers: Vec<Header<'n, 'v>>) { let new_headers = headers.into_iter().map(|h| { let owned: OwnedHeader = h.into(); owned.into() }); let header_chunk = ResponseChunk::Headers(HttpResponseHeaders { headers: new_headers.collect(), }); self.sender.send_chunk(header_chunk); } fn set_state(&mut self, state: StreamState) { self.state = state; // If we've transitioned into a state where the stream is closed on the remote end, // it means that there can't be more body chunks incoming... if self.is_closed_remote() { self.sender.send_chunk(ResponseChunk::EndOfBody); } } fn state(&self) -> StreamState { self.state } fn get_data_chunk(&mut self, buf: &mut [u8]) -> Result<StreamDataChunk, StreamDataError> { if self.is_closed_local() { return Err(StreamDataError::Closed); } // First make sure we have something in the out buffer, if at all possible. self.prepare_out_buf(); // Now try giving out as much of it as we can. let mut out_buf_exhausted = false; let chunk = match self.out_buf.as_mut() { // No data associated to the stream, but it's open => nothing available for writing None => { if self.should_close { StreamDataChunk::Last(0) } else { StreamDataChunk::Unavailable } }, Some(d) => { let read = d.read(buf)?; out_buf_exhausted = (d.position() as usize) == d.get_ref().len(); if self.should_close && out_buf_exhausted && self.out_queue.is_empty() { StreamDataChunk::Last(read) } else { StreamDataChunk::Chunk(read) } } }; if out_buf_exhausted { self.out_buf = None; } // Transition the stream state to locally closed if we've extracted the final data chunk. if let StreamDataChunk::Last(_) = chunk { self.close_local() } Ok(chunk) } } /// A type alias for the Frame type that we need to yield to Tokio from the Transport impl's /// `Stream`. type TokioResponseFrame = Frame<HttpResponseHeaders, HttpResponseBody, io::Error>; /// Implements the Tokio Transport trait -- a layer that translates between the HTTP request /// and response semantic representations (the Http{Request,Response}{Headers,Body} structs) /// and the lower-level IO required to drive HTTP/2. /// /// It handles mapping Tokio-level request IDs to HTTP/2 stream IDs, so that once a response /// is received, it can notify the correct Tokio request. /// /// It holds the HTTP/2 connection state, as a `ClientConnection` using `DefaultStream`s. /// /// The HTTP/2 connection is fed by the `FrameSender` and `FrameReceiver`. /// /// To satisfy the Tokio Transport trait, this struct implements a `Sink` and a `Stream` trait. /// # Sink /// /// As a `Sink`, it acts as a `Sink` of Tokio request frames. These frames do not necessarily /// have a 1-1 mapping to HTTP/2 frames, but it is the task of this struct to do the required /// mapping. /// /// For example, a Tokio frame that signals the start of a new request, `Frame::Message`, will be /// handled by constructing a new HTTP/2 stream in the HTTP/2 session state and instructing the /// HTTP/2 client connection to start a new request, which will queue up the required HEADERS /// frames, signaling the start of a new request. /// /// When handling body "chunk" Tokio frames, i.e. the `Frame::Body` variant, it will notify the /// appropriate stream (by mapping the Tokio request ID to the matching HTTP/2 stream ID). /// /// # Stream /// /// As a `Stream`, the struct acts as a `Stream` of `TokioResponseFrame`s. Tokio itself internally /// knows how to interpret these frames in order to produce: /// /// 1. A `Future` that resolves once the response headers come in /// 2. A `Stream` that will yield response body chunks /// /// Therefore, the job of this struct is to feed the HTTP/2 frames read by the `receiver` from the /// underlying raw IO to the ClientConnection and subsequently to interpret the new state of the /// HTTP/2 session in order to produce `TokioResponseFrame`s. pub struct H2ClientTokioTransport<T: Io + 'static> { sender: FrameSender<T>, receiver: FrameReceiver<T>, conn: ClientConnection<DefaultSessionState<ClientMarker, H2Stream>>, ready_responses: ResponseChunkReceiver, tokio_request_to_h2stream: HashMap<u64, u32>, } impl<T> H2ClientTokioTransport<T> where T: Io + 'static { /// Create a new `H2ClientTokioTransport` that will use the given `Io` for its underlying raw /// IO needs. fn new(io: T) -> H2ClientTokioTransport<T> { let (read, write) = io.split(); H2ClientTokioTransport { sender: FrameSender::new(write), receiver: FrameReceiver::new(read), conn: ClientConnection::with_connection( HttpConnection::new(HttpScheme::Http), DefaultSessionState::<ClientMarker, H2Stream>::new()), ready_responses: ResponseChunkReceiver::new(), tokio_request_to_h2stream: HashMap::new(), } } /// Kicks off a new HTTP request. /// /// It will set up the HTTP/2 session state appropriately (start tracking a new stream) /// and queue up the required HTTP/2 frames onto the connection. /// /// Also starts tracking the mapping between the Tokio request ID (`request_id`) and the HTTP/2 /// stream ID that it ends up getting assigned to. fn start_request(&mut self, request_id: u64, headers: Vec<StaticHeader>, has_body: bool) -> Result<(), Http2Error> { let request = self.prepare_request(request_id, headers, has_body); // Start the request, obtaining the h2 stream ID. let stream_id = self.conn.start_request(request, &mut self.sender)?; // The ID has been assigned to the stream, so attach it to the stream instance too. // TODO(mlalic): The `solicit::Stream` trait should grow an `on_id_assigned` method which // would be called by the session (i.e. the `ClientConnection` in this case). // Indeed, this is slightly awkward... self.conn.state.get_stream_mut(stream_id).expect("stream _just_ created").stream_id = Some(stream_id); // Now that the h2 request has started, we can keep the mapping of the Tokio request ID to // the matching h2 stream. This is used once data chunks start coming in, so we can match // up the request ID we get there to the h2 stream that the data chunk should be given to. debug!("started new request; tokio request={}, h2 stream id={}", request_id, stream_id); self.tokio_request_to_h2stream.insert(request_id, stream_id); Ok(()) } /// Prepares a new RequestStream with the given headers. If the request won't have any body, it /// immediately closes the stream on the local end to ensure that the peer doesn't expect any /// data to come in on the stream. fn prepare_request(&mut self, request_id: u64, headers: Vec<StaticHeader>, has_body: bool) -> RequestStream<'static, 'static, H2Stream> { let mut stream = H2Stream::new(self.ready_responses.get_sender(request_id)); if !has_body { stream.close_local(); } RequestStream { stream: stream, headers: headers, } } /// Handles all frames currently found in the in buffer. After this completes, the buffer will /// no longer contain these frames and they will have been seen by the h2 connection, with all /// of their effects being reported to the h2 session. fn handle_new_frames(&mut self) -> Result<(), Http2Error> { // We have new data. Let's try parsing and handling as many h2 // frames as we can! while let Some(bytes_to_discard) = self.handle_next_frame()? { // So far, the frame wasn't copied out of the original input buffer. // Now, we'll simply discard from the input buffer... self.receiver.discard_frame(bytes_to_discard); } Ok(()) } /// Handles the next frame in the in buffer (if any) and returns its size in bytes. These bytes /// can now safely be discarded from the in buffer, as they have been processed by the h2 /// connection. fn handle_next_frame(&mut self) -> Result<Option<usize>, Http2Error> { let res = match self.receiver.get_next_frame() { None => None, Some(mut frame_container) => { // Give the frame_container to the conn... self.conn.handle_next_frame(&mut frame_container, &mut self.sender)?; Some(frame_container.len()) }, }; Ok(res) } /// Cleans up all closed streams. fn handle_closed_streams(&mut self) { // Simply let them get dropped. let done = self.conn.state.get_closed(); debug!("Number of streams that got closed = {}", done.len()); } /// Try to read more data off the socket and handle any HTTP/2 frames that we might /// successfully obtain. fn try_read_more(&mut self) -> Result<(), Http2Error> { let total_read = self.receiver.try_read()?; if total_read > 0 { self.handle_new_frames()?; // After processing frames, let's see if there are any streams that have been completed // as a result... self.handle_closed_streams(); // Make sure to issue a write for anything that might have been queued up // during the processing of the frames... self.sender.try_write()?; } Ok(()) } /// Dequeue the next response frame off the `ready_responses` queue. As a `Stream` can only /// yield a frame at a time, while we can resolve multiple streams (i.e. requests) in the same /// stream poll, we need to keep a queue of frames that the `Stream` can yield. fn get_next_response_frame(&mut self) -> Option<TokioResponseFrame> { self.ready_responses.get_next_chunk().map(|(request_id, response)| { match response { ResponseChunk::Headers(headers) => { trace!("Yielding a headers frame for request {}", request_id); Frame::Message { id: request_id, message: headers, body: true, solo: false, } }, ResponseChunk::Body(body) => { trace!("Yielding a body chunk for request {}", request_id); Frame::Body { id: request_id, chunk: Some(body), } }, ResponseChunk::EndOfBody => { trace!("Yielding an 'end of body' chunk for request {}", request_id); Frame::Body { id: request_id, chunk: None, } }, } }) } /// Add a body chunk to the request with the given Tokio ID. /// /// Currently, we assume that each request will contain only a single body chunk. fn add_body_chunk(&mut self, id: u64, chunk: Option<HttpRequestBody>) -> Result<(), Http2Error> { let stream_id = self.tokio_request_to_h2stream .get(&id) .ok_or(Http2Error::TokioSync(TokioSyncError::UnmatchedRequestId))?; match self.conn.state.get_stream_mut(*stream_id) { Some(mut stream) => { match chunk { Some(HttpRequestBody { body }) => { trace!("set data for a request stream {}", *stream_id); stream.add_data(body)?; }, None => { trace!("no more data for stream {}", *stream_id); stream.set_should_close(); }, }; }, None => {}, }; Ok(()) } /// Attempts to queue up more HTTP/2 frames onto the `sender`. fn try_write_next_data(&mut self) -> Result<bool, Http2Error> { self.conn.send_next_data(&mut self.sender).map_err(|e| e.into()).map(|res| { match res { SendStatus::Sent => true, SendStatus::Nothing => false, } }) } /// Try to push out some request body data onto the underlying `Io`. fn send_request_data(&mut self) -> Poll<(), io::Error> { if !self.has_pending_request_data() { // No more pending request data -- we're done sending all requests. return Ok(Async::Ready(())); } trace!("preparing a data frame"); let has_data = self.try_write_next_data()?; if has_data { debug!("queued up a new data frame"); if self.sender.try_write()? { trace!("wrote a full data frame without blocking"); // HACK!? Yield to the executor, but make sure we're called back asap... // Ensures that we don't simply end up writing a whole lot of request // data (bodies) while ignoring to appropriately (timely) handle other // aspects of h2 communication (applying settings, sendings acks, initiating // _new_ requests, ping/pong, etc...). let task = task::park(); task.unpark(); Ok(Async::NotReady) } else { // Did not manage to write the entire new frame without blocking. // We'll get rescheduled when the socket unblocks. Ok(Async::NotReady) } } else { trace!("no stream data ready"); // If we didn't manage to prepare a data frame, while there were still open // streams, it means that the stream didn't have the data ready for writing. // In other words, we've managed to write all Tokio requests -- i.e. anything // that passed through `start_send`. When there's another piece of the full // HTTP request body ready, we'll get it through `start_send`. Ok(Async::Ready(())) } } /// Checks whether any active h2 stream still has data that needs to be sent out to the server. /// Returns `true` if there is such a stream. /// /// This is done by simply checking whether all streams have transitioned into a locally closed /// state, which indicates that we're done transmitting from our end. fn has_pending_request_data(&mut self) -> bool { self.conn.state.iter().any(|(_id, stream)| { !stream.is_closed_local() }) } } impl<T> Stream for H2ClientTokioTransport<T> where T: Io + 'static { type Item = Frame<HttpResponseHeaders, HttpResponseBody, io::Error>; type Error = io::Error; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { trace!("polling read"); // First, try to see if there's anything more that we can read off the socket already... self.try_read_more()?; // Now return the first response that we have ready, if any. match self.get_next_response_frame() { None => Ok(Async::NotReady), Some(tokio_frame) => Ok(Async::Ready(Some(tokio_frame))), } } } impl<T> Sink for H2ClientTokioTransport<T> where T: Io + 'static { type SinkItem = Frame<HttpRequestHeaders, HttpRequestBody, io::Error>; // NOTE: For some reason, Tokio requires that the Transport uses io::Error for its error type, // so any non-IO errors, like HTTP/2 protocol errors (`solicit::http::HttpError`) are wrapped // in an `io::ErrorKind::Other`... type SinkError = io::Error; fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> { match item { Frame::Message { id, body: has_body, message: HttpRequestHeaders { headers }, .. } => { debug!("start new request id={}, body={}", id, has_body); trace!(" headers={:?}", headers); self.start_request(id, headers, has_body)?; }, Frame::Body { id, chunk } => { debug!("add body chunk for request id={}", id); self.add_body_chunk(id, chunk)?; }, _ => {}, } Ok(AsyncSink::Ready) } fn poll_complete(&mut self) -> Poll<(), Self::SinkError> { trace!("poll all requests sent?"); // Make sure to trigger a frame flush ... if self.sender.try_write()? { // If sending everything that was queued so far worked, let's see if we can queue up // some data frames, if there are streams that still need to send some. self.send_request_data() } else { // We didn't manage to write everything from our out buffer without blocking. // We'll get woken up when writing to the socket is possible again. Ok(Async::NotReady) } } } impl<ReadBody, T> Transport<ReadBody> for H2ClientTokioTransport<T> where T: Io + 'static { fn tick(&mut self) { trace!("TokioTransport TICKING"); } } /// A unit struct that serves to implement the `ClientProto` Tokio trait, which hooks up a /// raw `Io` to the `H2ClientTokioTransport`. /// /// This is _almost_ trivial, except it also is required to do protocol negotiation/initialization. /// /// For cleartext HTTP/2, this means simply sending out the client preface bytes, for which /// `solicit` provides a helper. /// /// The transport is resolved only once the preface write is complete, as only after this can the /// `solicit` `ClientConnection` take over management of the socket: once the HTTP/2 frames start /// flowing through. pub struct H2ClientTokioProto<Connector> where Connector: Service, Connector::Response: Io { pub connector: Connector, pub authority: String, } impl<T, Connector> ClientProto<T> for H2ClientTokioProto<Connector> where T: 'static + Io, Connector: 'static + Service<Request=H2ConnectorParams<T>, Error=io::Error>, Connector::Response: 'static + Io { type Request = HttpRequestHeaders; type RequestBody = HttpRequestBody; type Response = HttpResponseHeaders; type ResponseBody = HttpResponseBody; type Error = io::Error; type Transport = H2ClientTokioTransport<Connector::Response>; type BindTransport = Box<Future<Item=Self::Transport, Error=io::Error>>; fn bind_transport(&self, io: T) -> Self::BindTransport { let params = H2ConnectorParams::new(self.authority.clone(), io); let transport = self.connector.call(params) .and_then(|io| { // Prepare the preface into an in-memory buffer... let mut buf = io::Cursor::new(vec![]); let preface_buf_future = future::result( client::write_preface(&mut buf).map(move |_| buf.into_inner())); preface_buf_future .and_then(|buf| { trace!("Kicking off a client preface write"); tokio_io::write_all(io, buf) }) .map(|(io, _buf)| { debug!("client preface write complete"); H2ClientTokioTransport::new(io) }) }); Box::new(transport) } }