hexsha
stringlengths
40
40
size
int64
4
1.05M
content
stringlengths
4
1.05M
avg_line_length
float64
1.33
100
max_line_length
int64
1
1k
alphanum_fraction
float64
0.25
1
de4bd6c410df1f98b5a6f97efeae9a7ef6103e50
11,446
// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. use std::rc::Rc; use tipb::schema::ColumnInfo; use tipb::executor::Aggregation; use tipb::expression::Expr; use util::collections::{HashMap, HashMapEntry as Entry}; use coprocessor::codec::table::RowColsDict; use coprocessor::codec::datum::{self, approximate_size, Datum, DatumEncoder}; use coprocessor::endpoint::SINGLE_GROUP; use coprocessor::select::aggregate::{self, AggrFunc}; use coprocessor::select::xeval::{EvalContext, Evaluator}; use coprocessor::metrics::*; use coprocessor::Result; use super::{inflate_with_col_for_dag, Executor, ExprColumnRefVisitor, Row}; pub struct AggregationExecutor<'a> { group_by: Vec<Expr>, aggr_func: Vec<Expr>, group_keys: Vec<Rc<Vec<u8>>>, group_key_aggrs: HashMap<Rc<Vec<u8>>, Vec<Box<AggrFunc>>>, cursor: usize, executed: bool, ctx: Rc<EvalContext>, cols: Rc<Vec<ColumnInfo>>, related_cols_offset: Vec<usize>, // offset of related columns src: Box<Executor + 'a>, } impl<'a> AggregationExecutor<'a> { pub fn new( mut meta: Aggregation, ctx: Rc<EvalContext>, columns: Rc<Vec<ColumnInfo>>, src: Box<Executor + 'a>, ) -> Result<AggregationExecutor<'a>> { // collect all cols used in aggregation let mut visitor = ExprColumnRefVisitor::new(columns.len()); let group_by = meta.take_group_by().into_vec(); try!(visitor.batch_visit(&group_by)); let aggr_func = meta.take_agg_func().into_vec(); try!(visitor.batch_visit(&aggr_func)); COPR_EXECUTOR_COUNT .with_label_values(&["aggregation"]) .inc(); Ok(AggregationExecutor { group_by: group_by, aggr_func: aggr_func, group_keys: vec![], group_key_aggrs: map![], cursor: 0, executed: false, ctx: ctx, cols: columns, related_cols_offset: visitor.column_offsets(), src: src, }) } fn get_group_key(&mut self, eval: &mut Evaluator) -> Result<Vec<u8>> { if self.group_by.is_empty() { let single_group = Datum::Bytes(SINGLE_GROUP.to_vec()); return Ok(box_try!(datum::encode_value(&[single_group]))); } let mut vals = Vec::with_capacity(self.group_by.len()); for expr in &self.group_by { let v = box_try!(eval.eval(&self.ctx, expr)); vals.push(v); } let res = box_try!(datum::encode_value(&vals)); Ok(res) } fn aggregate(&mut self) -> Result<()> { while let Some(row) = try!(self.src.next()) { let mut eval = Evaluator::default(); try!(inflate_with_col_for_dag( &mut eval, &self.ctx, &row.data, self.cols.clone(), &self.related_cols_offset, row.handle )); let group_key = Rc::new(try!(self.get_group_key(&mut eval))); match self.group_key_aggrs.entry(group_key.clone()) { Entry::Vacant(e) => { let mut aggrs = Vec::with_capacity(self.aggr_func.len()); for expr in &self.aggr_func { let mut aggr = try!(aggregate::build_aggr_func(expr)); let vals = box_try!(eval.batch_eval(&self.ctx, expr.get_children())); try!(aggr.update(&self.ctx, vals)); aggrs.push(aggr); } self.group_keys.push(group_key); e.insert(aggrs); } Entry::Occupied(e) => { let aggrs = e.into_mut(); for (expr, aggr) in self.aggr_func.iter().zip(aggrs) { let vals = box_try!(eval.batch_eval(&self.ctx, expr.get_children())); box_try!(aggr.update(&self.ctx, vals)); } } } } Ok(()) } } impl<'a> Executor for AggregationExecutor<'a> { fn next(&mut self) -> Result<Option<Row>> { if !self.executed { try!(self.aggregate()); self.executed = true; } if self.cursor >= self.group_keys.len() { return Ok(None); } // calc all aggr func let mut aggr_cols = Vec::with_capacity(2 * self.aggr_func.len()); let group_key = &self.group_keys[self.cursor]; let mut aggrs = self.group_key_aggrs.remove(group_key).unwrap(); for aggr in &mut aggrs { try!(aggr.calc(&mut aggr_cols)); } // construct row data let value_size = group_key.len() + approximate_size(&aggr_cols, false); let mut value = Vec::with_capacity(value_size); box_try!(value.encode(aggr_cols.as_slice(), false)); value.extend_from_slice(group_key); self.cursor += 1; Ok(Some(Row { handle: 0, data: RowColsDict::new(map![], value), })) } } #[cfg(test)] mod test { use std::i64; use kvproto::kvrpcpb::IsolationLevel; use protobuf::RepeatedField; use tipb::executor::TableScan; use tipb::expression::{Expr, ExprType}; use coprocessor::codec::datum::{Datum, DatumDecoder}; use coprocessor::codec::mysql::decimal::Decimal; use coprocessor::codec::mysql::types; use storage::{SnapshotStore, Statistics}; use util::codec::number::NumberEncoder; use super::*; use super::super::table_scan::TableScanExecutor; use super::super::scanner::test::{get_range, new_col_info, TestStore}; use super::super::topn::test::gen_table_data; #[inline] fn build_expr(tp: ExprType, id: Option<i64>, child: Option<Expr>) -> Expr { let mut expr = Expr::new(); expr.set_tp(tp); if tp == ExprType::ColumnRef { expr.mut_val().encode_i64(id.unwrap()).unwrap(); } else { expr.mut_children().push(child.unwrap()); } expr } fn build_group_by(col_ids: &[i64]) -> Vec<Expr> { let mut group_by = Vec::with_capacity(col_ids.len()); for id in col_ids { group_by.push(build_expr(ExprType::ColumnRef, Some(*id), None)); } group_by } fn build_aggr_func(aggrs: &[(ExprType, i64)]) -> Vec<Expr> { let mut aggr_func = Vec::with_capacity(aggrs.len()); for aggr in aggrs { let &(tp, id) = aggr; let col_ref = build_expr(ExprType::ColumnRef, Some(id), None); aggr_func.push(build_expr(tp, None, Some(col_ref))); } aggr_func } #[test] fn test_aggregation() { // prepare data and store let tid = 1; let cis = vec![ new_col_info(1, types::LONG_LONG), new_col_info(2, types::VARCHAR), new_col_info(3, types::NEW_DECIMAL), ]; let raw_data = vec![ vec![ Datum::I64(1), Datum::Bytes(b"a".to_vec()), Datum::Dec(7.into()), ], vec![ Datum::I64(2), Datum::Bytes(b"a".to_vec()), Datum::Dec(7.into()), ], vec![ Datum::I64(3), Datum::Bytes(b"b".to_vec()), Datum::Dec(8.into()), ], vec![ Datum::I64(4), Datum::Bytes(b"a".to_vec()), Datum::Dec(7.into()), ], vec![ Datum::I64(5), Datum::Bytes(b"f".to_vec()), Datum::Dec(5.into()), ], vec![ Datum::I64(6), Datum::Bytes(b"b".to_vec()), Datum::Dec(8.into()), ], vec![ Datum::I64(7), Datum::Bytes(b"f".to_vec()), Datum::Dec(6.into()), ], ]; let table_data = gen_table_data(tid, &cis, &raw_data); let mut test_store = TestStore::new(&table_data); // init table scan meta let mut table_scan = TableScan::new(); table_scan.set_table_id(tid); table_scan.set_columns(RepeatedField::from_vec(cis.clone())); // init TableScan Exectutor let key_ranges = vec![get_range(tid, i64::MIN, i64::MAX)]; let (snapshot, start_ts) = test_store.get_snapshot(); let store = SnapshotStore::new(snapshot, start_ts, IsolationLevel::SI); let mut statistics = Statistics::default(); let ts_ect = TableScanExecutor::new(table_scan, key_ranges, store, &mut statistics); // init aggregation meta let mut aggregation = Aggregation::default(); let group_by_cols = vec![1, 2]; let group_by = build_group_by(&group_by_cols); aggregation.set_group_by(RepeatedField::from_vec(group_by)); let aggr_funcs = vec![(ExprType::Avg, 0), (ExprType::Count, 2)]; let aggr_funcs = build_aggr_func(&aggr_funcs); aggregation.set_agg_func(RepeatedField::from_vec(aggr_funcs)); // init Aggregation Executor let mut aggr_ect = AggregationExecutor::new( aggregation, Rc::new(EvalContext::default()), Rc::new(cis), Box::new(ts_ect), ).unwrap(); let expect_row_cnt = 4; let mut row_data = Vec::with_capacity(expect_row_cnt); while let Some(row) = aggr_ect.next().unwrap() { row_data.push(row.data); } assert_eq!(row_data.len(), expect_row_cnt); let expect_row_data = vec![ ( 3 as u64, Decimal::from(7), 3 as u64, b"a".as_ref(), Decimal::from(7), ), ( 2 as u64, Decimal::from(9), 2 as u64, b"b".as_ref(), Decimal::from(8), ), ( 1 as u64, Decimal::from(5), 1 as u64, b"f".as_ref(), Decimal::from(5), ), ( 1 as u64, Decimal::from(7), 1 as u64, b"f".as_ref(), Decimal::from(6), ), ]; let expect_col_cnt = 5; for (row, expect_cols) in row_data.into_iter().zip(expect_row_data) { let ds = row.value.as_slice().decode().unwrap(); assert_eq!(ds.len(), expect_col_cnt); assert_eq!(ds[0], Datum::from(expect_cols.0)); assert_eq!(ds[1], Datum::from(expect_cols.1)); assert_eq!(ds[2], Datum::from(expect_cols.2)); assert_eq!(ds[3], Datum::from(expect_cols.3)); assert_eq!(ds[4], Datum::from(expect_cols.4)); } } }
34.896341
93
0.531976
5d256c8be484daf3164df43b64b8204ea6180432
988
use crate::schema::{cheque::*, printer::*}; use anchor_lang::prelude::*; use anchor_spl::token; #[derive(Accounts)] pub struct InitializeCheque<'info> { pub stable_token: Account<'info, token::Mint>, pub secure_token: Account<'info, token::Mint>, #[account(mut)] pub authority: Signer<'info>, pub printer: Account<'info, Printer>, #[account( init, payer = authority, space = Cheque::LEN, seeds = [ b"cheque".as_ref(), &printer.key().to_bytes(), &secure_token.key().to_bytes(), &authority.key().to_bytes(), ], bump )] pub cheque: Account<'info, Cheque>, pub system_program: Program<'info, System>, pub rent: Sysvar<'info, Rent>, } pub fn exec(ctx: Context<InitializeCheque>) -> Result<()> { let cheque = &mut ctx.accounts.cheque; cheque.amount = 0; cheque.printer = ctx.accounts.printer.key(); cheque.secure_token = ctx.accounts.secure_token.key(); cheque.authority = ctx.accounts.authority.key(); Ok(()) }
26.702703
59
0.65081
f434b79db626172343288306e5f85e58e36f02a9
7,976
use std::sync::{Arc, Mutex}; use crate::complete_hint_line; use crate::config::Config; use crate::edit::State; use crate::error; use crate::history::SearchDirection; use crate::keymap::{Anchor, At, Cmd, Movement, Word}; use crate::keymap::{InputState, Refresher}; use crate::kill_ring::{KillRing, Mode}; use crate::line_buffer::WordAction; use crate::{Helper, Result}; pub enum Status { Proceed, Submit, } pub fn execute<H: Helper>( cmd: Cmd, s: &mut State<'_, '_, H>, input_state: &InputState, kill_ring: &Arc<Mutex<KillRing>>, config: &Config, ) -> Result<Status> { use Status::*; match cmd { Cmd::CompleteHint => { complete_hint_line(s)?; } Cmd::SelfInsert(n, c) => { s.edit_insert(c, n)?; } Cmd::Insert(n, text) => { s.edit_yank(input_state, &text, Anchor::Before, n)?; } Cmd::Move(Movement::BeginningOfLine) => { // Move to the beginning of line. s.edit_move_home()? } Cmd::Move(Movement::ViFirstPrint) => { s.edit_move_home()?; s.edit_move_to_next_word(At::Start, Word::Big, 1)? } Cmd::Move(Movement::BackwardChar(n)) => { // Move back a character. s.edit_move_backward(n)? } Cmd::ReplaceChar(n, c) => s.edit_replace_char(c, n)?, Cmd::Replace(mvt, text) => { s.edit_kill(&mvt)?; if let Some(text) = text { s.edit_insert_text(&text)? } } Cmd::Overwrite(c) => { s.edit_overwrite_char(c)?; } Cmd::EndOfFile => { if s.has_hint() || !s.is_default_prompt() { // Force a refresh without hints to leave the previous // line as the user typed it after a newline. s.refresh_line_with_msg(None)?; } if s.line.is_empty() { return Err(error::ReadlineError::Eof); } else if !input_state.is_emacs_mode() { return Ok(Submit); } } Cmd::Move(Movement::EndOfLine) => { // Move to the end of line. s.edit_move_end()? } Cmd::Move(Movement::ForwardChar(n)) => { // Move forward a character. s.edit_move_forward(n)? } Cmd::ClearScreen => { // Clear the screen leaving the current line at the top of the screen. s.clear_screen()?; s.refresh_line()? } Cmd::NextHistory => { // Fetch the next command from the history list. s.edit_history_next(false)? } Cmd::PreviousHistory => { // Fetch the previous command from the history list. s.edit_history_next(true)? } Cmd::LineUpOrPreviousHistory(n) => { if !s.edit_move_line_up(n)? { s.edit_history_next(true)? } } Cmd::LineDownOrNextHistory(n) => { if !s.edit_move_line_down(n)? { s.edit_history_next(false)? } } Cmd::HistorySearchBackward => s.edit_history_search(SearchDirection::Reverse)?, Cmd::HistorySearchForward => s.edit_history_search(SearchDirection::Forward)?, Cmd::TransposeChars => { // Exchange the char before cursor with the character at cursor. s.edit_transpose_chars()? } Cmd::Yank(n, anchor) => { // retrieve (yank) last item killed let mut kill_ring = kill_ring.lock().unwrap(); if let Some(text) = kill_ring.yank() { s.edit_yank(input_state, text, anchor, n)? } } Cmd::ViYankTo(ref mvt) => { if let Some(text) = s.line.copy(mvt) { let mut kill_ring = kill_ring.lock().unwrap(); kill_ring.kill(&text, Mode::Append) } } Cmd::AcceptLine | Cmd::AcceptOrInsertLine { .. } | Cmd::Newline => { if s.has_hint() || !s.is_default_prompt() { // Force a refresh without hints to leave the previous // line as the user typed it after a newline. s.refresh_line_with_msg(None)?; } let validation_result = s.validate()?; let valid = validation_result.is_valid(); let end = s.line.is_end_of_input(); match (cmd, valid, end) { (Cmd::AcceptLine, ..) | (Cmd::AcceptOrInsertLine { .. }, true, true) | ( Cmd::AcceptOrInsertLine { accept_in_the_middle: true, }, true, _, ) => { return Ok(Submit); } (Cmd::Newline, ..) | (Cmd::AcceptOrInsertLine { .. }, false, _) | (Cmd::AcceptOrInsertLine { .. }, true, false) => { if valid || !validation_result.has_message() { s.edit_insert('\n', 1)?; } } _ => unreachable!(), } } Cmd::BeginningOfHistory => { // move to first entry in history s.edit_history(true)? } Cmd::EndOfHistory => { // move to last entry in history s.edit_history(false)? } Cmd::Move(Movement::BackwardWord(n, word_def)) => { // move backwards one word s.edit_move_to_prev_word(word_def, n)? } Cmd::CapitalizeWord => { // capitalize word after point s.edit_word(WordAction::Capitalize)? } Cmd::Kill(ref mvt) => { s.edit_kill(mvt)?; } Cmd::Move(Movement::ForwardWord(n, at, word_def)) => { // move forwards one word s.edit_move_to_next_word(at, word_def, n)? } Cmd::Move(Movement::LineUp(n)) => { s.edit_move_line_up(n)?; } Cmd::Move(Movement::LineDown(n)) => { s.edit_move_line_down(n)?; } Cmd::Move(Movement::BeginningOfBuffer) => { // Move to the start of the buffer. s.edit_move_buffer_start()? } Cmd::Move(Movement::EndOfBuffer) => { // Move to the end of the buffer. s.edit_move_buffer_end()? } Cmd::DowncaseWord => { // lowercase word after point s.edit_word(WordAction::Lowercase)? } Cmd::TransposeWords(n) => { // transpose words s.edit_transpose_words(n)? } Cmd::UpcaseWord => { // uppercase word after point s.edit_word(WordAction::Uppercase)? } Cmd::YankPop => { // yank-pop let mut kill_ring = kill_ring.lock().unwrap(); if let Some((yank_size, text)) = kill_ring.yank_pop() { s.edit_yank_pop(yank_size, text)? } } Cmd::Move(Movement::ViCharSearch(n, cs)) => s.edit_move_to(cs, n)?, Cmd::Undo(n) => { if s.changes.borrow_mut().undo(&mut s.line, n) { s.refresh_line()?; } } Cmd::Dedent(mvt) => { s.edit_indent(&mvt, config.indent_size(), true)?; } Cmd::Indent(mvt) => { s.edit_indent(&mvt, config.indent_size(), false)?; } Cmd::Interrupt => { // Move to end, in case cursor was in the middle of the // line, so that next thing application prints goes after // the input s.edit_move_buffer_end()?; return Err(error::ReadlineError::Interrupted); } _ => { // Ignore the character typed. } } Ok(Proceed) }
34.08547
87
0.492854
4abc71653c8a89582ba4d76602dfa97397900010
1,745
use bevy::{ input::system::exit_on_esc_system as exit_on_esc, prelude::*, render::camera::WindowOrigin, window::exit_on_window_close_system as exit_on_close, }; use sliding_puzzle_game::{GamePlugins, GameState, TextLabel}; #[bevy_main] fn main() { App::new() // background color .insert_resource(ClearColor(Color::ORANGE)) .add_plugins(DefaultPlugins) // this is the actual game .add_plugins(GamePlugins) // welcome to game .add_state(GameState::default()) // show our ui and so on .add_startup_system(setup_camera) // window close don't app exit default .add_system(exit_on_close) // exit on esc pressed .add_system(exit_on_esc) .add_system(viewport) .run(); } // setup both ui camera and 2d camera with origin is bottom left fn setup_camera(mut commands: Commands) { commands.spawn_bundle(UiCameraBundle::default()); let mut camera = OrthographicCameraBundle::new_2d(); camera.orthographic_projection.window_origin = WindowOrigin::BottomLeft; commands.spawn_bundle(camera); } // adjust text during window resize fn viewport(windows: Res<Windows>, mut query: Query<(&TextLabel, &mut Text)>) { if windows.is_changed() { if let Some(window) = windows.get_primary() { query.for_each_mut(|(label, mut text)| { text.sections .iter_mut() .zip(label.scales.iter()) .for_each(|(section, scale)| { section.style.font_size = (window.width() * scale.width).min(window.height() * scale.height); }); }); } } }
34.215686
95
0.606304
75bbc3ab233ef1afa52427ce8d0d786ccce838f0
10,327
#![no_std] #![forbid(unsafe_code)] #![feature(const_panic)] #![feature(const_mut_refs)] #![allow(clippy::needless_return)] //! This crate enables reading of Gameboy Filesystem (`GBFS`)-formatted data. //! It's primarily designed for use in GBA games, and as such is fully `no_std` compatible (even `alloc` is not required). mod error; pub use error::*; mod header; use header::*; use core::str; use core::u32; use arrayvec::{ArrayString, ArrayVec}; use byte_slice_cast::AsSliceOf; /// Maximum length of a filename in bytes. Is 24 in the pin-eight C implementation pub const FILENAME_LEN: usize = 24; /// Length of a single file's entry in the directory that precedes the data. const DIR_ENTRY_LEN: usize = 32; // TODO: Allow control at build-time by user for different ROM use/flexibility tradeoffs. const NUM_FS_ENTRIES: usize = 2048; /// The name of a GBFS file. This is not a regular string because filenames have a limited length. type Filename = ArrayString<FILENAME_LEN>; #[derive(Debug, Copy, Clone)] struct GBFSFileEntry { /// Name of file; at most 24 bytes. /// TODO: Once const fn's can perform subslicing, use a slice here name: [u8; FILENAME_LEN], /// Length of file in bytes len: u32, /// Offset of first file byte from start of filesystem data_offset: u32, } impl GBFSFileEntry { /// Compare the name with a Filename. fn name_is_equal(&self, name: Filename) -> Result<bool, GBFSError> { // Unfortunately, the const fn constructor for GBFSFilesystem // can't use dynamically-sized data structures. // Therefore, we have to strip out the trailing nulls from the filename here. let no_nulls: ArrayVec<u8, { FILENAME_LEN }> = self.name.iter().filter(|x| **x != 0).copied().collect(); let filename_str: &str = match str::from_utf8(no_nulls.as_ref()) { Ok(s) => s, Err(e) => return Err(GBFSError::Utf8Error(e)), }; match Filename::from(filename_str) { Err(_) => return Err(GBFSError::FilenameTooLong(FILENAME_LEN, filename_str.len())), Ok(our_name) => return Ok(name == our_name), } } } /// A filesystem that files can be read from. // Needed to ensure proper alignment for casting u8 slices to u16/u32 slices #[repr(align(4))] #[repr(C)] #[derive(Clone)] pub struct GBFSFilesystem<'a> { /// Backing data slice data: &'a [u8], /// Filesystem header hdr: GBFSHeader, /// Directory dir: [Option<GBFSFileEntry>; NUM_FS_ENTRIES], } impl<'a> GBFSFilesystem<'a> { /// Constructs a new filesystem from a GBFS-formatted byte slice. /// /// To make lifetime management easier it's probably a good idea to use a slice with a `static` lifetime here. /// It's also a good idea to ensure this function is called at compile time with a `const` argument, /// to avoid having to store the filesystem index in RAM. pub const fn from_slice(data: &'a [u8]) -> Result<GBFSFilesystem<'a>, GBFSError> { // TODO: Assert slice alignment // Brace yourself for some very ugly code caused by the limitations of const fn below. // Create the FS header // Forgive me God, for I have sinned // TODO: Clean up this mess (maybe a macro?) let hdr: GBFSHeader; if data.len() < header::GBFS_HEADER_LENGTH { return Err(GBFSError::HeaderInvalid); } match GBFSHeader::from_slice(&[ data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15], data[16], data[17], data[18], data[19], data[20], data[21], data[22], data[23], data[24], data[25], data[26], data[27], data[28], data[29], data[30], data[31], ]) { Ok(val) => hdr = val, Err(err) => return Err(err), } // Create the FS entry table // Read directory entries let mut dir_entries: [Option<GBFSFileEntry>; NUM_FS_ENTRIES] = [None; NUM_FS_ENTRIES]; // Can't use a for loop here because they're not yet supported in const fn's let mut i = 0; if (hdr.dir_num_members as usize) > NUM_FS_ENTRIES { return Err(GBFSError::TooManyEntries( NUM_FS_ENTRIES, hdr.dir_num_members as usize, )); } while i < hdr.dir_num_members as usize { let entry_start = hdr.dir_off as usize + ((i as usize) * DIR_ENTRY_LEN); // Extract filename if data.len() < entry_start + FILENAME_LEN { return Err(GBFSError::Truncated); } // TODO: DRY let filename: [u8; FILENAME_LEN] = [ data[entry_start], data[entry_start + 1], data[entry_start + 2], data[entry_start + 3], data[entry_start + 4], data[entry_start + 5], data[entry_start + 6], data[entry_start + 7], data[entry_start + 8], data[entry_start + 9], data[entry_start + 10], data[entry_start + 11], data[entry_start + 12], data[entry_start + 13], data[entry_start + 14], data[entry_start + 15], data[entry_start + 16], data[entry_start + 17], data[entry_start + 18], data[entry_start + 19], data[entry_start + 20], data[entry_start + 21], data[entry_start + 22], data[entry_start + 23], ]; // Extract length of file in bytes if data.len() < entry_start + FILENAME_LEN + 4 { return Err(GBFSError::Truncated); }; let len = u32::from_le_bytes([ data[(entry_start + FILENAME_LEN)], data[entry_start + FILENAME_LEN + 1], data[entry_start + FILENAME_LEN + 2], data[entry_start + FILENAME_LEN + 3], ]); // Extract offset of file data from FS start if data.len() < entry_start + FILENAME_LEN + 8 { return Err(GBFSError::Truncated); }; let data_offset = u32::from_le_bytes([ data[(entry_start + FILENAME_LEN + 4)], data[entry_start + FILENAME_LEN + 5], data[entry_start + FILENAME_LEN + 6], data[entry_start + FILENAME_LEN + 7], ]); dir_entries[i] = Some(GBFSFileEntry { name: filename, len, data_offset, }); i += 1; } return Ok(GBFSFilesystem { data, hdr, dir: dir_entries, }); } /// Gets file data by index in directory table. fn get_file_data_by_index(&self, index: usize) -> &'a [u8] { // The storage format changes based on whether we have a static filesystem or // once created at runtime. let dir_entry_wrapped = self.dir[index]; let dir_entry = dir_entry_wrapped // This should never trigger. .expect("Attempt to access file with nonexistent index. This is a bug in gbfs_rs."); return &self.data[dir_entry.data_offset as usize ..(dir_entry.data_offset as usize + dir_entry.len as usize)]; } /// Returns a reference to the file data as a slice of u8's. /// An error is returned if the file does not exist or the filename is invalid. /// All filenames longer than `FILENAME_LEN` characters are invalid. pub fn get_file_data_by_name(&self, str_name: &str) -> Result<&'a [u8], GBFSError> { let name: Filename; match Filename::from(str_name) { Ok(val) => name = val, Err(_) => return Err(GBFSError::FilenameTooLong(FILENAME_LEN, str_name.len())), } // In this case, dir entries are stored in a fixed-size // array using an Option to denote occupied slots. for (i, entry) in self.dir.iter().enumerate() { match entry { Some(inner_entry) => { if inner_entry.name_is_equal(name)? { return Ok(self.get_file_data_by_index(i)); } } None => return Err(GBFSError::NoSuchFile(name)), } } return Err(GBFSError::NoSuchFile(name)); } /// Returns a reference to the file data as a slice of u32's. /// An error is returned if the file does not exist, it's length is not a multiple of 2 /// or the filename is invalid. /// All filenames longer than 24 characters are invalid. pub fn get_file_data_by_name_as_u16_slice(&self, name: &str) -> Result<&'a [u16], GBFSError> { return Ok(self.get_file_data_by_name(name)?.as_slice_of::<u16>()?); } /// Returns a reference to the file data as a slice of u32's. /// An error is returned if the file does not exist, it's length is not a multiple of 4 /// or the filename is invalid. /// All filenames longer than 24 characters are invalid. pub fn get_file_data_by_name_as_u32_slice(&self, name: &str) -> Result<&'a [u32], GBFSError> { return Ok(self.get_file_data_by_name(name)?.as_slice_of::<u32>()?); } } impl<'a> IntoIterator for GBFSFilesystem<'a> { type Item = &'a [u8]; type IntoIter = GBFSFilesystemIterator<'a>; fn into_iter(self) -> Self::IntoIter { return GBFSFilesystemIterator { fs: self, next_file_index: 0, }; } } /// Returns the data of each file in the filesystem. pub struct GBFSFilesystemIterator<'a> { fs: GBFSFilesystem<'a>, next_file_index: usize, } impl<'a> Iterator for GBFSFilesystemIterator<'a> { type Item = &'a [u8]; fn next(&mut self) -> Option<Self::Item> { if self.next_file_index < self.fs.hdr.dir_num_members as usize { let ret = Some(self.fs.get_file_data_by_index(self.next_file_index)); self.next_file_index += 1; return ret; } else { return None; } } }
38.969811
122
0.582066
b96c970174f7681d80783d47e9af35fb1053bb41
5,343
// Copyright 2020. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. mod block_template_data; mod block_template_protocol; mod cli; mod common; mod config; mod error; mod proxy; #[cfg(test)] mod test; use std::{ convert::Infallible, io::{stdout, Write}, }; use clap::Parser; use crossterm::{execute, terminal::SetTitle}; use futures::future; use hyper::{service::make_service_fn, Server}; use log::*; use proxy::MergeMiningProxyService; use tari_app_grpc::tari_rpc as grpc; use tari_app_utilities::consts; use tari_common::{initialize_logging, load_configuration, DefaultConfigLoader}; use tari_comms::utils::multiaddr::multiaddr_to_socketaddr; use tari_core::proof_of_work::randomx_factory::RandomXFactory; use tokio::time::Duration; use crate::{ block_template_data::BlockTemplateRepository, cli::Cli, config::MergeMiningProxyConfig, error::MmProxyError, }; const LOG_TARGET: &str = "tari_mm_proxy::proxy"; #[tokio::main] async fn main() -> Result<(), anyhow::Error> { let terminal_title = format!("Tari Merge Mining Proxy - Version {}", consts::APP_VERSION); if let Err(e) = execute!(stdout(), SetTitle(terminal_title.as_str())) { println!("Error setting terminal title. {}", e) } let cli = Cli::parse(); let config_path = cli.common.config_path(); let cfg = load_configuration(&config_path, true, &cli.config_property_overrides())?; initialize_logging( &cli.common.log_config_path("proxy"), include_str!("../log4rs_sample.yml"), )?; let config = MergeMiningProxyConfig::load_from(&cfg)?; error!(target: LOG_TARGET, "Configuration: {:?}", config); let client = reqwest::Client::builder() .connect_timeout(Duration::from_secs(5)) .timeout(Duration::from_secs(10)) .pool_max_idle_per_host(25) .build() .map_err(MmProxyError::ReqwestError)?; let base_node = multiaddr_to_socketaddr(&config.base_node_grpc_address)?; info!(target: LOG_TARGET, "Connecting to base node at {}", base_node); println!("Connecting to base node at {}", base_node); let base_node_client = grpc::base_node_client::BaseNodeClient::connect(format!("http://{}", base_node)).await?; let wallet = multiaddr_to_socketaddr(&config.console_wallet_grpc_address)?; info!(target: LOG_TARGET, "Connecting to wallet at {}", wallet); println!("Connecting to wallet at {}", wallet); let wallet_client = grpc::wallet_client::WalletClient::connect(format!("http://{}", wallet)).await?; let listen_addr = multiaddr_to_socketaddr(&config.listener_address)?; let randomx_factory = RandomXFactory::new(config.max_randomx_vms); let xmrig_service = MergeMiningProxyService::new( config, client, base_node_client, wallet_client, BlockTemplateRepository::new(), randomx_factory, ); let service = make_service_fn(|_conn| future::ready(Result::<_, Infallible>::Ok(xmrig_service.clone()))); match Server::try_bind(&listen_addr) { Ok(builder) => { info!(target: LOG_TARGET, "Listening on {}...", listen_addr); println!("Listening on {}...", listen_addr); builder.serve(service).await?; Ok(()) }, Err(err) => { error!(target: LOG_TARGET, "Fatal: Cannot bind to '{}'.", listen_addr); println!("Fatal: Cannot bind to '{}'.", listen_addr); println!("It may be part of a Port Exclusion Range. Please try to use another port for the"); println!("'proxy_host_address' in 'config/config.toml' and for the applicable XMRig '[pools][url]' or"); println!("[pools][self-select]' config setting that can be found in 'config/xmrig_config_***.json' or"); println!("'<xmrig folder>/config.json'."); println!(); Err(err.into()) }, } }
42.744
118
0.69811
03c82fde0292757100684d3fbc6ecc4468d43733
1,006
use crate::io; use crate::path::Path; use crate::task::spawn_blocking; use crate::utils::Context as _; /// Removes a file. /// /// This function is an async version of [`std::fs::remove_file`]. /// /// [`std::fs::remove_file`]: https://doc.rust-lang.org/std/fs/fn.remove_file.html /// /// # Errors /// /// An error will be returned in the following situations: /// /// * `path` does not point to an existing file. /// * The current process lacks permissions to remove the file. /// * Some other I/O error occurred. /// /// # Examples /// /// ```no_run /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async { /// # /// use async_std::fs; /// /// fs::remove_file("a.txt").await?; /// # /// # Ok(()) }) } /// ``` pub async fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> { let path = path.as_ref().to_owned(); spawn_blocking(move || { std::fs::remove_file(&path) .context(|| format!("could not remove file `{}`", path.display())) }) .await? }
25.794872
82
0.590457
5b18a71eabd8118a11eab6cb899c2defd5faebd5
18,371
#![feature(decl_macro)] use std::thread; extern crate env_logger; extern crate sgx_types; extern crate sgx_urts; extern crate mio; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; #[macro_use] extern crate rocket; #[macro_use] extern crate rocket_contrib; extern crate rocket_cors; extern crate serde; extern crate serde_json; #[macro_use] extern crate serde_derive; extern crate enclave_api; extern crate structopt; extern crate parity_scale_codec; #[cfg(test)] mod tests; #[cfg(test)] extern crate ring_compat; #[cfg(test)] extern crate base64; #[cfg(test)] extern crate hex_literal; mod attestation; mod contract_input; mod contract_output; use colored::Colorize; use sgx_types::*; use sgx_urts::SgxEnclave; use std::fs; use std::path; use std::str; use std::sync::RwLock; use std::env; use rocket::data::Data; use rocket::http::Status; use rocket::response::status::Custom; use rocket::http::Method; use rocket_contrib::json::{Json, JsonValue}; use rocket_cors::{AllowedHeaders, AllowedOrigins, AllowedMethods, CorsOptions}; use structopt::StructOpt; use contract_input::ContractInput; use enclave_api::{actions, prpc}; #[derive(StructOpt, Debug)] #[structopt(name = "pruntime", about = "The Phala TEE worker app.")] struct Args { /// Number of CPU cores to be used for mining. #[structopt(short, long)] cores: Option<u32> } static ENCLAVE_FILE: &'static str = "enclave.signed.so"; static ENCLAVE_STATE_FILE: &'static str = "enclave.token"; const ENCLAVE_OUTPUT_BUF_MAX_LEN: usize = 10*2048*1024 as usize; lazy_static! { static ref ENCLAVE: RwLock<Option<SgxEnclave>> = RwLock::new(None); static ref ENCLAVE_STATE_FILE_PATH: &'static str = { Box::leak( env::var("STATE_FILE_PATH").unwrap_or_else(|_| "./".to_string()).into_boxed_str() ) }; static ref ALLOW_CORS: bool = { env::var("ALLOW_CORS").unwrap_or_else(|_| "".to_string()) != "" }; static ref ENABLE_KICK_API: bool = { env::var("ENABLE_KICK_API").unwrap_or_else(|_| "".to_string()) != "" }; } fn destroy_enclave() { let enclave = ENCLAVE.write().unwrap().take().unwrap(); enclave.destroy(); } fn get_eid() -> u64 { ENCLAVE.read().unwrap().as_ref().unwrap().geteid() } extern { fn ecall_handle( eid: sgx_enclave_id_t, retval: *mut sgx_status_t, action: u8, input_ptr: *const u8, input_len: usize, output_ptr : *mut u8, output_len_ptr: *mut usize, output_buf_len: usize ) -> sgx_status_t; fn ecall_init( eid: sgx_enclave_id_t, retval: *mut sgx_status_t ) -> sgx_status_t; fn ecall_bench_run( eid: sgx_enclave_id_t, retval: *mut sgx_status_t, index: u32, ) -> sgx_status_t; fn ecall_prpc_request( eid: sgx_enclave_id_t, retval: *mut sgx_status_t, path: *const uint8_t, path_len: usize, data: *const uint8_t, data_len: usize, status_code: *mut u16, output_ptr: *mut uint8_t, output_buf_len: usize, output_len_ptr: *mut usize, ) -> sgx_status_t; } const IAS_SPID_STR: &str = env!("IAS_SPID"); const IAS_API_KEY_STR: &str = env!("IAS_API_KEY"); #[no_mangle] pub extern "C" fn ocall_load_ias_spid( key_ptr : *mut u8, key_len_ptr: *mut usize, key_buf_len: usize ) -> sgx_status_t { let key_len = IAS_SPID_STR.len(); unsafe { if key_len <= key_buf_len { std::ptr::copy_nonoverlapping(IAS_SPID_STR.as_ptr(), key_ptr, key_len); } else { panic!("IAS_SPID_STR too long. Buffer overflow."); } std::ptr::copy_nonoverlapping(&key_len as *const usize, key_len_ptr, std::mem::size_of_val(&key_len)); } sgx_status_t::SGX_SUCCESS } #[no_mangle] pub extern "C" fn ocall_load_ias_key( key_ptr : *mut u8, key_len_ptr: *mut usize, key_buf_len: usize ) -> sgx_status_t { let key_len = IAS_API_KEY_STR.len(); unsafe { if key_len <= key_buf_len { std::ptr::copy_nonoverlapping(IAS_API_KEY_STR.as_ptr(), key_ptr, key_len); } else { panic!("IAS_API_KEY_STR too long. Buffer overflow."); } std::ptr::copy_nonoverlapping(&key_len as *const usize, key_len_ptr, std::mem::size_of_val(&key_len)); } sgx_status_t::SGX_SUCCESS } #[no_mangle] pub extern "C" fn ocall_sgx_init_quote(ret_ti: *mut sgx_target_info_t, ret_gid : *mut sgx_epid_group_id_t) -> sgx_status_t { info!("Entering ocall_sgx_init_quote"); unsafe { sgx_init_quote(ret_ti, ret_gid) } } #[no_mangle] pub extern "C" fn ocall_get_quote (p_sigrl : *const u8, sigrl_len : u32, p_report : *const sgx_report_t, quote_type : sgx_quote_sign_type_t, p_spid : *const sgx_spid_t, p_nonce : *const sgx_quote_nonce_t, p_qe_report : *mut sgx_report_t, p_quote : *mut u8, _maxlen : u32, p_quote_len : *mut u32) -> sgx_status_t { info!("Entering ocall_get_quote"); let mut real_quote_len : u32 = 0; let ret = unsafe { sgx_calc_quote_size(p_sigrl, sigrl_len, &mut real_quote_len as *mut u32) }; if ret != sgx_status_t::SGX_SUCCESS { warn!("sgx_calc_quote_size returned {}", ret); return ret; } info!("quote size = {}", real_quote_len); unsafe { *p_quote_len = real_quote_len; } let ret = unsafe { sgx_get_quote(p_report, quote_type, p_spid, p_nonce, p_sigrl, sigrl_len, p_qe_report, p_quote as *mut sgx_quote_t, real_quote_len) }; if ret != sgx_status_t::SGX_SUCCESS { warn!("sgx_calc_quote_size returned {}", ret); return ret; } info!("sgx_calc_quote_size returned {}", ret); ret } #[no_mangle] pub extern "C" fn ocall_get_update_info( platform_blob: * const sgx_platform_info_t, enclave_trusted: i32, update_info: * mut sgx_update_info_bit_t ) -> sgx_status_t { unsafe{ sgx_report_attestation_status(platform_blob, enclave_trusted, update_info) } } #[no_mangle] pub extern "C" fn ocall_dump_state( _output_ptr : *mut u8, _output_len_ptr: *mut usize, _output_buf_len: usize ) -> sgx_status_t { // TODO: sgx_status_t::SGX_SUCCESS } #[no_mangle] pub extern "C" fn ocall_save_persistent_data( input_ptr: *const u8, input_len: usize ) -> sgx_status_t { let input_slice = unsafe { std::slice::from_raw_parts(input_ptr, input_len) }; debug!("Sealed data {:}: {:?}", input_len, hex::encode(input_slice)); let executable = env::current_exe().unwrap(); let path = executable.parent().unwrap(); let state_path: path::PathBuf = path.join(*ENCLAVE_STATE_FILE_PATH).join(ENCLAVE_STATE_FILE); info!("Save seal data to {}", state_path.as_path().to_str().unwrap()); fs::write(state_path.as_path().to_str().unwrap(), input_slice) .expect("Failed to write persistent data"); sgx_status_t::SGX_SUCCESS } #[no_mangle] pub extern "C" fn ocall_load_persistent_data( output_ptr : *mut u8, output_len_ptr: *mut usize, output_buf_len: usize ) -> sgx_status_t { let executable = env::current_exe().unwrap(); let path = executable.parent().unwrap(); let state_path: path::PathBuf = path.join(*ENCLAVE_STATE_FILE_PATH).join(ENCLAVE_STATE_FILE); let state = match fs::read(state_path.as_path().to_str().unwrap()) { Ok(data) => data, _ => Vec::<u8>::new() }; let state_len = state.len(); if state_len == 0 { return sgx_status_t::SGX_SUCCESS } info!("Loaded sealed data {:}: {:?}", state_len, state); unsafe { if state_len <= output_buf_len { std::ptr::copy_nonoverlapping(state.as_ptr(), output_ptr, state_len); } else { panic!("State too long. Buffer overflow."); } std::ptr::copy_nonoverlapping(&state_len as *const usize, output_len_ptr, std::mem::size_of_val(&state_len)); } sgx_status_t::SGX_SUCCESS } fn init_enclave() -> SgxResult<SgxEnclave> { let mut launch_token: sgx_launch_token_t = [0; 1024]; let mut launch_token_updated: i32 = 0; // call sgx_create_enclave to initialize an enclave instance // Debug Support: set 2nd parameter to 1 let debug = option_env!("SGX_DEBUG").unwrap_or("1"); let mut misc_attr = sgx_misc_attribute_t {secs_attr: sgx_attributes_t {flags:0, xfrm:0}, misc_select:0}; SgxEnclave::create(ENCLAVE_FILE, if debug == "0" { 0 } else { 1 }, &mut launch_token, &mut launch_token_updated, &mut misc_attr) } macro_rules! do_ecall_handle { ($num: expr, $content: expr) => {{ let eid = crate::get_eid(); let mut return_output_buf = vec![0; crate::ENCLAVE_OUTPUT_BUF_MAX_LEN].into_boxed_slice(); let mut output_len : usize = 0; let output_slice = &mut return_output_buf; let output_ptr = output_slice.as_mut_ptr(); let output_len_ptr = &mut output_len as *mut usize; let mut retval = crate::sgx_status_t::SGX_SUCCESS; let result = unsafe { crate::ecall_handle( eid, &mut retval, $num, $content.as_ptr(), $content.len(), output_ptr, output_len_ptr, crate::ENCLAVE_OUTPUT_BUF_MAX_LEN ) }; match result { crate::sgx_status_t::SGX_SUCCESS => { let output_slice = unsafe { std::slice::from_raw_parts(output_ptr, output_len) }; let output_value: serde_json::value::Value = serde_json::from_slice(output_slice).unwrap(); json!(output_value) }, _ => { error!("[-] ECALL Enclave Failed {}!", result.as_str()); json!({ "status": "error", "payload": format!("[-] ECALL Enclave Failed {}!", result.as_str()) }) } } }}; } macro_rules! proxy { ($rpc: literal, $name: ident, $num: expr) => { #[post($rpc, format = "json", data = "<contract_input>")] fn $name(contract_input: Json<ContractInput>) -> JsonValue { debug!("{}", ::serde_json::to_string_pretty(&*contract_input).unwrap()); let input_string = serde_json::to_string(&*contract_input).unwrap(); do_ecall_handle!($num, input_string) } }; } fn read_data(data: Data) -> Option<Vec<u8>> { use std::io::Read; let mut stream = data.open(); let mut data = Vec::new(); stream.read_to_end(&mut data).ok()?; Some(data) } macro_rules! proxy_bin { ($rpc: literal, $name: ident, $num: expr) => { #[post($rpc, data = "<data>")] fn $name(data: Data) -> JsonValue { let data = match read_data(data) { Some(data) => data, None => { return json!({ "status": "error", "payload": "Io error: Read input data failed" }) } }; do_ecall_handle!($num, data) } }; } proxy!("/test", test, actions::ACTION_TEST); proxy!("/init_runtime", init_runtime, actions::ACTION_INIT_RUNTIME); proxy!("/get_info", get_info, actions::ACTION_GET_INFO); proxy!("/get_runtime_info", get_runtime_info, actions::ACTION_GET_RUNTIME_INFO); proxy!("/dump_states", dump_states, actions::ACTION_DUMP_STATES); proxy!("/load_states", load_states, actions::ACTION_LOAD_STATES); proxy!("/query", query, actions::ACTION_QUERY); proxy!("/get_egress_messages", get_egress_messages, actions::ACTION_GET_EGRESS_MESSAGES); proxy!("/test_ink", test_ink, actions::ACTION_TEST_INK); proxy_bin!("/bin_api/sync_header", sync_header, actions::BIN_ACTION_SYNC_HEADER); proxy_bin!("/bin_api/dispatch_block", dispatch_block, actions::BIN_ACTION_DISPATCH_BLOCK); proxy_bin!("/bin_api/sync_para_header", sync_para_header, actions::BIN_ACTION_SYNC_PARA_HEADER); #[post("/kick")] fn kick() { // TODO: we should improve this info!("Kick API received, destroying enclave..."); destroy_enclave(); std::process::exit(0); } #[post("/<method>", data = "<data>")] fn prpc_proxy(method: String, data: Data) -> Custom<Vec<u8>> { let eid = crate::get_eid(); let path_bytes = method.as_bytes(); let path_len = path_bytes.len(); let path_ptr = path_bytes.as_ptr(); let data = match crate::read_data(data) { Some(data) => data, None => { return Custom(Status::BadRequest, b"Read body failed".to_vec()); } }; let data_len = data.len(); let data_ptr = data.as_ptr(); let mut output_buf = vec![0; crate::ENCLAVE_OUTPUT_BUF_MAX_LEN]; let output_buf_len = output_buf.len(); let output_ptr = output_buf.as_mut_ptr(); let mut output_len : usize = 0; let output_len_ptr = &mut output_len as *mut usize; let mut status_code: u16 = 500; let mut retval = crate::sgx_status_t::SGX_SUCCESS; let result = unsafe { crate::ecall_prpc_request( eid, &mut retval, path_ptr, path_len, data_ptr, data_len, &mut status_code, output_ptr, output_buf_len, output_len_ptr ) }; match result { crate::sgx_status_t::SGX_SUCCESS => { let output_slice = unsafe { std::slice::from_raw_parts(output_ptr, output_len) }; if let Some(status) = Status::from_code(status_code) { Custom(status, output_slice.to_vec()) } else { error!("[-] prpc: Invalid status code: {}!", status_code); Custom(Status::ServiceUnavailable, vec![]) } }, _ => { error!("[-] ECALL Enclave Failed {}!", result.as_str()); Custom(Status::ServiceUnavailable, vec![]) } } } fn cors_options() -> CorsOptions { let allowed_origins = AllowedOrigins::all(); let allowed_methods: AllowedMethods = vec![Method::Get, Method::Post].into_iter().map(From::from).collect(); // You can also deserialize this rocket_cors::CorsOptions { allowed_origins, allowed_methods, allowed_headers: AllowedHeaders::all(), allow_credentials: true, ..Default::default() } } fn print_rpc_methods(prefix: &str, methods: &[&str]) { info!("Methods under {}:", prefix); for method in methods { info!(" {}", format!("{}/{}", prefix, method).blue()); } } fn rocket() -> rocket::Rocket { let mut server = rocket::ignite() .mount("/", routes![ test, init_runtime, get_info, dump_states, load_states, sync_header, dispatch_block, query, get_runtime_info, get_egress_messages, test_ink, sync_para_header, ]); if *ENABLE_KICK_API { info!("ENABLE `kick` API"); server = server.mount("/", routes![kick]); } server = server.mount("/prpc", routes![prpc_proxy]); print_rpc_methods("/prpc", prpc::phactory_api_server::supported_methods()); if *ALLOW_CORS { info!("Allow CORS"); server .mount("/", rocket_cors::catch_all_options_routes()) // mount the catch all routes .attach(cors_options().to_cors().expect("To not fail")) .manage(cors_options().to_cors().expect("To not fail")) } else { server } } fn main() { let args = Args::from_args(); env::set_var("RUST_BACKTRACE", "1"); env::set_var("ROCKET_ENV", "dev"); env_logger::builder() .filter_level(log::LevelFilter::Info) .parse_default_env() .init(); let enclave = match init_enclave() { Ok(r) => { info!("[+] Init Enclave Successful, pid={}!", r.geteid()); r }, Err(x) => { panic!("[-] Init Enclave Failed {}!", x.as_str()); }, }; ENCLAVE.write().unwrap().replace(enclave); let eid = get_eid(); let mut retval = sgx_status_t::SGX_SUCCESS; let result = unsafe { ecall_init(eid, &mut retval) }; if result != sgx_status_t::SGX_SUCCESS { panic!("Initialize Failed"); } let bench_cores: u32 = args.cores.unwrap_or_else(|| num_cpus::get() as _); info!("Bench cores: {}", bench_cores); let rocket = thread::spawn(move || { rocket().launch(); }); let mut v = vec![]; for i in 0..bench_cores { let child = thread::spawn(move || { set_thread_idle_policy(); loop { let result = unsafe { ecall_bench_run(eid, &mut retval, i) }; if result != sgx_status_t::SGX_SUCCESS { panic!("Run benchmark {} failed", i); } std::thread::sleep(std::time::Duration::from_millis(200)); } }); v.push(child); } let _ = rocket.join(); for child in v { let _ = child.join(); } info!("Quit signal received, destroying enclave..."); destroy_enclave(); std::process::exit(0); } fn set_thread_idle_policy() { let param = libc::sched_param { sched_priority: 0, }; unsafe { let rv = libc::sched_setscheduler(0, libc::SCHED_IDLE, &param); if rv != 0 { error!("Failed to set thread schedule prolicy to IDLE"); } } }
29.440705
112
0.579936
33be77a4ee206ee0c8b00a78be4b43a821b03991
1,620
use rocket::request::Form; use rocket_contrib::Template; use rocket::response::status; use rocket::http; use {todo_filter, CookieSessionId, QueryParams}; use super::visit_todos; use db::redis::RedisConnection; use db::todos::Repository; use view_models::todos::context; #[derive(Debug, FromForm)] struct UpdateForm { command: Option<String>, } #[get("/?<query_params>")] pub fn show( query_params: Option<QueryParams>, session_id: CookieSessionId, db: RedisConnection, ) -> Result<Template, status::Custom<String>> { let repo = Repository::new(session_id.into(), db); render_todos(query_params, repo) } #[patch("/?<query_params>", data = "<form>")] fn update( form: Form<UpdateForm>, query_params: Option<QueryParams>, session_id: CookieSessionId, db: RedisConnection, ) -> Result<String, status::Custom<String>> { let form_data = form.get(); let repo = Repository::new(session_id.into(), db); match form_data.command { Some(ref x) if x == "clear_completed" => repo.clear_completed()?, Some(ref x) if x == "activate_all" => repo.activate_all()?, Some(ref x) if x == "complete_all" => repo.complete_all()?, _ => Err(status::Custom( http::Status::BadRequest, "Unexpected command".into(), ))?, }; visit_todos(query_params) } fn render_todos( query_params: Option<QueryParams>, repo: Repository, ) -> Result<Template, status::Custom<String>> { let filter = todo_filter(query_params)?; let context = context(repo, &filter)?; Ok(Template::render("todos/list", &context)) }
27
73
0.658642
38c60241c103dc7e9211067180d4781f7ccbc275
8,019
#![allow(unused_imports, non_camel_case_types)] use crate::models::r4b::Element::Element; use crate::models::r4b::Extension::Extension; use serde_json::json; use serde_json::value::Value; use std::borrow::Cow; /// Describes a required data item for evaluation in terms of the type of data, and /// optional code or date-based filters of the data. #[derive(Debug)] pub struct DataRequirement_Sort<'a> { pub(crate) value: Cow<'a, Value>, } impl DataRequirement_Sort<'_> { pub fn new(value: &Value) -> DataRequirement_Sort { DataRequirement_Sort { value: Cow::Borrowed(value), } } pub fn to_json(&self) -> Value { (*self.value).clone() } /// Extensions for direction pub fn _direction(&self) -> Option<Element> { if let Some(val) = self.value.get("_direction") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// Extensions for path pub fn _path(&self) -> Option<Element> { if let Some(val) = self.value.get("_path") { return Some(Element { value: Cow::Borrowed(val), }); } return None; } /// The direction of the sort, ascending or descending. pub fn direction(&self) -> Option<DataRequirement_SortDirection> { if let Some(Value::String(val)) = self.value.get("direction") { return Some(DataRequirement_SortDirection::from_string(&val).unwrap()); } return None; } /// May be used to represent additional information that is not part of the basic /// definition of the element. To make the use of extensions safe and manageable, /// there is a strict set of governance applied to the definition and use of /// extensions. Though any implementer can define an extension, there is a set of /// requirements that SHALL be met as part of the definition of the extension. pub fn extension(&self) -> Option<Vec<Extension>> { if let Some(Value::Array(val)) = self.value.get("extension") { return Some( val.into_iter() .map(|e| Extension { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// Unique id for the element within a resource (for internal references). This may be /// any string value that does not contain spaces. pub fn id(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("id") { return Some(string); } return None; } /// May be used to represent additional information that is not part of the basic /// definition of the element and that modifies the understanding of the element /// in which it is contained and/or the understanding of the containing element's /// descendants. Usually modifier elements provide negation or qualification. To make /// the use of extensions safe and manageable, there is a strict set of governance /// applied to the definition and use of extensions. Though any implementer can define /// an extension, there is a set of requirements that SHALL be met as part of the /// definition of the extension. Applications processing a resource are required to /// check for modifier extensions. Modifier extensions SHALL NOT change the meaning /// of any elements on Resource or DomainResource (including cannot change the meaning /// of modifierExtension itself). pub fn modifier_extension(&self) -> Option<Vec<Extension>> { if let Some(Value::Array(val)) = self.value.get("modifierExtension") { return Some( val.into_iter() .map(|e| Extension { value: Cow::Borrowed(e), }) .collect::<Vec<_>>(), ); } return None; } /// The attribute of the sort. The specified path must be resolvable from the type of /// the required data. The path is allowed to contain qualifiers (.) to traverse sub- /// elements, as well as indexers ([x]) to traverse multiple-cardinality sub-elements. /// Note that the index must be an integer constant. pub fn path(&self) -> Option<&str> { if let Some(Value::String(string)) = self.value.get("path") { return Some(string); } return None; } pub fn validate(&self) -> bool { if let Some(_val) = self._direction() { if !_val.validate() { return false; } } if let Some(_val) = self._path() { if !_val.validate() { return false; } } if let Some(_val) = self.direction() {} if let Some(_val) = self.extension() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if let Some(_val) = self.id() {} if let Some(_val) = self.modifier_extension() { if !_val.into_iter().map(|e| e.validate()).all(|x| x == true) { return false; } } if let Some(_val) = self.path() {} return true; } } #[derive(Debug)] pub struct DataRequirement_SortBuilder { pub(crate) value: Value, } impl DataRequirement_SortBuilder { pub fn build(&self) -> DataRequirement_Sort { DataRequirement_Sort { value: Cow::Owned(self.value.clone()), } } pub fn with(existing: DataRequirement_Sort) -> DataRequirement_SortBuilder { DataRequirement_SortBuilder { value: (*existing.value).clone(), } } pub fn new() -> DataRequirement_SortBuilder { let mut __value: Value = json!({}); return DataRequirement_SortBuilder { value: __value }; } pub fn _direction<'a>(&'a mut self, val: Element) -> &'a mut DataRequirement_SortBuilder { self.value["_direction"] = json!(val.value); return self; } pub fn _path<'a>(&'a mut self, val: Element) -> &'a mut DataRequirement_SortBuilder { self.value["_path"] = json!(val.value); return self; } pub fn direction<'a>( &'a mut self, val: DataRequirement_SortDirection, ) -> &'a mut DataRequirement_SortBuilder { self.value["direction"] = json!(val.to_string()); return self; } pub fn extension<'a>(&'a mut self, val: Vec<Extension>) -> &'a mut DataRequirement_SortBuilder { self.value["extension"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn id<'a>(&'a mut self, val: &str) -> &'a mut DataRequirement_SortBuilder { self.value["id"] = json!(val); return self; } pub fn modifier_extension<'a>( &'a mut self, val: Vec<Extension>, ) -> &'a mut DataRequirement_SortBuilder { self.value["modifierExtension"] = json!(val.into_iter().map(|e| e.value).collect::<Vec<_>>()); return self; } pub fn path<'a>(&'a mut self, val: &str) -> &'a mut DataRequirement_SortBuilder { self.value["path"] = json!(val); return self; } } #[derive(Debug)] pub enum DataRequirement_SortDirection { Ascending, Descending, } impl DataRequirement_SortDirection { pub fn from_string(string: &str) -> Option<DataRequirement_SortDirection> { match string { "ascending" => Some(DataRequirement_SortDirection::Ascending), "descending" => Some(DataRequirement_SortDirection::Descending), _ => None, } } pub fn to_string(&self) -> String { match self { DataRequirement_SortDirection::Ascending => "ascending".to_string(), DataRequirement_SortDirection::Descending => "descending".to_string(), } } }
34.269231
100
0.587729
ed230be5bf79f7f31689f076279d21dee5865bf2
16,196
// Copyright Materialize, Inc. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0. //! Transformations based on pulling information about individual columns from sources. use std::collections::HashMap; use itertools::Itertools; use expr::{MirRelationExpr, MirScalarExpr, UnaryFunc}; use repr::Datum; use repr::{ColumnType, RelationType, ScalarType}; use crate::TransformArgs; /// Harvest and act upon per-column information. #[derive(Debug)] pub struct ColumnKnowledge; impl crate::Transform for ColumnKnowledge { fn transform( &self, expr: &mut MirRelationExpr, _: TransformArgs, ) -> Result<(), crate::TransformError> { self.transform(expr) } } impl ColumnKnowledge { /// Transforms an expression through accumulated knowledge. pub fn transform(&self, expr: &mut MirRelationExpr) -> Result<(), crate::TransformError> { ColumnKnowledge::harvest(expr, &mut HashMap::new())?; Ok(()) } /// Harvest per-column knowledge. fn harvest( expr: &mut MirRelationExpr, knowledge: &mut HashMap<expr::Id, Vec<DatumKnowledge>>, ) -> Result<Vec<DatumKnowledge>, crate::TransformError> { Ok(match expr { MirRelationExpr::ArrangeBy { input, .. } => ColumnKnowledge::harvest(input, knowledge)?, MirRelationExpr::Get { id, typ } => knowledge .get(id) .cloned() .unwrap_or_else(|| typ.column_types.iter().map(DatumKnowledge::from).collect()), MirRelationExpr::Constant { rows, typ } => { if rows.len() == 1 { let mut row_packer = repr::RowPacker::new(); rows[0] .0 .iter() .zip(typ.column_types.iter()) .map(|(datum, typ)| DatumKnowledge { value: Some((row_packer.pack(Some(datum.clone())), typ.clone())), nullable: datum == Datum::Null, }) .collect() } else { typ.column_types.iter().map(DatumKnowledge::from).collect() } } MirRelationExpr::Let { id, value, body } => { let value_knowledge = ColumnKnowledge::harvest(value, knowledge)?; let prior_knowledge = knowledge.insert(expr::Id::Local(id.clone()), value_knowledge); let body_knowledge = ColumnKnowledge::harvest(body, knowledge)?; knowledge.remove(&expr::Id::Local(id.clone())); if let Some(prior_knowledge) = prior_knowledge { knowledge.insert(expr::Id::Local(id.clone()), prior_knowledge); } body_knowledge } MirRelationExpr::Project { input, outputs } => { let input_knowledge = ColumnKnowledge::harvest(input, knowledge)?; outputs .iter() .map(|i| input_knowledge[*i].clone()) .collect() } MirRelationExpr::Map { input, scalars } => { let mut input_knowledge = ColumnKnowledge::harvest(input, knowledge)?; for scalar in scalars.iter_mut() { let know = optimize(scalar, &input.typ(), &input_knowledge[..])?; input_knowledge.push(know); } input_knowledge } MirRelationExpr::FlatMap { input, func, exprs, demand: _, } => { let mut input_knowledge = ColumnKnowledge::harvest(input, knowledge)?; for expr in exprs { optimize(expr, &input.typ(), &input_knowledge[..])?; } let func_typ = func.output_type(); input_knowledge.extend(func_typ.column_types.iter().map(DatumKnowledge::from)); input_knowledge } MirRelationExpr::Filter { input, predicates } => { let mut input_knowledge = ColumnKnowledge::harvest(input, knowledge)?; for predicate in predicates.iter_mut() { optimize(predicate, &input.typ(), &input_knowledge[..])?; } // If any predicate tests a column for equality, truth, or is_null, we learn stuff. for predicate in predicates.iter() { // Equality tests allow us to unify the column knowledge of each input. if let MirScalarExpr::CallBinary { func, expr1, expr2 } = predicate { if func == &expr::BinaryFunc::Eq { // Collect knowledge about the inputs (for columns and literals). let mut knowledge = DatumKnowledge::default(); if let MirScalarExpr::Column(c) = &**expr1 { knowledge.absorb(&input_knowledge[*c]); } if let MirScalarExpr::Column(c) = &**expr2 { knowledge.absorb(&input_knowledge[*c]); } // Absorb literal knowledge about columns. knowledge.absorb(&DatumKnowledge::from(&**expr1)); knowledge.absorb(&DatumKnowledge::from(&**expr2)); // Write back unified knowledge to each column. if let MirScalarExpr::Column(c) = &**expr1 { input_knowledge[*c].absorb(&knowledge); } if let MirScalarExpr::Column(c) = &**expr2 { input_knowledge[*c].absorb(&knowledge); } } } if let MirScalarExpr::CallUnary { func: UnaryFunc::Not, expr, } = predicate { if let MirScalarExpr::CallUnary { func: UnaryFunc::IsNull, expr, } = &**expr { if let MirScalarExpr::Column(c) = &**expr { input_knowledge[*c].nullable = false; } } } } input_knowledge } MirRelationExpr::Join { inputs, equivalences, .. } => { let mut knowledges = Vec::new(); for input in inputs.iter_mut() { for knowledge in ColumnKnowledge::harvest(input, knowledge)? { knowledges.push(knowledge); } } for equivalence in equivalences.iter_mut() { let mut knowledge = DatumKnowledge::default(); // We can produce composite knowledge for everything in the equivalence class. for expr in equivalence.iter_mut() { if let MirScalarExpr::Column(c) = expr { knowledge.absorb(&knowledges[*c]); } knowledge.absorb(&DatumKnowledge::from(&*expr)); } for expr in equivalence.iter_mut() { if let MirScalarExpr::Column(c) = expr { knowledges[*c] = knowledge.clone(); } } } knowledges } MirRelationExpr::Reduce { input, group_key, aggregates, monotonic: _, expected_group_size: _, } => { let input_knowledge = ColumnKnowledge::harvest(input, knowledge)?; let mut output = group_key .iter_mut() .map(|k| optimize(k, &input.typ(), &input_knowledge[..])) .collect::<Result<Vec<_>, _>>()?; for aggregate in aggregates.iter_mut() { use expr::AggregateFunc; let knowledge = optimize(&mut aggregate.expr, &input.typ(), &input_knowledge[..])?; // This could be improved. let knowledge = match aggregate.func { AggregateFunc::MaxInt32 | AggregateFunc::MaxInt64 | AggregateFunc::MaxFloat32 | AggregateFunc::MaxFloat64 | AggregateFunc::MaxDecimal | AggregateFunc::MaxBool | AggregateFunc::MaxString | AggregateFunc::MaxDate | AggregateFunc::MaxTimestamp | AggregateFunc::MaxTimestampTz | AggregateFunc::MinInt32 | AggregateFunc::MinInt64 | AggregateFunc::MinFloat32 | AggregateFunc::MinFloat64 | AggregateFunc::MinDecimal | AggregateFunc::MinBool | AggregateFunc::MinString | AggregateFunc::MinDate | AggregateFunc::MinTimestamp | AggregateFunc::MinTimestampTz | AggregateFunc::Any | AggregateFunc::All => { // These methods propagate constant values exactly. knowledge } _ => { // All aggregates are non-null if their inputs are non-null. DatumKnowledge { value: None, nullable: knowledge.nullable, } } }; output.push(knowledge); } output } MirRelationExpr::TopK { input, .. } => ColumnKnowledge::harvest(input, knowledge)?, MirRelationExpr::Negate { input } => ColumnKnowledge::harvest(input, knowledge)?, MirRelationExpr::Threshold { input } => ColumnKnowledge::harvest(input, knowledge)?, MirRelationExpr::Union { base, inputs } => { let mut know = ColumnKnowledge::harvest(base, knowledge)?; for input in inputs { know = know .into_iter() .zip_eq(ColumnKnowledge::harvest(input, knowledge)?) .map(|(k1, k2)| DatumKnowledge { value: if k1.value == k2.value { k1.value.clone() } else { None }, nullable: k1.nullable || k2.nullable, }) .collect(); } know } }) } } /// Information about a specific column. #[derive(Clone, Debug)] pub struct DatumKnowledge { /// If set, a specific value for the column. value: Option<(repr::Row, ColumnType)>, /// If false, the value is not `Datum::Null`. nullable: bool, } impl DatumKnowledge { // Intersects the two knowledge about a column. fn absorb(&mut self, other: &Self) { self.nullable &= other.nullable; if self.value.is_none() { self.value = other.value.clone() } } } impl Default for DatumKnowledge { fn default() -> Self { Self { value: None, nullable: true, } } } impl From<&MirScalarExpr> for DatumKnowledge { fn from(expr: &MirScalarExpr) -> Self { if let MirScalarExpr::Literal(Ok(l), t) = expr { Self { value: Some((l.clone(), t.clone())), nullable: expr.is_literal_null(), } } else { Self::default() } } } impl From<&ColumnType> for DatumKnowledge { fn from(typ: &ColumnType) -> Self { Self { value: None, nullable: typ.nullable, } } } /// Attempts to optimize pub fn optimize( expr: &mut MirScalarExpr, input_type: &RelationType, column_knowledge: &[DatumKnowledge], ) -> Result<DatumKnowledge, crate::TransformError> { Ok(match expr { MirScalarExpr::Column(index) => { let index = *index; if let Some((datum, typ)) = &column_knowledge[index].value { *expr = MirScalarExpr::Literal(Ok(datum.clone()), typ.clone()); } column_knowledge[index].clone() } MirScalarExpr::Literal(res, typ) => { let row = match res { Ok(row) => row, Err(err) => return Err(err.clone().into()), }; DatumKnowledge { value: Some((row.clone(), typ.clone())), nullable: row.unpack_first() == Datum::Null, } } MirScalarExpr::CallNullary(_) => { expr.reduce(input_type); optimize(expr, input_type, column_knowledge)? } MirScalarExpr::CallUnary { func, expr: inner } => { let knowledge = optimize(inner, input_type, column_knowledge)?; if knowledge.value.is_some() { expr.reduce(input_type); optimize(expr, input_type, column_knowledge)? } else if func == &UnaryFunc::IsNull && !knowledge.nullable { *expr = MirScalarExpr::literal_ok(Datum::False, ScalarType::Bool); optimize(expr, input_type, column_knowledge)? } else { DatumKnowledge::default() } } MirScalarExpr::CallBinary { func: _, expr1, expr2, } => { let knowledge1 = optimize(expr1, input_type, column_knowledge)?; let knowledge2 = optimize(expr2, input_type, column_knowledge)?; if knowledge1.value.is_some() && knowledge2.value.is_some() { expr.reduce(input_type); optimize(expr, input_type, column_knowledge)? } else { DatumKnowledge::default() } } MirScalarExpr::CallVariadic { func: _, exprs } => { let mut knows = Vec::new(); for expr in exprs.iter_mut() { knows.push(optimize(expr, input_type, column_knowledge)?); } if knows.iter().all(|k| k.value.is_some()) { expr.reduce(input_type); optimize(expr, input_type, column_knowledge)? } else { DatumKnowledge::default() } } MirScalarExpr::If { cond, then, els } => { if let Some((value, _typ)) = optimize(cond, input_type, column_knowledge)?.value { match value.unpack_first() { Datum::True => *expr = (**then).clone(), Datum::False | Datum::Null => *expr = (**els).clone(), d => panic!("IF condition evaluated to non-boolean datum {:?}", d), } optimize(expr, input_type, column_knowledge)? } else { DatumKnowledge::default() } } }) }
40.288557
100
0.47098
33da07a2cd93fcf5ca9470b10dc9c560c77fe664
630
mod consts; mod de; mod ser; use js_sys::Array; use pulldown_cmark::Options; use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn tokens(text: String, options: u32) -> Array { let parser = pulldown_cmark::Parser::new_ext(&text, Options::from_bits_truncate(options)); parser.into_iter().map(ser::serialize).collect() } #[wasm_bindgen] pub fn html(tokens: Array) -> Result<String, JsValue> { let events = tokens .iter() .map(de::deserialize) .collect::<Result<Vec<_>, _>>()?; let mut html = String::new(); pulldown_cmark::html::push_html(&mut html, events.into_iter()); Ok(html) }
25.2
94
0.65873
e9ec57072450ecc22820bb294377886fa7cf56eb
886
use crate::color::RGBAColor; use super::{ drawing::{line, rect}, polygon, }; pub struct Point(u32, u32); pub trait DrawingBase { fn get_size(&self) -> (u32, u32); fn borrow_mut_buf(&mut self) -> &mut Vec<RGBAColor>; fn focus(&self, upper_left: Point, lower_right: Point) -> &Self where Self: Sized; fn draw_line(&mut self, from: (i32, i32), to: (i32, i32), line_width: u32) where Self: Sized, { line::draw_line(self, from, to, line_width); } fn draw_circle(&mut self); fn draw_rect( &mut self, upper_left: (u32, u32), bottom_right: (u32, u32), fill: Option<RGBAColor>, ) where Self: Sized, { rect::draw_rect(self, upper_left, bottom_right, fill) } fn draw_polygon(&mut self) { polygon::draw_polygon(); } fn draw_text(&mut self); }
23.315789
78
0.576749
cc9ed9f2e966b4f08cd1f0bc7d4f975a90b6acff
4,622
use priority_queue::PriorityQueue; use std::collections::HashMap; use xcg::utils::Trim; use xcg::model::*; use xcg::bot::common::Weight; use xcg::bot::common::{P, a_star_find}; use xcg::bot::common::distance; #[test] fn test_a_star() { let mut gs = game_state(r#" *.*.*.*.*.*.*.*.*.*.*. *. . . . . . . . . .*. *. . . . . . . . . .*. *. . . . a a a . . .*. *. . . . a A a . . .*. *. . . . . . a . . .*. *. . a a a a a . . .*. *. . . . . . . . . .*. *.*.*.*.*.*.*.*.*.*.*. "#); let m = gs.field.m as i16; let n = gs.field.n as i16; let me = gs.players[0].body().iter().map(|p| P(p.1, m - 1 - p.0)).collect::<Vec<P>>(); let is_boundary = |p: &P| { let P(x, y) = *p; 0 <= y && y < m && 0 <= x && x < n && !me.contains(&p) }; let heuristic = |p: &P, q: &P| distance(p, q); // we are using decartes coordinates, src -> dst let pairs = [ (P(5, 4), P(9, 2)), (P(5, 4), P(8, 3)) ]; let mut gs_paths: Vec<String> = vec![]; for (src, dst) in pairs.iter() { // clear previous path for i in 0..gs.field.m { for j in 0..gs.field.n { match gs.field.cells[i][j] { Cell::Owned(_) => gs.field.cells[i][j] = Cell::Empty, _ => (), } } } let path = { // use this logger for the debugging let mut _logger = Some(|ol: &PriorityQueue<P, Weight>, cl: &HashMap<P, P>| { for (k, _) in ol { let P(x, y) = *k; let j = x as usize; let i = (m as usize) - 1 - (y as usize); gs.field.cells[i][j] = Cell::Owned(0); } for (p, _) in cl { let P(x, y) = *p; let j = x as usize; let i = (m as usize) - 1 - (y as usize); gs.field.cells[i][j] = Cell::Owned(1); } println!("{}", prettify_game_state(&gs, false, false)); println!("{:?}", ol); }); let logger: Option<fn(&PriorityQueue<P, Weight>, &HashMap<P, P>)> = None; a_star_find(&src, &dst, is_boundary, heuristic, logger) }; if let Some(path) = path { println!("path = {:?}", path); for P(x, y) in path { let j = x as usize; let i = (m as usize) - 1 - (y as usize); gs.field.cells[i][j] = Cell::Owned(2); } gs_paths.push(prettify_game_state(&gs, false, false)); } } // (5,4) -> (9,2) let exp0 = r#" * * * * * * * * * * * * . . . . . . . . . * * . . . . . . . . . * * . . . a a a . . . * * . . . a A a . . . * * 2 2 2 2 2 a . . . * * 2 a a a a a 2 2 2 * * 2 2 2 2 2 2 2 . . * * * * * * * * * * * * "#.trim_indent(); let exp0 = format!("A: 0 \n{}\niteration: 0\n", exp0); assert_eq!(exp0, gs_paths[0]); // (5,4) -> (9,2) let exp1 = r#" * * * * * * * * * * * * . . . . . . . . . * * . . 2 2 2 2 2 . . * * . . 2 a a a 2 . . * * . . 2 a A a 2 . . * * . . 2 2 2 a 2 2 . * * . a a a a a . . . * * . . . . . . . . . * * * * * * * * * * * * "#.trim_indent(); let exp1 = format!("A: 0 \n{}\niteration: 0\n", exp1); assert_eq!(exp1, gs_paths[1]); } #[test] fn test_a_cannot_find() { let gs = game_state(r#" *.*.*.*.*.*.*.*.*.*. *. . . . . . . . .*. *. . a a a a a . .*. *. . A . . . a . .*. *. . a a a a a . .*. *. . . . . . . . .*. *.*.*.*.*.*.*.*.*.*. "#); let m = gs.field.m as i16; let n = gs.field.n as i16; let me = gs.players[0].body().iter().map(|p| P(p.1, m - 1 - p.0)).collect::<Vec<P>>(); let is_boundary = |p: &P| { let P(x, y) = *p; 0 <= y && y < m && 0 <= x && x < n && !me.contains(&p) }; let heuristic = |p: &P, q: &P| distance(p, q); // we are using decartes coordinates, src -> dst let src = P(4, 3); let dst = P(8, 1); let logger: Option<fn(&PriorityQueue<P, Weight>, &HashMap<P, P>)> = None; let path = a_star_find(&src, &dst, is_boundary, heuristic, logger); assert_eq!(path, None); } fn game_state(gs: &str) -> GameState { GameState::parse_string(&gs.trim_indent()).unwrap() }
32.097222
90
0.368888
f52f42245c65ccbcfb3752fe977c7fc8f1406873
46,637
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! An implementation of a client for a fidl interface. use { crate::{ encoding::{ decode_transaction_header, Decodable, Decoder, Encodable, Encoder, EpitaphBody, TransactionHeader, TransactionMessage, }, handle::{AsyncChannel, Handle, MessageBuf}, Error, }, fuchsia_zircon_status as zx_status, futures::{ future::{self, AndThen, Either, Future, FutureExt, Ready, TryFutureExt}, ready, stream::{FusedStream, Stream}, task::{Context, Poll, Waker}, }, parking_lot::Mutex, slab::Slab, std::{collections::VecDeque, marker::Unpin, mem, ops::Deref, pin::Pin, sync::Arc}, }; #[cfg(target_os = "fuchsia")] use fuchsia_zircon::AsHandleRef; fn decode_transaction_body<D: Decodable>(mut buf: MessageBuf) -> Result<D, Error> { let (bytes, handles) = buf.split_mut(); let (header, body_bytes) = decode_transaction_header(bytes)?; let mut output = D::new_empty(); Decoder::decode_into(&header, body_bytes, handles, &mut output)?; Ok(output) } fn decode_transaction_body_fut<D: Decodable>(buf: MessageBuf) -> Ready<Result<D, Error>> { future::ready(decode_transaction_body(buf)) } /// A FIDL client which can be used to send buffers and receive responses via a channel. #[derive(Debug, Clone)] pub struct Client { inner: Arc<ClientInner>, } /// A future representing the raw response to a FIDL query. pub type RawQueryResponseFut = Either<Ready<Result<MessageBuf, Error>>, MessageResponse>; /// A future representing the decoded response to a FIDL query. pub type QueryResponseFut<D> = AndThen< RawQueryResponseFut, Ready<Result<D, Error>>, fn(MessageBuf) -> Ready<Result<D, Error>>, >; /// A FIDL transaction id. Will not be zero for a message that includes a response. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct Txid(u32); /// A message interest id. #[derive(Debug, Copy, Clone, PartialEq, Eq)] struct InterestId(usize); impl InterestId { fn from_txid(txid: Txid) -> Self { InterestId(txid.0 as usize - 1) } fn as_raw_id(&self) -> usize { self.0 } } impl Txid { fn from_interest_id(int_id: InterestId) -> Self { Txid((int_id.0 + 1) as u32) } /// Get the raw u32 transaction ID. pub fn as_raw_id(&self) -> u32 { self.0 } } impl From<u32> for Txid { fn from(txid: u32) -> Self { Self(txid) } } impl Client { /// Create a new client. /// /// `channel` is the asynchronous channel over which data is sent and received. /// `event_ordinals` are the ordinals on which events will be received. pub fn new(channel: AsyncChannel) -> Client { Client { inner: Arc::new(ClientInner { channel: channel, message_interests: Mutex::new(Slab::<MessageInterest>::new()), event_channel: Mutex::default(), epitaph: Mutex::default(), }), } } /// Attempt to convert the `Client` back into a channel. /// /// This will only succeed if there are no active clones of this `Client` /// and no currently-alive `EventReceiver` or `MessageResponse`s that /// came from this `Client`. pub fn into_channel(self) -> Result<AsyncChannel, Self> { match Arc::try_unwrap(self.inner) { Ok(ClientInner { channel, .. }) => Ok(channel), Err(inner) => Err(Self { inner }), } } /// Retrieve the stream of event messages for the `Client`. /// Panics if the stream was already taken. pub fn take_event_receiver(&self) -> EventReceiver { { let mut lock = self.inner.event_channel.lock(); if let EventListener::None = lock.listener { lock.listener = EventListener::WillPoll; } else { panic!("Event stream was already taken"); } } EventReceiver { inner: self.inner.clone(), terminated: false } } /// Send an encodable message without expecting a response. pub fn send<T: Encodable>(&self, body: &mut T, ordinal: u64) -> Result<(), Error> { let msg = &mut TransactionMessage { header: TransactionHeader::new(0, ordinal), body }; crate::encoding::with_tls_encoded(msg, |bytes, handles| { self.send_raw_msg(&**bytes, handles) }) } /// Send an encodable query and receive a decodable response. pub fn send_query<E: Encodable, D: Decodable>( &self, msg: &mut E, ordinal: u64, ) -> QueryResponseFut<D> { let res_fut = self.send_raw_query(|tx_id, bytes, handles| { let msg = &mut TransactionMessage { header: TransactionHeader::new(tx_id.as_raw_id(), ordinal), body: msg, }; Encoder::encode(bytes, handles, msg)?; Ok(()) }); res_fut.and_then(decode_transaction_body_fut::<D>) } /// Send a raw message without expecting a response. pub fn send_raw_msg(&self, buf: &[u8], handles: &mut Vec<Handle>) -> Result<(), Error> { Ok(self.inner.channel.write(buf, handles).map_err(|e| Error::ClientWrite(e.into()))?) } /// Send a raw query and receive a response future. pub fn send_raw_query<F>(&self, msg_from_id: F) -> RawQueryResponseFut where F: for<'a, 'b> FnOnce(Txid, &'a mut Vec<u8>, &'b mut Vec<Handle>) -> Result<(), Error>, { let id = self.inner.register_msg_interest(); let res = crate::encoding::with_tls_coding_bufs(|bytes, handles| { msg_from_id(Txid::from_interest_id(id), bytes, handles)?; self.inner.channel.write(bytes, handles).map_err(|e| Error::ClientWrite(e.into()))?; Ok::<(), Error>(()) }); match res { Ok(()) => { MessageResponse { id: Txid::from_interest_id(id), client: Some(self.inner.clone()) } .right_future() } Err(e) => futures::future::ready(Err(e)).left_future(), } } } #[must_use] /// A future which polls for the response to a client message. #[derive(Debug)] pub struct MessageResponse { id: Txid, // `None` if the message response has been recieved client: Option<Arc<ClientInner>>, } impl Unpin for MessageResponse {} impl Future for MessageResponse { type Output = Result<MessageBuf, Error>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = &mut *self; let res; { let client = this.client.as_ref().ok_or(Error::PollAfterCompletion)?; res = client.poll_recv_msg_response(this.id, cx); } // Drop the client reference if the response has been received if let Poll::Ready(Ok(_)) = res { let client = this.client.take().expect("MessageResponse polled after completion"); client.wake_any(); } res } } impl Drop for MessageResponse { fn drop(&mut self) { if let Some(client) = &self.client { client.deregister_msg_interest(InterestId::from_txid(self.id)); client.wake_any(); } } } /// An enum reprenting either a resolved message interest or a task on which to alert /// that a response message has arrived. #[derive(Debug)] enum MessageInterest { /// A new `MessageInterest` WillPoll, /// A task is waiting to receive a response, and can be awoken with `Waker`. Waiting(Waker), /// A message has been received, and a task will poll to receive it. Received(MessageBuf), /// A message has not been received, but the person interested in the response /// no longer cares about it, so the message should be discared upon arrival. Discard, } impl MessageInterest { /// Check if a message has been received. fn is_received(&self) -> bool { if let MessageInterest::Received(_) = *self { true } else { false } } fn unwrap_received(self) -> MessageBuf { if let MessageInterest::Received(buf) = self { buf } else { panic!("EXPECTED received message") } } } /// A stream of events as `MessageBuf`s. #[derive(Debug)] pub struct EventReceiver { inner: Arc<ClientInner>, terminated: bool, } impl Unpin for EventReceiver {} impl FusedStream for EventReceiver { fn is_terminated(&self) -> bool { self.terminated } } /// This implementation holds up two invariants /// (1) After `None` is returned, the next poll panics /// (2) Until this instance is dropped, no other EventReceiver may claim the /// event channel by calling Client::take_event_receiver. impl Stream for EventReceiver { type Item = Result<MessageBuf, Error>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { if self.is_terminated() { panic!("polled EventReceiver after `None`"); } Poll::Ready(match ready!(self.inner.as_ref().poll_recv_event(cx)) { Ok(x) => Some(Ok(x)), Err(Error::ClientChannelClosed(_)) => { // The channel is closed, set our internal state so that on the // next poll_next() we panic and is_terminated() returns an // appropriate value. self.terminated = true; None } Err(e) => Some(Err(e)), }) } } impl Drop for EventReceiver { fn drop(&mut self) { self.inner.event_channel.lock().listener = EventListener::None; self.inner.wake_any(); } } #[derive(Debug, Default)] struct EventChannel { listener: EventListener, queue: VecDeque<MessageBuf>, } #[derive(Debug)] enum EventListener { /// No one is listening for the event None, /// Someone is listening for the event but has not yet polled WillPoll, /// Someone is listening for the event and can be woken via the `Waker` Some(Waker), } impl Default for EventListener { fn default() -> Self { EventListener::None } } /// A shared client channel which tracks EXPECTED and received responses #[derive(Debug)] struct ClientInner { channel: AsyncChannel, /// A map of message interests to either `None` (no message received yet) /// or `Some(DecodeBuf)` when a message has been received. /// An interest is registered with `register_msg_interest` and deregistered /// by either receiving a message via a call to `poll_recv` or manually /// deregistering with `deregister_msg_interest` message_interests: Mutex<Slab<MessageInterest>>, /// A queue of received events and a waker for the task to receive them. event_channel: Mutex<EventChannel>, /// The server provided epitaph, or None if the channel is not closed. epitaph: Mutex<Option<zx_status::Status>>, } impl Deref for Client { type Target = AsyncChannel; fn deref(&self) -> &Self::Target { &self.inner.channel } } impl ClientInner { /// Registers interest in a response message. /// /// This function returns a `usize` ID which should be used to send a message /// via the channel. Responses are then received using `poll_recv`. fn register_msg_interest(&self) -> InterestId { // TODO(cramertj) use `try_from` here and assert that the conversion from // `usize` to `u32` hasn't overflowed. InterestId(self.message_interests.lock().insert(MessageInterest::WillPoll)) } fn poll_recv_event(&self, cx: &mut Context<'_>) -> Poll<Result<MessageBuf, Error>> { { // Update the EventListener with the latest waker, remove any stale WillPoll state let mut lock = self.event_channel.lock(); lock.listener = EventListener::Some(cx.waker().clone()); } let epitaph = self.recv_all()?; let mut lock = self.event_channel.lock(); if let Some(msg_buf) = lock.queue.pop_front() { Poll::Ready(Ok(msg_buf)) } else { if let Some(status) = epitaph { Poll::Ready(Err(Error::ClientChannelClosed(status))) } else { Poll::Pending } } } fn poll_recv_msg_response( &self, txid: Txid, cx: &mut Context<'_>, ) -> Poll<Result<MessageBuf, Error>> { let interest_id = InterestId::from_txid(txid); { // If have not yet received anything, update any stale WillPoll or Waiting(stale waker) // message interest for the current message. let mut message_interests = self.message_interests.lock(); let message_interest = message_interests .get_mut(interest_id.as_raw_id()) .expect("Polled unregistered interest"); if !message_interest.is_received() { *message_interest = MessageInterest::Waiting(cx.waker().clone()); } } let epitaph = self.recv_all()?; let mut message_interests = self.message_interests.lock(); if message_interests .get(interest_id.as_raw_id()) .expect("Polled unregistered interest") .is_received() { // If, by happy accident, we just raced to getting the result, // then yay! Return success. let buf = message_interests.remove(interest_id.as_raw_id()).unwrap_received(); Poll::Ready(Ok(buf)) } else { if let Some(status) = epitaph { Poll::Ready(Err(Error::ClientChannelClosed(status))) } else { Poll::Pending } } } /// Poll for the receipt of any response message or an event. /// /// Returns whether or not the channel is closed. fn recv_all(&self) -> Result<Option<zx_status::Status>, Error> { // TODO(cramertj) return errors if one has occured _ever_ in recv_all, not just if // one happens on this call. loop { // Acquire a mutex so that only one thread can read from the underlying channel // at a time. Channel is already synchronized, but we need to also decode the // FIDL message header atomically so that epitaphs can be properly handled. let mut epitaph_lock = self.epitaph.lock(); if epitaph_lock.is_some() { return Ok(*epitaph_lock); } let buf = { let waker = match self.get_pending_waker() { Some(v) => v, None => return Ok(None), }; let cx = &mut Context::from_waker(&waker); let mut buf = MessageBuf::new(); let result = self.channel.recv_from(cx, &mut buf); match result { Poll::Ready(Ok(())) => {} Poll::Ready(Err(zx_status::Status::PEER_CLOSED)) => { // The channel has been closed, and no epitaph was received. Set the epitaph to PEER_CLOSED. *epitaph_lock = Some(zx_status::Status::PEER_CLOSED); // The task that calls this method also has its Waker woken. This could be // optimized by excluding this task, but since this occurs on channel close, // it is not a critical optimization. self.wake_all(); return Ok(*epitaph_lock); } Poll::Ready(Err(e)) => return Err(Error::ClientRead(e)), Poll::Pending => { return Ok(None); } }; buf }; let (header, body_bytes) = decode_transaction_header(buf.bytes()).map_err(|_| Error::InvalidHeader)?; if !header.is_compatible() { return Err(Error::IncompatibleMagicNumber(header.magic_number())); } if header.is_epitaph() { // Received an epitaph. Record this so that future operations receive the same // epitaph. let handles = &mut []; let mut epitaph_body = EpitaphBody::new_empty(); Decoder::decode_into(&header, &body_bytes, handles, &mut epitaph_body)?; *epitaph_lock = Some(epitaph_body.error); // The task that calls this method also has its Waker woken. This could be // optimized by excluding this task, but since this occurs on channel close, // it is not a critical optimization. self.wake_all(); return Ok(*epitaph_lock); } // Epitaph handling is done, so the lock is no longer required. drop(epitaph_lock); if header.tx_id() == 0 { // received an event let mut lock = self.event_channel.lock(); lock.queue.push_back(buf); if let EventListener::Some(_) = lock.listener { if let EventListener::Some(waker) = mem::replace(&mut lock.listener, EventListener::WillPoll) { waker.wake(); } } } else { // received a message response let recvd_interest_id = InterestId::from_txid(Txid(header.tx_id())); // Look for a message interest with the given ID. // If one is found, store the message so that it can be picked up later. let mut message_interests = self.message_interests.lock(); let raw_recvd_interest_id = recvd_interest_id.as_raw_id(); if let Some(&MessageInterest::Discard) = message_interests.get(raw_recvd_interest_id) { message_interests.remove(raw_recvd_interest_id); } else if let Some(entry) = message_interests.get_mut(raw_recvd_interest_id) { let old_entry = mem::replace(entry, MessageInterest::Received(buf)); if let MessageInterest::Waiting(waker) = old_entry { // Wake up the task to let them know a message has arrived. waker.wake(); } } } } } fn deregister_msg_interest(&self, InterestId(id): InterestId) { let mut lock = self.message_interests.lock(); if lock[id].is_received() { lock.remove(id); } else { lock[id] = MessageInterest::Discard; } } /// Gets an arbitrary task that has polled on this channel and has not yet /// gotten a response. fn get_pending_waker(&self) -> Option<Waker> { { let lock = self.message_interests.lock(); for (_, message_interest) in lock.iter() { if let MessageInterest::Waiting(waker) = message_interest { return Some(waker.clone()); } } } { let lock = self.event_channel.lock(); if let EventListener::Some(waker) = &lock.listener { return Some(waker.clone()); } } None } /// Wakes up an arbitrary task that has begun polling on the channel so that /// it will call recv_all. fn wake_any(&self) { if let Some(waker) = self.get_pending_waker() { waker.wake(); } } /// Wakes all tasks that have polled on this channel. fn wake_all(&self) { { let mut lock = self.message_interests.lock(); for (_, message_interest) in lock.iter_mut() { // Only wake and replace the tasks that have polled and have Wakers. // Otherwise a task has received a response would have that buffer // overridden. if let MessageInterest::Waiting(_) = message_interest { if let MessageInterest::Waiting(waker) = mem::replace(message_interest, MessageInterest::WillPoll) { waker.wake(); } } } } { let lock = self.event_channel.lock(); if let EventListener::Some(waker) = &lock.listener { waker.wake_by_ref(); } } } } #[cfg(target_os = "fuchsia")] pub mod sync { //! Synchronous FIDL Client use fuchsia_zircon as zx; use super::*; /// A synchronous client for making FIDL calls. #[derive(Debug)] pub struct Client { // Underlying channel channel: zx::Channel, // Reusable buffer for r/w buf: zx::MessageBuf, } // TODO: remove this and allow multiple overlapping queries on the same channel. pub(super) const QUERY_TX_ID: u32 = 42; impl Client { /// Create a new synchronous FIDL client. pub fn new(channel: zx::Channel) -> Self { Client { channel, buf: zx::MessageBuf::new() } } /// Get the underlying channel out of the client. pub fn into_channel(self) -> zx::Channel { self.channel } /// Send a new message. pub fn send<E: Encodable>(&mut self, msg: &mut E, ordinal: u64) -> Result<(), Error> { self.buf.clear(); let (buf, handles) = self.buf.split_mut(); let msg = &mut TransactionMessage { header: TransactionHeader::new(0, ordinal), body: msg }; Encoder::encode(buf, handles, msg)?; self.channel.write(buf, handles).map_err(|e| Error::ClientWrite(e.into()))?; Ok(()) } /// Send a new message expecting a response. pub fn send_query<E: Encodable, D: Decodable>( &mut self, msg: &mut E, ordinal: u64, deadline: zx::Time, ) -> Result<D, Error> { // Write the message into the channel self.buf.clear(); let (buf, handles) = self.buf.split_mut(); let msg = &mut TransactionMessage { header: TransactionHeader::new(QUERY_TX_ID, ordinal), body: msg, }; Encoder::encode(buf, handles, msg)?; self.channel.write(buf, handles).map_err(|e| Error::ClientWrite(e.into()))?; // Read the response self.buf.clear(); match self.channel.read(&mut self.buf) { Ok(()) => {} Err(zx_status::Status::SHOULD_WAIT) => { let signals = self .channel .wait_handle( zx::Signals::CHANNEL_READABLE | zx::Signals::CHANNEL_PEER_CLOSED, deadline, ) .map_err(|e| Error::ClientRead(e.into()))?; if !signals.contains(zx::Signals::CHANNEL_READABLE) { debug_assert!(signals.contains(zx::Signals::CHANNEL_PEER_CLOSED)); return Err(Error::ClientRead(zx_status::Status::PEER_CLOSED)); } self.channel.read(&mut self.buf).map_err(|e| Error::ClientRead(e.into()))?; } Err(e) => return Err(Error::ClientRead(e.into())), } let (buf, handles) = self.buf.split_mut(); let (header, body_bytes) = decode_transaction_header(buf)?; // TODO(fxb/7848): Check received ordinal against sent ordinal. For // the migration, we disable this check and rely only on the tx_id // since the ordinal sent may not be the ordinal received. if header.tx_id() != QUERY_TX_ID { return Err(Error::UnexpectedSyncResponse); } let mut output = D::new_empty(); Decoder::decode_into(&header, body_bytes, handles, &mut output)?; Ok(output) } } } #[cfg(all(test, target_os = "fuchsia"))] mod tests { use super::*; use { crate::encoding::MAGIC_NUMBER_INITIAL, crate::epitaph::{self, ChannelEpitaphExt}, failure::{Error, ResultExt}, fuchsia_async as fasync, fuchsia_async::{DurationExt, TimeoutExt}, fuchsia_zircon as zx, fuchsia_zircon::DurationNum, futures::{join, FutureExt, StreamExt}, futures_test::task::new_count_waker, std::thread, test_util::assert_matches, }; const SEND_ORDINAL_HIGH_BYTE: u8 = 42; const SEND_ORDINAL: u64 = 42 << 32; const SEND_DATA: u8 = 55; #[rustfmt::skip] fn expected_sent_bytes(tx_id_low_byte: u8) -> [u8; 24] { [ tx_id_low_byte, 0, 0, 0, // 32 bit tx_id 1, 0, 0, // flags (unions encoded as xunions) MAGIC_NUMBER_INITIAL, 0, 0, 0, 0, // low bytes of 64 bit ordinal SEND_ORDINAL_HIGH_BYTE, 0, 0, 0, // high bytes of 64 bit ordinal SEND_DATA, // 8 bit data 0, 0, 0, 0, 0, 0, 0, // 7 bytes of padding after our 1 byte of data ] } fn send_transaction(header: TransactionHeader, channel: &zx::Channel) { let (bytes, handles) = (&mut vec![], &mut vec![]); encode_transaction(header, bytes, handles); channel.write(bytes, handles).expect("Server channel write failed"); } fn encode_transaction( header: TransactionHeader, bytes: &mut Vec<u8>, handles: &mut Vec<zx::Handle>, ) { let event = &mut TransactionMessage { header: header, body: &mut SEND_DATA }; Encoder::encode(bytes, handles, event).expect("Encoding failure"); } #[test] fn sync_client() -> Result<(), Error> { let (client_end, server_end) = zx::Channel::create().context("chan create")?; let mut client = sync::Client::new(client_end); client.send(&mut SEND_DATA, SEND_ORDINAL).context("sending")?; let mut received = MessageBuf::new(); server_end.read(&mut received).context("reading")?; let one_way_tx_id = 0; assert_eq!(received.bytes(), expected_sent_bytes(one_way_tx_id)); Ok(()) } #[test] fn sync_client_with_response() -> Result<(), Error> { let (client_end, server_end) = zx::Channel::create().context("chan create")?; let mut client = sync::Client::new(client_end); thread::spawn(move || { // Server let mut received = MessageBuf::new(); server_end .wait_handle(zx::Signals::CHANNEL_READABLE, zx::Time::after(5.seconds())) .expect("failed to wait for channel readable"); server_end.read(&mut received).expect("failed to read on server end"); let (buf, _handles) = received.split_mut(); let (header, _body_bytes) = decode_transaction_header(buf).expect("server decode"); assert_eq!(header.tx_id(), sync::QUERY_TX_ID); assert_eq!(header.ordinal(), SEND_ORDINAL); send_transaction(TransactionHeader::new(header.tx_id(), header.ordinal()), &server_end); }); let response_data = client .send_query::<u8, u8>(&mut SEND_DATA, SEND_ORDINAL, zx::Time::after(5.seconds())) .context("sending query")?; assert_eq!(SEND_DATA, response_data); Ok(()) } #[fasync::run_singlethreaded(test)] async fn client() { let (client_end, server_end) = zx::Channel::create().unwrap(); let client_end = AsyncChannel::from_channel(client_end).unwrap(); let client = Client::new(client_end); let server = AsyncChannel::from_channel(server_end).unwrap(); let receiver = async move { let mut buffer = MessageBuf::new(); server.recv_msg(&mut buffer).await.expect("failed to recv msg"); let one_way_tx_id = 0; assert_eq!(buffer.bytes(), expected_sent_bytes(one_way_tx_id)); }; // add a timeout to receiver so if test is broken it doesn't take forever let receiver = receiver .on_timeout(300.millis().after_now(), || panic!("did not receive message in time!")); let sender = fasync::Timer::new(100.millis().after_now()).map(|()| { client.send(&mut SEND_DATA, SEND_ORDINAL).expect("failed to send msg"); }); join!(receiver, sender); } #[fasync::run_singlethreaded(test)] async fn client_with_response() { let (client_end, server_end) = zx::Channel::create().unwrap(); let client_end = AsyncChannel::from_channel(client_end).unwrap(); let client = Client::new(client_end); let server = AsyncChannel::from_channel(server_end).unwrap(); let mut buffer = MessageBuf::new(); let receiver = async move { server.recv_msg(&mut buffer).await.expect("failed to recv msg"); let two_way_tx_id = 1u8; assert_eq!(buffer.bytes(), expected_sent_bytes(two_way_tx_id)); let (bytes, handles) = (&mut vec![], &mut vec![]); let header = TransactionHeader::new(two_way_tx_id as u32, 42); encode_transaction(header, bytes, handles); server.write(bytes, handles).expect("Server channel write failed"); }; // add a timeout to receiver so if test is broken it doesn't take forever let receiver = receiver .on_timeout(300.millis().after_now(), || panic!("did not receiver message in time!")); let sender = client .send_query::<u8, u8>(&mut SEND_DATA, SEND_ORDINAL) .map_ok(|x| assert_eq!(x, SEND_DATA)) .unwrap_or_else(|e| panic!("fidl error: {:?}", e)); // add a timeout to receiver so if test is broken it doesn't take forever let sender = sender .on_timeout(300.millis().after_now(), || panic!("did not receive response in time!")); let ((), ()) = join!(receiver, sender); } #[fasync::run_singlethreaded(test)] async fn client_with_response_receives_epitaph() { let (client_end, server_end) = zx::Channel::create().unwrap(); let client_end = fasync::Channel::from_channel(client_end).unwrap(); let client = Client::new(client_end); let server = fasync::Channel::from_channel(server_end).unwrap(); let mut buffer = zx::MessageBuf::new(); let receiver = async move { server.recv_msg(&mut buffer).await.expect("failed to recv msg"); server .close_with_epitaph(zx_status::Status::UNAVAILABLE) .expect("failed to write epitaph"); }; // add a timeout to receiver so if test is broken it doesn't take forever let receiver = receiver .on_timeout(300.millis().after_now(), || panic!("did not receive message in time!")); let sender = async move { let result = client.send_query::<u8, u8>(&mut 55, 42 << 32).await; assert_matches!( result, Err(crate::Error::ClientChannelClosed(zx_status::Status::UNAVAILABLE)) ); }; // add a timeout to sender so if test is broken it doesn't take forever let sender = sender .on_timeout(300.millis().after_now(), || panic!("did not receive response in time!")); let ((), ()) = join!(receiver, sender); } #[fasync::run_singlethreaded(test)] #[should_panic] async fn event_cant_be_taken_twice() { let (client_end, _) = zx::Channel::create().unwrap(); let client_end = AsyncChannel::from_channel(client_end).unwrap(); let client = Client::new(client_end); let _foo = client.take_event_receiver(); client.take_event_receiver(); } #[fasync::run_singlethreaded(test)] async fn event_can_be_taken_after_drop() { let (client_end, _) = zx::Channel::create().unwrap(); let client_end = AsyncChannel::from_channel(client_end).unwrap(); let client = Client::new(client_end); let foo = client.take_event_receiver(); drop(foo); client.take_event_receiver(); } #[fasync::run_singlethreaded(test)] async fn receiver_termination_test() { let (client_end, _) = zx::Channel::create().unwrap(); let client_end = AsyncChannel::from_channel(client_end).unwrap(); let client = Client::new(client_end); let mut foo = client.take_event_receiver(); assert!(!foo.is_terminated(), "receiver should not report terminated before being polled"); let _ = foo.next().await; assert!( foo.is_terminated(), "receiver should report terminated after seeing channel is closed" ); } #[fasync::run_singlethreaded(test)] #[should_panic(expected = "polled EventReceiver after `None`")] async fn receiver_cant_be_polled_more_than_once_on_closed_stream() { let (client_end, _) = zx::Channel::create().unwrap(); let client_end = AsyncChannel::from_channel(client_end).unwrap(); let client = Client::new(client_end); let foo = client.take_event_receiver(); drop(foo); let mut bar = client.take_event_receiver(); assert!(bar.next().await.is_none(), "read on closed channel should return none"); // this should panic let _ = bar.next().await; } #[fasync::run_singlethreaded(test)] async fn event_can_be_taken() { let (client_end, _) = zx::Channel::create().unwrap(); let client_end = AsyncChannel::from_channel(client_end).unwrap(); let client = Client::new(client_end); client.take_event_receiver(); } #[fasync::run_singlethreaded(test)] async fn event_received() { let (client_end, server_end) = zx::Channel::create().unwrap(); let client_end = AsyncChannel::from_channel(client_end).unwrap(); let client = Client::new(client_end); // Send the event from the server let server = AsyncChannel::from_channel(server_end).unwrap(); let (bytes, handles) = (&mut vec![], &mut vec![]); let header = TransactionHeader::new(0, 5); encode_transaction(header, bytes, handles); server.write(bytes, handles).expect("Server channel write failed"); drop(server); let recv = client .take_event_receiver() .into_future() .then(|(x, stream)| { let x = x.expect("should contain one element"); let x = x.expect("fidl error"); let x: i32 = decode_transaction_body(x).expect("failed to decode event"); assert_eq!(x, 55); stream.into_future() }) .map(|(x, _stream)| assert!(x.is_none(), "should have emptied")); // add a timeout to receiver so if test is broken it doesn't take forever let recv = recv.on_timeout(300.millis().after_now(), || panic!("did not receive event in time!")); recv.await; } /// Tests that the event receiver can be taken, the stream read to the end, /// the receiver dropped, and then a new receiver gotten from taking the /// stream again. #[fasync::run_singlethreaded(test)] async fn receiver_can_be_taken_after_end_of_stream() { let (client_end, server_end) = zx::Channel::create().unwrap(); let client_end = AsyncChannel::from_channel(client_end).unwrap(); let client = Client::new(client_end); // Send the event from the server let server = AsyncChannel::from_channel(server_end).unwrap(); let (bytes, handles) = (&mut vec![], &mut vec![]); let header = TransactionHeader::new(0, 5); encode_transaction(header, bytes, handles); server.write(bytes, handles).expect("Server channel write failed"); drop(server); // Create a block to make sure the first event receiver is dropped. // Creating the block is a bit of paranoia, because awaiting the // future moves the receiver anyway. { let recv = client .take_event_receiver() .into_future() .then(|(x, stream)| { let x = x.expect("should contain one element"); let x = x.expect("fidl error"); let x: i32 = decode_transaction_body(x).expect("failed to decode event"); assert_eq!(x, 55); stream.into_future() }) .map(|(x, _stream)| assert!(x.is_none(), "should have emptied")); // add a timeout to receiver so if test is broken it doesn't take forever let recv = recv .on_timeout(300.millis().after_now(), || panic!("did not receive event in time!")); recv.await; } // if we take the event stream again, we should be able to get the next // without a panic, but that should be none let mut c = client.take_event_receiver(); assert!( c.next().await.is_none(), "receiver on closed channel should return none on first call" ); } #[fasync::run_singlethreaded(test)] async fn event_incompatible_format() { let (client_end, server_end) = zx::Channel::create().unwrap(); let client_end = fasync::Channel::from_channel(client_end).unwrap(); let client = Client::new(client_end); // Send the event from the server let server = fasync::Channel::from_channel(server_end).unwrap(); let (bytes, handles) = (&mut vec![], &mut vec![]); let header = TransactionHeader::new_full(0, 5, &crate::encoding::Context {}, 0); encode_transaction(header, bytes, handles); server.write(bytes, handles).expect("Server channel write failed"); drop(server); let mut event_receiver = client.take_event_receiver(); let recv = event_receiver.next().map(|event| { assert_matches!(event, Some(Err(crate::Error::IncompatibleMagicNumber(0)))) }); // add a timeout to receiver so if test is broken it doesn't take forever let recv = recv.on_timeout(300.millis().after_now(), || panic!("did not receive event in time!")); recv.await; } #[fasync::run_singlethreaded(test)] async fn polling_event_receives_epitaph() { let (client_end, server_end) = zx::Channel::create().unwrap(); let client_end = fasync::Channel::from_channel(client_end).unwrap(); let client = Client::new(client_end); // Send the epitaph from the server let server = fasync::Channel::from_channel(server_end).unwrap(); server.close_with_epitaph(zx_status::Status::UNAVAILABLE).expect("failed to write epitaph"); let mut event_receiver = client.take_event_receiver(); let recv = event_receiver.next().map(|x| assert!(x.is_none(), "should be None")); // add a timeout to receiver so if test is broken it doesn't take forever let recv = recv.on_timeout(300.millis().after_now(), || panic!("did not receive event in time!")); recv.await; } #[test] fn client_always_wakes_pending_futures() { let mut executor = fasync::Executor::new().unwrap(); let (client_end, server_end) = zx::Channel::create().unwrap(); let client_end = AsyncChannel::from_channel(client_end).unwrap(); let client = Client::new(client_end); let mut event_receiver = client.take_event_receiver(); // first poll on a response let (response_waker, response_waker_count) = new_count_waker(); let response_cx = &mut Context::from_waker(&response_waker); let mut response_txid = Txid(0); let mut response_future = client.send_raw_query(|tx_id, bytes, handles| { response_txid = tx_id; let header = TransactionHeader::new(response_txid.as_raw_id(), 42); encode_transaction(header, bytes, handles); Ok(()) }); assert!(response_future.poll_unpin(response_cx).is_pending()); // then, poll on an event let (event_waker, event_waker_count) = new_count_waker(); let event_cx = &mut Context::from_waker(&event_waker); assert!(event_receiver.poll_next_unpin(event_cx).is_pending()); // at this point, nothing should have been woken assert_eq!(response_waker_count.get(), 0); assert_eq!(event_waker_count.get(), 0); // next, simulate an event coming in send_transaction(TransactionHeader::new(0, 5), &server_end); // get event loop to deliver readiness notifications to channels let _ = executor.run_until_stalled(&mut future::pending::<()>()); // either response_waker or event_waker should be woken assert_eq!(response_waker_count.get() + event_waker_count.get(), 1); let last_response_waker_count = response_waker_count.get(); // we'll pretend event_waker was woken, and have that poll out the event assert!(event_receiver.poll_next_unpin(event_cx).is_ready()); // next, simulate a response coming in send_transaction(TransactionHeader::new(response_txid.as_raw_id(), 42), &server_end); // get event loop to deliver readiness notifications to channels let _ = executor.run_until_stalled(&mut future::pending::<()>()); // response waker should have been woken again assert_eq!(response_waker_count.get(), last_response_waker_count + 1); } #[test] fn client_always_wakes_pending_futures_on_epitaph() { let mut executor = fasync::Executor::new().unwrap(); let (client_end, server_end) = zx::Channel::create().unwrap(); let client_end = fasync::Channel::from_channel(client_end).unwrap(); let client = Client::new(client_end); let mut event_receiver = client.take_event_receiver(); // first poll on a response let (response1_waker, response1_waker_count) = new_count_waker(); let response1_cx = &mut Context::from_waker(&response1_waker); let mut response1_future = client.send_raw_query(|tx_id, bytes, handles| { let header = TransactionHeader::new(tx_id.as_raw_id(), 42); encode_transaction(header, bytes, handles); Ok(()) }); assert!(response1_future.poll_unpin(response1_cx).is_pending()); // then, poll on an event let (event_waker, event_waker_count) = new_count_waker(); let event_cx = &mut Context::from_waker(&event_waker); assert!(event_receiver.poll_next_unpin(event_cx).is_pending()); // poll on another response let (response2_waker, response2_waker_count) = new_count_waker(); let response2_cx = &mut Context::from_waker(&response2_waker); let mut response2_future = client.send_raw_query(|tx_id, bytes, handles| { let header = TransactionHeader::new(tx_id.as_raw_id(), 42); encode_transaction(header, bytes, handles); Ok(()) }); assert!(response2_future.poll_unpin(response2_cx).is_pending()); let wakers = vec![response1_waker_count, response2_waker_count, event_waker_count]; // get event loop to deliver readiness notifications to channels let _ = executor.run_until_stalled(&mut future::pending::<()>()); // at this point, nothing should have been woken assert_eq!(0, wakers.iter().fold(0, |acc, x| acc + x.get())); // next, simulate an epitaph without closing epitaph::write_epitaph_impl(&server_end, zx_status::Status::UNAVAILABLE) .expect("wrote epitaph"); // get event loop to deliver readiness notifications to channels let _ = executor.run_until_stalled(&mut future::pending::<()>()); // one waker should have woken up, since reading from a channel only supports // a single waker. assert_eq!(1, wakers.iter().fold(0, |acc, x| acc + x.get())); // pretend that response1 woke and poll that to completion. assert_matches!( response1_future.poll_unpin(response1_cx), Poll::Ready(Err(crate::Error::ClientChannelClosed(zx_status::Status::UNAVAILABLE))) ); // get event loop to deliver readiness notifications to channels let _ = executor.run_until_stalled(&mut future::pending::<()>()); // response1 will have woken all other tasks again. // NOTE: The task that is waking all other tasks is also woken. assert_eq!(1 + wakers.len(), wakers.iter().fold(0, |acc, x| acc + x.get())); // poll response2 to completion. assert_matches!( response2_future.poll_unpin(response2_cx), Poll::Ready(Err(crate::Error::ClientChannelClosed(zx_status::Status::UNAVAILABLE))) ); // poll the event stream to completion. assert!(event_receiver.poll_next_unpin(event_cx).is_ready()); } #[fasync::run_singlethreaded(test)] async fn client_allows_take_event_stream_even_if_event_delivered() { let (client_end, server_end) = zx::Channel::create().unwrap(); let client_end = AsyncChannel::from_channel(client_end).unwrap(); let client = Client::new(client_end); // first simulate an event coming in, even though nothing has polled send_transaction(TransactionHeader::new(0, 5), &server_end); // next, poll on a response let (response_waker, _response_waker_count) = new_count_waker(); let response_cx = &mut Context::from_waker(&response_waker); let mut response_future = client.send_query::<u8, u8>(&mut 55, 42); assert!(response_future.poll_unpin(response_cx).is_pending()); // then, make sure we can still take the event receiver without panicking let mut _event_receiver = client.take_event_receiver(); } }
38.89658
116
0.592405
eb24463a0cb1fe0749601c7f844e564cb5c9bdf7
90
mod utils; pub use utils::create_box_geometry; mod geometry; pub use geometry::Geometry;
15
35
0.788889
28cd8e74c9c2015d0c713b84e5aab2a216be76a1
24,303
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 // Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 //! The following is a slightly modified version of the file with the same name in the //! rust-wallet crate. The original file may be found here: //! //! https://github.com/rust-bitcoin/rust-wallet/blob/master/wallet/src/mnemonic.rs use crate::error::*; use crypto::{digest::Digest, sha2::Sha256}; #[cfg(test)] use rand::rngs::EntropyRng; #[cfg(test)] use rand_core::RngCore; use std::{ fs::{self, File}, io::Write, path::Path, }; #[cfg(test)] use tempfile::NamedTempFile; /// Mnemonic seed for deterministic key derivation pub struct Mnemonic(Vec<&'static str>); impl ToString for Mnemonic { fn to_string(&self) -> String { self.0.as_slice().join(" ") } } impl Mnemonic { /// Generate mnemonic from string pub fn from(s: &str) -> Result<Mnemonic> { let words: Vec<_> = s.split(' ').collect(); if words.len() < 6 || words.len() % 6 != 0 { return Err(WalletError::LibraWalletGeneric( "Mnemonic must have a word count divisible with 6".to_string(), )); } let mut mnemonic = Vec::new(); for word in &words { if let Ok(idx) = WORDS.binary_search(word) { mnemonic.push(WORDS[idx]); } else { return Err(WalletError::LibraWalletGeneric( "Mnemonic contains an unknown word".to_string(), )); } } Ok(Mnemonic(mnemonic)) } /// Generate mnemonic from byte-array pub fn mnemonic(data: &[u8]) -> Result<Mnemonic> { if data.len() % 4 != 0 { return Err(WalletError::LibraWalletGeneric( "Data for mnemonic should have a length divisible by 4".to_string(), )); } let mut check = [0u8; 32]; let mut sha2 = Sha256::new(); sha2.input(data); sha2.result(&mut check); let mut bits = vec![false; data.len() * 8 + data.len() / 4]; for i in 0..data.len() { for j in 0..8 { bits[i * 8 + j] = (data[i] & (1 << (7 - j))) > 0; } } for i in 0..data.len() / 4 { bits[8 * data.len() + i] = (check[i / 8] & (1 << (7 - (i % 8)))) > 0; } let mlen = data.len() * 3 / 4; let mut memo = Vec::new(); for i in 0..mlen { let mut idx = 0; for j in 0..11 { if bits[i * 11 + j] { idx += 1 << (10 - j); } } memo.push(WORDS[idx]); } Ok(Mnemonic(memo)) } /// Write mnemonic to output_file_path pub fn write(&self, output_file_path: &Path) -> Result<()> { if output_file_path.exists() && !output_file_path.is_file() { return Err(WalletError::LibraWalletGeneric(format!( "Output file {:?} for mnemonic backup is reserved", output_file_path.to_str(), ))); } let mut file = File::create(output_file_path)?; file.write_all(&self.to_string().as_bytes())?; Ok(()) } /// Read mnemonic from input_file_path pub fn read(input_file_path: &Path) -> Result<Self> { if input_file_path.exists() && input_file_path.is_file() { let mnemonic_string: String = fs::read_to_string(input_file_path)?; return Self::from(&mnemonic_string[..]); } Err(WalletError::LibraWalletGeneric( "Input file for mnemonic backup does not exist".to_string(), )) } } #[test] fn test_roundtrip_mnemonic() { let mut rng = EntropyRng::new(); let mut buf = [0u8; 32]; rng.fill_bytes(&mut buf[..]); let file = NamedTempFile::new().unwrap(); let path = file.into_temp_path(); let mnemonic = Mnemonic::mnemonic(&buf[..]).unwrap(); mnemonic.write(&path).unwrap(); let other_mnemonic = Mnemonic::read(&path).unwrap(); assert_eq!(mnemonic.to_string(), other_mnemonic.to_string()); } const WORDS: [&str; 2048] = [ "abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract", "absurd", "abuse", "access", "accident", "account", "accuse", "achieve", "acid", "acoustic", "acquire", "across", "act", "action", "actor", "actress", "actual", "adapt", "add", "addict", "address", "adjust", "admit", "adult", "advance", "advice", "aerobic", "affair", "afford", "afraid", "again", "age", "agent", "agree", "ahead", "aim", "air", "airport", "aisle", "alarm", "album", "alcohol", "alert", "alien", "all", "alley", "allow", "almost", "alone", "alpha", "already", "also", "alter", "always", "amateur", "amazing", "among", "amount", "amused", "analyst", "anchor", "ancient", "anger", "angle", "angry", "animal", "ankle", "announce", "annual", "another", "answer", "antenna", "antique", "anxiety", "any", "apart", "apology", "appear", "apple", "approve", "april", "arch", "arctic", "area", "arena", "argue", "arm", "armed", "armor", "army", "around", "arrange", "arrest", "arrive", "arrow", "art", "artefact", "artist", "artwork", "ask", "aspect", "assault", "asset", "assist", "assume", "asthma", "athlete", "atom", "attack", "attend", "attitude", "attract", "auction", "audit", "august", "aunt", "author", "auto", "autumn", "average", "avocado", "avoid", "awake", "aware", "away", "awesome", "awful", "awkward", "axis", "baby", "bachelor", "bacon", "badge", "bag", "balance", "balcony", "ball", "bamboo", "banana", "banner", "bar", "barely", "bargain", "barrel", "base", "basic", "basket", "battle", "beach", "bean", "beauty", "because", "become", "beef", "before", "begin", "behave", "behind", "believe", "below", "belt", "bench", "benefit", "best", "betray", "better", "between", "beyond", "bicycle", "bid", "bike", "bind", "biology", "bird", "birth", "bitter", "black", "blade", "blame", "blanket", "blast", "bleak", "bless", "blind", "blood", "blossom", "blouse", "blue", "blur", "blush", "board", "boat", "body", "boil", "bomb", "bone", "bonus", "book", "boost", "border", "boring", "borrow", "boss", "bottom", "bounce", "box", "boy", "bracket", "brain", "brand", "brass", "brave", "bread", "breeze", "brick", "bridge", "brief", "bright", "bring", "brisk", "broccoli", "broken", "bronze", "broom", "brother", "brown", "brush", "bubble", "buddy", "budget", "buffalo", "build", "bulb", "bulk", "bullet", "bundle", "bunker", "burden", "burger", "burst", "bus", "business", "busy", "butter", "buyer", "buzz", "cabbage", "cabin", "cable", "cactus", "cage", "cake", "call", "calm", "camera", "camp", "can", "canal", "cancel", "candy", "cannon", "canoe", "canvas", "canyon", "capable", "capital", "captain", "car", "carbon", "card", "cargo", "carpet", "carry", "cart", "case", "cash", "casino", "castle", "casual", "cat", "catalog", "catch", "category", "cattle", "caught", "cause", "caution", "cave", "ceiling", "celery", "cement", "census", "century", "cereal", "certain", "chair", "chalk", "champion", "change", "chaos", "chapter", "charge", "chase", "chat", "cheap", "check", "cheese", "chef", "cherry", "chest", "chicken", "chief", "child", "chimney", "choice", "choose", "chronic", "chuckle", "chunk", "churn", "cigar", "cinnamon", "circle", "citizen", "city", "civil", "claim", "clap", "clarify", "claw", "clay", "clean", "clerk", "clever", "click", "client", "cliff", "climb", "clinic", "clip", "clock", "clog", "close", "cloth", "cloud", "clown", "club", "clump", "cluster", "clutch", "coach", "coast", "coconut", "code", "coffee", "coil", "coin", "collect", "color", "column", "combine", "come", "comfort", "comic", "common", "company", "concert", "conduct", "confirm", "congress", "connect", "consider", "control", "convince", "cook", "cool", "copper", "copy", "coral", "core", "corn", "correct", "cost", "cotton", "couch", "country", "couple", "course", "cousin", "cover", "coyote", "crack", "cradle", "craft", "cram", "crane", "crash", "crater", "crawl", "crazy", "cream", "credit", "creek", "crew", "cricket", "crime", "crisp", "critic", "crop", "cross", "crouch", "crowd", "crucial", "cruel", "cruise", "crumble", "crunch", "crush", "cry", "crystal", "cube", "culture", "cup", "cupboard", "curious", "current", "curtain", "curve", "cushion", "custom", "cute", "cycle", "dad", "damage", "damp", "dance", "danger", "daring", "dash", "daughter", "dawn", "day", "deal", "debate", "debris", "decade", "december", "decide", "decline", "decorate", "decrease", "deer", "defense", "define", "defy", "degree", "delay", "deliver", "demand", "demise", "denial", "dentist", "deny", "depart", "depend", "deposit", "depth", "deputy", "derive", "describe", "desert", "design", "desk", "despair", "destroy", "detail", "detect", "develop", "device", "devote", "diagram", "dial", "diamond", "diary", "dice", "diesel", "diet", "differ", "digital", "dignity", "dilemma", "dinner", "dinosaur", "direct", "dirt", "disagree", "discover", "disease", "dish", "dismiss", "disorder", "display", "distance", "divert", "divide", "divorce", "dizzy", "doctor", "document", "dog", "doll", "dolphin", "domain", "donate", "donkey", "donor", "door", "dose", "double", "dove", "draft", "dragon", "drama", "drastic", "draw", "dream", "dress", "drift", "drill", "drink", "drip", "drive", "drop", "drum", "dry", "duck", "dumb", "dune", "during", "dust", "dutch", "duty", "dwarf", "dynamic", "eager", "eagle", "early", "earn", "earth", "easily", "east", "easy", "echo", "ecology", "economy", "edge", "edit", "educate", "effort", "egg", "eight", "either", "elbow", "elder", "electric", "elegant", "element", "elephant", "elevator", "elite", "else", "embark", "embody", "embrace", "emerge", "emotion", "employ", "empower", "empty", "enable", "enact", "end", "endless", "endorse", "enemy", "energy", "enforce", "engage", "engine", "enhance", "enjoy", "enlist", "enough", "enrich", "enroll", "ensure", "enter", "entire", "entry", "envelope", "episode", "equal", "equip", "era", "erase", "erode", "erosion", "error", "erupt", "escape", "essay", "essence", "estate", "eternal", "ethics", "evidence", "evil", "evoke", "evolve", "exact", "example", "excess", "exchange", "excite", "exclude", "excuse", "execute", "exercise", "exhaust", "exhibit", "exile", "exist", "exit", "exotic", "expand", "expect", "expire", "explain", "expose", "express", "extend", "extra", "eye", "eyebrow", "fabric", "face", "faculty", "fade", "faint", "faith", "fall", "false", "fame", "family", "famous", "fan", "fancy", "fantasy", "farm", "fashion", "fat", "fatal", "father", "fatigue", "fault", "favorite", "feature", "february", "federal", "fee", "feed", "feel", "female", "fence", "festival", "fetch", "fever", "few", "fiber", "fiction", "field", "figure", "file", "film", "filter", "final", "find", "fine", "finger", "finish", "fire", "firm", "first", "fiscal", "fish", "fit", "fitness", "fix", "flag", "flame", "flash", "flat", "flavor", "flee", "flight", "flip", "float", "flock", "floor", "flower", "fluid", "flush", "fly", "foam", "focus", "fog", "foil", "fold", "follow", "food", "foot", "force", "forest", "forget", "fork", "fortune", "forum", "forward", "fossil", "foster", "found", "fox", "fragile", "frame", "frequent", "fresh", "friend", "fringe", "frog", "front", "frost", "frown", "frozen", "fruit", "fuel", "fun", "funny", "furnace", "fury", "future", "gadget", "gain", "galaxy", "gallery", "game", "gap", "garage", "garbage", "garden", "garlic", "garment", "gas", "gasp", "gate", "gather", "gauge", "gaze", "general", "genius", "genre", "gentle", "genuine", "gesture", "ghost", "giant", "gift", "giggle", "ginger", "giraffe", "girl", "give", "glad", "glance", "glare", "glass", "glide", "glimpse", "globe", "gloom", "glory", "glove", "glow", "glue", "goat", "goddess", "gold", "good", "goose", "gorilla", "gospel", "gossip", "govern", "gown", "grab", "grace", "grain", "grant", "grape", "grass", "gravity", "great", "green", "grid", "grief", "grit", "grocery", "group", "grow", "grunt", "guard", "guess", "guide", "guilt", "guitar", "gun", "gym", "habit", "hair", "half", "hammer", "hamster", "hand", "happy", "harbor", "hard", "harsh", "harvest", "hat", "have", "hawk", "hazard", "head", "health", "heart", "heavy", "hedgehog", "height", "hello", "helmet", "help", "hen", "hero", "hidden", "high", "hill", "hint", "hip", "hire", "history", "hobby", "hockey", "hold", "hole", "holiday", "hollow", "home", "honey", "hood", "hope", "horn", "horror", "horse", "hospital", "host", "hotel", "hour", "hover", "hub", "huge", "human", "humble", "humor", "hundred", "hungry", "hunt", "hurdle", "hurry", "hurt", "husband", "hybrid", "ice", "icon", "idea", "identify", "idle", "ignore", "ill", "illegal", "illness", "image", "imitate", "immense", "immune", "impact", "impose", "improve", "impulse", "inch", "include", "income", "increase", "index", "indicate", "indoor", "industry", "infant", "inflict", "inform", "inhale", "inherit", "initial", "inject", "injury", "inmate", "inner", "innocent", "input", "inquiry", "insane", "insect", "inside", "inspire", "install", "intact", "interest", "into", "invest", "invite", "involve", "iron", "island", "isolate", "issue", "item", "ivory", "jacket", "jaguar", "jar", "jazz", "jealous", "jeans", "jelly", "jewel", "job", "join", "joke", "journey", "joy", "judge", "juice", "jump", "jungle", "junior", "junk", "just", "kangaroo", "keen", "keep", "ketchup", "key", "kick", "kid", "kidney", "kind", "kingdom", "kiss", "kit", "kitchen", "kite", "kitten", "kiwi", "knee", "knife", "knock", "know", "lab", "label", "labor", "ladder", "lady", "lake", "lamp", "language", "laptop", "large", "later", "latin", "laugh", "laundry", "lava", "law", "lawn", "lawsuit", "layer", "lazy", "leader", "leaf", "learn", "leave", "lecture", "left", "leg", "legal", "legend", "leisure", "lemon", "lend", "length", "lens", "leopard", "lesson", "letter", "level", "liar", "liberty", "library", "license", "life", "lift", "light", "like", "limb", "limit", "link", "lion", "liquid", "list", "little", "live", "lizard", "load", "loan", "lobster", "local", "lock", "logic", "lonely", "long", "loop", "lottery", "loud", "lounge", "love", "loyal", "lucky", "luggage", "lumber", "lunar", "lunch", "luxury", "lyrics", "machine", "mad", "magic", "magnet", "maid", "mail", "main", "major", "make", "mammal", "man", "manage", "mandate", "mango", "mansion", "manual", "maple", "marble", "march", "margin", "marine", "market", "marriage", "mask", "mass", "master", "match", "material", "math", "matrix", "matter", "maximum", "maze", "meadow", "mean", "measure", "meat", "mechanic", "medal", "media", "melody", "melt", "member", "memory", "mention", "menu", "mercy", "merge", "merit", "merry", "mesh", "message", "metal", "method", "middle", "midnight", "milk", "million", "mimic", "mind", "minimum", "minor", "minute", "miracle", "mirror", "misery", "miss", "mistake", "mix", "mixed", "mixture", "mobile", "model", "modify", "mom", "moment", "monitor", "monkey", "monster", "month", "moon", "moral", "more", "morning", "mosquito", "mother", "motion", "motor", "mountain", "mouse", "move", "movie", "much", "muffin", "mule", "multiply", "muscle", "museum", "mushroom", "music", "must", "mutual", "myself", "mystery", "myth", "naive", "name", "napkin", "narrow", "nasty", "nation", "nature", "near", "neck", "need", "negative", "neglect", "neither", "nephew", "nerve", "nest", "net", "network", "neutral", "never", "news", "next", "nice", "night", "noble", "noise", "nominee", "noodle", "normal", "north", "nose", "notable", "note", "nothing", "notice", "novel", "now", "nuclear", "number", "nurse", "nut", "oak", "obey", "object", "oblige", "obscure", "observe", "obtain", "obvious", "occur", "ocean", "october", "odor", "off", "offer", "office", "often", "oil", "okay", "old", "olive", "olympic", "omit", "once", "one", "onion", "online", "only", "open", "opera", "opinion", "oppose", "option", "orange", "orbit", "orchard", "order", "ordinary", "organ", "orient", "original", "orphan", "ostrich", "other", "outdoor", "outer", "output", "outside", "oval", "oven", "over", "own", "owner", "oxygen", "oyster", "ozone", "pact", "paddle", "page", "pair", "palace", "palm", "panda", "panel", "panic", "panther", "paper", "parade", "parent", "park", "parrot", "party", "pass", "patch", "path", "patient", "patrol", "pattern", "pause", "pave", "payment", "peace", "peanut", "pear", "peasant", "pelican", "pen", "penalty", "pencil", "people", "pepper", "perfect", "permit", "person", "pet", "phone", "photo", "phrase", "physical", "piano", "picnic", "picture", "piece", "pig", "pigeon", "pill", "pilot", "pink", "pioneer", "pipe", "pistol", "pitch", "pizza", "place", "planet", "plastic", "plate", "play", "please", "pledge", "pluck", "plug", "plunge", "poem", "poet", "point", "polar", "pole", "police", "pond", "pony", "pool", "popular", "portion", "position", "possible", "post", "potato", "pottery", "poverty", "powder", "power", "practice", "praise", "predict", "prefer", "prepare", "present", "pretty", "prevent", "price", "pride", "primary", "print", "priority", "prison", "private", "prize", "problem", "process", "produce", "profit", "program", "project", "promote", "proof", "property", "prosper", "protect", "proud", "provide", "public", "pudding", "pull", "pulp", "pulse", "pumpkin", "punch", "pupil", "puppy", "purchase", "purity", "purpose", "purse", "push", "put", "puzzle", "pyramid", "quality", "quantum", "quarter", "question", "quick", "quit", "quiz", "quote", "rabbit", "raccoon", "race", "rack", "radar", "radio", "rail", "rain", "raise", "rally", "ramp", "ranch", "random", "range", "rapid", "rare", "rate", "rather", "raven", "raw", "razor", "ready", "real", "reason", "rebel", "rebuild", "recall", "receive", "recipe", "record", "recycle", "reduce", "reflect", "reform", "refuse", "region", "regret", "regular", "reject", "relax", "release", "relief", "rely", "remain", "remember", "remind", "remove", "render", "renew", "rent", "reopen", "repair", "repeat", "replace", "report", "require", "rescue", "resemble", "resist", "resource", "response", "result", "retire", "retreat", "return", "reunion", "reveal", "review", "reward", "rhythm", "rib", "ribbon", "rice", "rich", "ride", "ridge", "rifle", "right", "rigid", "ring", "riot", "ripple", "risk", "ritual", "rival", "river", "road", "roast", "robot", "robust", "rocket", "romance", "roof", "rookie", "room", "rose", "rotate", "rough", "round", "route", "royal", "rubber", "rude", "rug", "rule", "run", "runway", "rural", "sad", "saddle", "sadness", "safe", "sail", "salad", "salmon", "salon", "salt", "salute", "same", "sample", "sand", "satisfy", "satoshi", "sauce", "sausage", "save", "say", "scale", "scan", "scare", "scatter", "scene", "scheme", "school", "science", "scissors", "scorpion", "scout", "scrap", "screen", "script", "scrub", "sea", "search", "season", "seat", "second", "secret", "section", "security", "seed", "seek", "segment", "select", "sell", "seminar", "senior", "sense", "sentence", "series", "service", "session", "settle", "setup", "seven", "shadow", "shaft", "shallow", "share", "shed", "shell", "sheriff", "shield", "shift", "shine", "ship", "shiver", "shock", "shoe", "shoot", "shop", "short", "shoulder", "shove", "shrimp", "shrug", "shuffle", "shy", "sibling", "sick", "side", "siege", "sight", "sign", "silent", "silk", "silly", "silver", "similar", "simple", "since", "sing", "siren", "sister", "situate", "six", "size", "skate", "sketch", "ski", "skill", "skin", "skirt", "skull", "slab", "slam", "sleep", "slender", "slice", "slide", "slight", "slim", "slogan", "slot", "slow", "slush", "small", "smart", "smile", "smoke", "smooth", "snack", "snake", "snap", "sniff", "snow", "soap", "soccer", "social", "sock", "soda", "soft", "solar", "soldier", "solid", "solution", "solve", "someone", "song", "soon", "sorry", "sort", "soul", "sound", "soup", "source", "south", "space", "spare", "spatial", "spawn", "speak", "special", "speed", "spell", "spend", "sphere", "spice", "spider", "spike", "spin", "spirit", "split", "spoil", "sponsor", "spoon", "sport", "spot", "spray", "spread", "spring", "spy", "square", "squeeze", "squirrel", "stable", "stadium", "staff", "stage", "stairs", "stamp", "stand", "start", "state", "stay", "steak", "steel", "stem", "step", "stereo", "stick", "still", "sting", "stock", "stomach", "stone", "stool", "story", "stove", "strategy", "street", "strike", "strong", "struggle", "student", "stuff", "stumble", "style", "subject", "submit", "subway", "success", "such", "sudden", "suffer", "sugar", "suggest", "suit", "summer", "sun", "sunny", "sunset", "super", "supply", "supreme", "sure", "surface", "surge", "surprise", "surround", "survey", "suspect", "sustain", "swallow", "swamp", "swap", "swarm", "swear", "sweet", "swift", "swim", "swing", "switch", "sword", "symbol", "symptom", "syrup", "system", "table", "tackle", "tag", "tail", "talent", "talk", "tank", "tape", "target", "task", "taste", "tattoo", "taxi", "teach", "team", "tell", "ten", "tenant", "tennis", "tent", "term", "test", "text", "thank", "that", "theme", "then", "theory", "there", "they", "thing", "this", "thought", "three", "thrive", "throw", "thumb", "thunder", "ticket", "tide", "tiger", "tilt", "timber", "time", "tiny", "tip", "tired", "tissue", "title", "toast", "tobacco", "today", "toddler", "toe", "together", "toilet", "token", "tomato", "tomorrow", "tone", "tongue", "tonight", "tool", "tooth", "top", "topic", "topple", "torch", "tornado", "tortoise", "toss", "total", "tourist", "toward", "tower", "town", "toy", "track", "trade", "traffic", "tragic", "train", "transfer", "trap", "trash", "travel", "tray", "treat", "tree", "trend", "trial", "tribe", "trick", "trigger", "trim", "trip", "trophy", "trouble", "truck", "true", "truly", "trumpet", "trust", "truth", "try", "tube", "tuition", "tumble", "tuna", "tunnel", "turkey", "turn", "turtle", "twelve", "twenty", "twice", "twin", "twist", "two", "type", "typical", "ugly", "umbrella", "unable", "unaware", "uncle", "uncover", "under", "undo", "unfair", "unfold", "unhappy", "uniform", "unique", "unit", "universe", "unknown", "unlock", "until", "unusual", "unveil", "update", "upgrade", "uphold", "upon", "upper", "upset", "urban", "urge", "usage", "use", "used", "useful", "useless", "usual", "utility", "vacant", "vacuum", "vague", "valid", "valley", "valve", "van", "vanish", "vapor", "various", "vast", "vault", "vehicle", "velvet", "vendor", "venture", "venue", "verb", "verify", "version", "very", "vessel", "veteran", "viable", "vibrant", "vicious", "victory", "video", "view", "village", "vintage", "violin", "virtual", "virus", "visa", "visit", "visual", "vital", "vivid", "vocal", "voice", "void", "volcano", "volume", "vote", "voyage", "wage", "wagon", "wait", "walk", "wall", "walnut", "want", "warfare", "warm", "warrior", "wash", "wasp", "waste", "water", "wave", "way", "wealth", "weapon", "wear", "weasel", "weather", "web", "wedding", "weekend", "weird", "welcome", "west", "wet", "whale", "what", "wheat", "wheel", "when", "where", "whip", "whisper", "wide", "width", "wife", "wild", "will", "win", "window", "wine", "wing", "wink", "winner", "winter", "wire", "wisdom", "wise", "wish", "witness", "wolf", "woman", "wonder", "wood", "wool", "word", "work", "world", "worry", "worth", "wrap", "wreck", "wrestle", "wrist", "write", "wrong", "yard", "year", "yellow", "you", "young", "youth", "zebra", "zero", "zone", "zoo", ];
70.648256
99
0.550056
db6c97f3739c74068a74e4b26ca4e9f80aae964c
7,358
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::get_parent_expr; use clippy_utils::source::snippet_with_context; use clippy_utils::ty::{is_type_lang_item, peel_mid_ty_refs}; use if_chain::if_chain; use rustc_ast::util::parser::PREC_PREFIX; use rustc_errors::Applicability; use rustc_hir::{BorrowKind, Expr, ExprKind, LangItem, Mutability}; use rustc_lint::{LateContext, LateLintPass, Lint}; use rustc_middle::ty::adjustment::{Adjust, AutoBorrow, AutoBorrowMutability}; use rustc_middle::ty::subst::GenericArg; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { /// ### What it does /// Checks for redundant slicing expressions which use the full range, and /// do not change the type. /// /// ### Why is this bad? /// It unnecessarily adds complexity to the expression. /// /// ### Known problems /// If the type being sliced has an implementation of `Index<RangeFull>` /// that actually changes anything then it can't be removed. However, this would be surprising /// to people reading the code and should have a note with it. /// /// ### Example /// ```ignore /// fn get_slice(x: &[u32]) -> &[u32] { /// &x[..] /// } /// ``` /// Use instead: /// ```ignore /// fn get_slice(x: &[u32]) -> &[u32] { /// x /// } /// ``` #[clippy::version = "1.51.0"] pub REDUNDANT_SLICING, complexity, "redundant slicing of the whole range of a type" } declare_clippy_lint! { /// ### What it does /// Checks for slicing expressions which are equivalent to dereferencing the /// value. /// /// ### Why is this bad? /// Some people may prefer to dereference rather than slice. /// /// ### Example /// ```rust /// let vec = vec![1, 2, 3]; /// let slice = &vec[..]; /// ``` /// Use instead: /// ```rust /// let vec = vec![1, 2, 3]; /// let slice = &*vec; /// ``` #[clippy::version = "1.61.0"] pub DEREF_BY_SLICING, restriction, "slicing instead of dereferencing" } declare_lint_pass!(RedundantSlicing => [REDUNDANT_SLICING, DEREF_BY_SLICING]); static REDUNDANT_SLICING_LINT: (&Lint, &str) = (REDUNDANT_SLICING, "redundant slicing of the whole range"); static DEREF_BY_SLICING_LINT: (&Lint, &str) = (DEREF_BY_SLICING, "slicing when dereferencing would work"); impl<'tcx> LateLintPass<'tcx> for RedundantSlicing { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if expr.span.from_expansion() { return; } let ctxt = expr.span.ctxt(); if_chain! { if let ExprKind::AddrOf(BorrowKind::Ref, mutability, addressee) = expr.kind; if addressee.span.ctxt() == ctxt; if let ExprKind::Index(indexed, range) = addressee.kind; if is_type_lang_item(cx, cx.typeck_results().expr_ty_adjusted(range), LangItem::RangeFull); then { let (expr_ty, expr_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(expr)); let (indexed_ty, indexed_ref_count) = peel_mid_ty_refs(cx.typeck_results().expr_ty(indexed)); let parent_expr = get_parent_expr(cx, expr); let needs_parens_for_prefix = parent_expr.map_or(false, |parent| { parent.precedence().order() > PREC_PREFIX }); let mut app = Applicability::MachineApplicable; let ((lint, msg), help, sugg) = if expr_ty == indexed_ty { if expr_ref_count > indexed_ref_count { // Indexing takes self by reference and can't return a reference to that // reference as it's a local variable. The only way this could happen is if // `self` contains a reference to the `Self` type. If this occurs then the // lint no longer applies as it's essentially a field access, which is not // redundant. return; } let deref_count = indexed_ref_count - expr_ref_count; let (lint, reborrow_str, help_str) = if mutability == Mutability::Mut { // The slice was used to reborrow the mutable reference. (DEREF_BY_SLICING_LINT, "&mut *", "reborrow the original value instead") } else if matches!( parent_expr, Some(Expr { kind: ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _), .. }) ) || cx.typeck_results().expr_adjustments(expr).first().map_or(false, |a| { matches!(a.kind, Adjust::Borrow(AutoBorrow::Ref(_, AutoBorrowMutability::Mut { .. }))) }) { // The slice was used to make a temporary reference. (DEREF_BY_SLICING_LINT, "&*", "reborrow the original value instead") } else if deref_count != 0 { (DEREF_BY_SLICING_LINT, "", "dereference the original value instead") } else { (REDUNDANT_SLICING_LINT, "", "use the original value instead") }; let snip = snippet_with_context(cx, indexed.span, ctxt, "..", &mut app).0; let sugg = if (deref_count != 0 || !reborrow_str.is_empty()) && needs_parens_for_prefix { format!("({}{}{})", reborrow_str, "*".repeat(deref_count), snip) } else { format!("{}{}{}", reborrow_str, "*".repeat(deref_count), snip) }; (lint, help_str, sugg) } else if let Some(target_id) = cx.tcx.lang_items().deref_target() { if let Ok(deref_ty) = cx.tcx.try_normalize_erasing_regions( cx.param_env, cx.tcx.mk_projection(target_id, cx.tcx.mk_substs([GenericArg::from(indexed_ty)].into_iter())), ) { if deref_ty == expr_ty { let snip = snippet_with_context(cx, indexed.span, ctxt, "..", &mut app).0; let sugg = if needs_parens_for_prefix { format!("(&{}{}*{})", mutability.prefix_str(), "*".repeat(indexed_ref_count), snip) } else { format!("&{}{}*{}", mutability.prefix_str(), "*".repeat(indexed_ref_count), snip) }; (DEREF_BY_SLICING_LINT, "dereference the original value instead", sugg) } else { return; } } else { return; } } else { return; }; span_lint_and_sugg( cx, lint, expr.span, msg, help, sugg, app, ); } } } }
43.282353
118
0.519978
0a45585f65e6b57c2b5116a08a7dcd08cf4915eb
885
// This file is part of security-keys-rust. 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/security-keys-rust/master/COPYRIGHT. No part of security-keys-rust, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2021 The developers of security-keys-rust. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/security-keys-rust/master/COPYRIGHT. /// Video protocol. #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] #[derive(Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub enum VideoProtocol { #[allow(missing_docs)] Version_1_0, #[allow(missing_docs)] Version_1_5, }
52.058824
409
0.784181
fc627d36fc9190335fef898b4b56cb66a1acfe63
4,222
#![allow(clippy::module_inception)] #![allow(clippy::upper_case_acronyms)] #![allow(clippy::large_enum_variant)] #![allow(clippy::wrong_self_convention)] #![allow(clippy::should_implement_trait)] #![allow(clippy::blacklisted_name)] #![allow(clippy::vec_init_then_push)] #![allow(rustdoc::bare_urls)] #![warn(missing_docs)] //! <fullname>AWS Resource Groups</fullname> //! //! <p>AWS Resource Groups lets you organize AWS resources such as Amazon EC2 instances, Amazon Relational Database Service //! databases, and Amazon S3 buckets into groups using criteria that you define as tags. A //! resource group is a collection of resources that match the resource types specified in a //! query, and share one or more tags or portions of tags. You can create a group of //! resources based on their roles in your cloud infrastructure, lifecycle stages, regions, //! application layers, or virtually any criteria. Resource Groups enable you to automate management //! tasks, such as those in AWS Systems Manager Automation documents, on tag-related resources in //! AWS Systems Manager. Groups of tagged resources also let you quickly view a custom console in //! AWS Systems Manager that shows AWS Config compliance and other monitoring data about member //! resources.</p> //! <p>To create a resource group, build a resource query, and specify tags that identify the //! criteria that members of the group have in common. Tags are key-value pairs.</p> //! <p>For more information about Resource Groups, see the <a href="https://docs.aws.amazon.com/ARG/latest/userguide/welcome.html">AWS Resource Groups User Guide</a>.</p> //! <p>AWS Resource Groups uses a REST-compliant API that you can use to perform the following types of //! operations.</p> //! <ul> //! <li> //! <p>Create, Read, Update, and Delete (CRUD) operations on resource groups and //! resource query entities</p> //! </li> //! <li> //! <p>Applying, editing, and removing tags from resource groups</p> //! </li> //! <li> //! <p>Resolving resource group member ARNs so they can be returned as search //! results</p> //! </li> //! <li> //! <p>Getting data about resources that are members of a group</p> //! </li> //! <li> //! <p>Searching AWS resources based on a resource query</p> //! </li> //! </ul> //! //! # Crate Organization //! //! The entry point for most customers will be [`Client`]. [`Client`] exposes one method for each API offered //! by the service. //! //! Some APIs require complex or nested arguments. These exist in [`model`](crate::model). //! //! Lastly, errors that can be returned by the service are contained within [`error`]. [`Error`] defines a meta //! error encompassing all possible errors that can be returned by the service. //! //! The other modules within this crate are not required for normal usage. // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub use error_meta::Error; pub use config::Config; mod aws_endpoint; /// Client and fluent builders for calling the service. pub mod client; /// Configuration for the service. pub mod config; /// Errors that can occur when calling the service. pub mod error; mod error_meta; /// Input structures for operations. pub mod input; mod json_deser; mod json_errors; mod json_ser; /// Generated accessors for nested fields mod lens; pub mod middleware; /// Data structures used by operation inputs/outputs. pub mod model; mod no_credentials; /// All operations that this crate can perform. pub mod operation; mod operation_deser; mod operation_ser; /// Output structures for operations. pub mod output; /// Paginators for the service pub mod paginator; /// Crate version number. pub static PKG_VERSION: &str = env!("CARGO_PKG_VERSION"); pub use aws_smithy_http::byte_stream::ByteStream; pub use aws_smithy_http::result::SdkError; pub use aws_smithy_types::Blob; pub use aws_smithy_types::DateTime; static API_METADATA: aws_http::user_agent::ApiMetadata = aws_http::user_agent::ApiMetadata::new("resourcegroups", PKG_VERSION); pub use aws_smithy_http::endpoint::Endpoint; pub use aws_smithy_types::retry::RetryConfig; pub use aws_types::app_name::AppName; pub use aws_types::region::Region; pub use aws_types::Credentials; pub use client::Client;
40.209524
170
0.74325
0ed1102c65889fba38edf7b0360fed98658e1f4b
5,165
use glium::glutin; use glium::texture::{texture2d, ClientFormat, PixelValue, RawImage2d}; use glium::{Program, Surface}; use winit::{ dpi::PhysicalSize, event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, platform::run_return::EventLoopExtRunReturn, window::WindowBuilder, }; use std::cell::Cell; #[derive(Copy, Clone)] struct Vertex { position: [f32; 2], tex_coords: [f32; 2], } implement_vertex!(Vertex, position, tex_coords); pub struct Window { display: glium::Display, indicies: glium::index::NoIndices, program: glium::Program, vertex_buffer: glium::VertexBuffer<Vertex>, event_loop: EventLoop<()>, closed: Cell<bool>, } impl Window { pub fn new(width: u32, height: u32) -> Window { let event_loop = EventLoop::new(); let window_size = PhysicalSize::new(width, height); let window_builder = WindowBuilder::new() .with_inner_size(window_size) .with_title("Mass Renderer"); let context_builder = glutin::ContextBuilder::new() .with_vsync(true) .with_srgb(true) .with_gl_profile(glutin::GlProfile::Core) .with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (4, 2))); let display = glium::Display::new(window_builder, context_builder, &event_loop) .expect("Unable to create display"); let vert_shader = r#" #version 140 in vec2 position; in vec2 tex_coords; out vec2 v_tex_coords; void main() { v_tex_coords = tex_coords; gl_Position = vec4(position, 0.0, 1.0); } "#; let frag_shader = r#" #version 140 in vec2 v_tex_coords; out vec4 color; uniform sampler2D tex; void main() { color = texture(tex, v_tex_coords); } "#; let top_right = Vertex { position: [1.0, 1.0], tex_coords: [1.0, 0.0], }; let top_left = Vertex { position: [-1.0, 1.0], tex_coords: [0.0, 0.0], }; let bottom_left = Vertex { position: [-1.0, -1.0], tex_coords: [0.0, 1.0], }; let bottom_right = Vertex { position: [1.0, -1.0], tex_coords: [1.0, 1.0], }; let shape = vec![top_right, top_left, bottom_left, bottom_right]; let program = Program::from_source(&display, vert_shader, frag_shader, None) .expect("Unable to create gl program"); let vertex_buffer = glium::VertexBuffer::new(&display, &shape).expect("Unable to create vertex buffer"); let indicies = glium::index::NoIndices(glium::index::PrimitiveType::TriangleFan); Window { display, indicies, program, vertex_buffer, event_loop, closed: Cell::new(false), } } fn process_events(&mut self) { let closed = self.closed.get_mut(); self.event_loop.run_return(|event, _window, control_flow| { match event { Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => *closed = true, _ => (), } *control_flow = ControlFlow::Exit; }) } pub fn render<'a, T: 'a + Clone + PixelValue, I: Into<RawImage2d<'a, T>>>( &'a mut self, image: I, ) { let texture = texture2d::Texture2d::new(&self.display, image.into()).unwrap(); let uniforms = uniform! { tex: texture.sampled() .magnify_filter(glium::uniforms::MagnifySamplerFilter::Nearest) .minify_filter(glium::uniforms::MinifySamplerFilter::Nearest), }; let mut target = self.display.draw(); target.clear_color(0.0, 0.0, 0.0, 1.0); target .draw( &self.vertex_buffer, &self.indicies, &self.program, &uniforms, &Default::default(), ) .unwrap(); target.finish().unwrap(); self.display.gl_window().window().request_redraw(); self.process_events(); } pub fn is_closed(&self) -> bool { self.closed.get() } } use crate::renderer::{Color as RColor, Surface as RSurface, Texture as RTexture}; impl<'a, 'b, T> Into<RawImage2d<'a, (u8, u8, u8, u8)>> for &'b RTexture<T> where T: Into<RColor> + Copy, { fn into(self) -> RawImage2d<'a, (u8, u8, u8, u8)> { let mut data = Vec::new(); for y in 0..self.height() { for x in 0..self.width() { let c = self.get(x, self.height() - y - 1).into().to_linear(); data.push((c.r(), c.g(), c.b(), c.a())); } } RawImage2d { width: self.width(), height: self.height(), format: ClientFormat::U8U8U8U8, data: data.into(), } } }
28.535912
96
0.523911
75335af0fb953b685d626867799ff5a700a4bd3b
9,988
#![allow(clippy::integer_arithmetic)] use { log::*, serial_test::serial, solana_core::validator::ValidatorConfig, solana_gossip::{cluster_info::Node, contact_info::ContactInfo}, solana_local_cluster::{ cluster::Cluster, local_cluster::{ClusterConfig, LocalCluster}, validator_configs::*, }, solana_replica_node::{ replica_node::{ReplicaNode, ReplicaNodeConfig}, replica_util, }, solana_rpc::{rpc::JsonRpcConfig, rpc_pubsub_service::PubSubConfig}, solana_runtime::{ accounts_index::AccountSecondaryIndexes, snapshot_archive_info::SnapshotArchiveInfoGetter, snapshot_config::{LastFullSnapshotSlot, SnapshotConfig}, snapshot_utils::{self, ArchiveFormat}, }, solana_sdk::{ client::SyncClient, clock::Slot, commitment_config::CommitmentConfig, epoch_schedule::MINIMUM_SLOTS_PER_EPOCH, exit::Exit, hash::Hash, signature::{Keypair, Signer}, }, solana_streamer::socket::SocketAddrSpace, std::{ net::{IpAddr, Ipv4Addr, SocketAddr}, path::{Path, PathBuf}, sync::{Arc, RwLock}, thread::sleep, time::Duration, }, tempfile::TempDir, }; const RUST_LOG_FILTER: &str = "error,solana_core::replay_stage=warn,solana_local_cluster=info,local_cluster=info"; fn wait_for_next_snapshot( cluster: &LocalCluster, snapshot_package_output_path: &Path, ) -> (PathBuf, (Slot, Hash)) { // Get slot after which this was generated let client = cluster .get_validator_client(&cluster.entry_point_info.id) .unwrap(); let last_slot = client .get_slot_with_commitment(CommitmentConfig::processed()) .expect("Couldn't get slot"); // Wait for a snapshot for a bank >= last_slot to be made so we know that the snapshot // must include the transactions just pushed trace!( "Waiting for snapshot archive to be generated with slot > {}", last_slot ); loop { if let Some(full_snapshot_archive_info) = snapshot_utils::get_highest_full_snapshot_archive_info(snapshot_package_output_path) { trace!( "full snapshot for slot {} exists", full_snapshot_archive_info.slot() ); if full_snapshot_archive_info.slot() >= last_slot { return ( full_snapshot_archive_info.path().clone(), ( full_snapshot_archive_info.slot(), *full_snapshot_archive_info.hash(), ), ); } trace!( "full snapshot slot {} < last_slot {}", full_snapshot_archive_info.slot(), last_slot ); } sleep(Duration::from_millis(1000)); } } fn farf_dir() -> PathBuf { std::env::var("FARF_DIR") .unwrap_or_else(|_| "farf".to_string()) .into() } fn generate_account_paths(num_account_paths: usize) -> (Vec<TempDir>, Vec<PathBuf>) { let account_storage_dirs: Vec<TempDir> = (0..num_account_paths) .map(|_| tempfile::tempdir_in(farf_dir()).unwrap()) .collect(); let account_storage_paths: Vec<_> = account_storage_dirs .iter() .map(|a| a.path().to_path_buf()) .collect(); (account_storage_dirs, account_storage_paths) } struct SnapshotValidatorConfig { _snapshot_dir: TempDir, snapshot_archives_dir: TempDir, account_storage_dirs: Vec<TempDir>, validator_config: ValidatorConfig, } fn setup_snapshot_validator_config( snapshot_interval_slots: u64, num_account_paths: usize, ) -> SnapshotValidatorConfig { // Create the snapshot config let snapshot_dir = tempfile::tempdir_in(farf_dir()).unwrap(); let snapshot_archives_dir = tempfile::tempdir_in(farf_dir()).unwrap(); let snapshot_config = SnapshotConfig { full_snapshot_archive_interval_slots: snapshot_interval_slots, incremental_snapshot_archive_interval_slots: Slot::MAX, snapshot_package_output_path: snapshot_archives_dir.path().to_path_buf(), snapshot_path: snapshot_dir.path().to_path_buf(), archive_format: ArchiveFormat::TarBzip2, snapshot_version: snapshot_utils::SnapshotVersion::default(), maximum_snapshots_to_retain: snapshot_utils::DEFAULT_MAX_FULL_SNAPSHOT_ARCHIVES_TO_RETAIN, last_full_snapshot_slot: LastFullSnapshotSlot::default(), }; // Create the account paths let (account_storage_dirs, account_storage_paths) = generate_account_paths(num_account_paths); // Create the validator config let validator_config = ValidatorConfig { snapshot_config: Some(snapshot_config), account_paths: account_storage_paths, accounts_hash_interval_slots: snapshot_interval_slots, ..ValidatorConfig::default() }; SnapshotValidatorConfig { _snapshot_dir: snapshot_dir, snapshot_archives_dir, account_storage_dirs, validator_config, } } fn test_local_cluster_start_and_exit_with_config(socket_addr_space: SocketAddrSpace) { solana_logger::setup(); const NUM_NODES: usize = 1; let mut config = ClusterConfig { validator_configs: make_identical_validator_configs(&ValidatorConfig::default(), NUM_NODES), node_stakes: vec![3; NUM_NODES], cluster_lamports: 100, ticks_per_slot: 8, slots_per_epoch: MINIMUM_SLOTS_PER_EPOCH as u64, stakers_slot_offset: MINIMUM_SLOTS_PER_EPOCH as u64, ..ClusterConfig::default() }; let cluster = LocalCluster::new(&mut config, socket_addr_space); assert_eq!(cluster.validators.len(), NUM_NODES); } #[test] #[serial] fn test_replica_bootstrap() { let socket_addr_space = SocketAddrSpace::new(true); test_local_cluster_start_and_exit_with_config(socket_addr_space); solana_logger::setup_with_default(RUST_LOG_FILTER); // First set up the cluster with 1 node let snapshot_interval_slots = 50; let num_account_paths = 3; let leader_snapshot_test_config = setup_snapshot_validator_config(snapshot_interval_slots, num_account_paths); info!( "Snapshot config for the leader: accounts: {:?}, snapshot: {:?}", leader_snapshot_test_config.account_storage_dirs, leader_snapshot_test_config.snapshot_archives_dir ); let stake = 10_000; let mut config = ClusterConfig { node_stakes: vec![stake], cluster_lamports: 1_000_000, validator_configs: make_identical_validator_configs( &leader_snapshot_test_config.validator_config, 1, ), ..ClusterConfig::default() }; let cluster = LocalCluster::new(&mut config, socket_addr_space); assert_eq!(cluster.validators.len(), 1); let contact_info = &cluster.entry_point_info; info!("Contact info: {:?}", contact_info); // Get slot after which this was generated let snapshot_package_output_path = &leader_snapshot_test_config .validator_config .snapshot_config .as_ref() .unwrap() .snapshot_package_output_path; info!("Waiting for snapshot"); let (archive_filename, archive_snapshot_hash) = wait_for_next_snapshot(&cluster, snapshot_package_output_path); info!("found: {:?}", archive_filename); let identity_keypair = Keypair::new(); // now bring up a replica to talk to it. let ip_addr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let port = solana_net_utils::find_available_port_in_range(ip_addr, (8101, 8200)).unwrap(); let rpc_addr = SocketAddr::new(ip_addr, port); let port = solana_net_utils::find_available_port_in_range(ip_addr, (8201, 8300)).unwrap(); let rpc_pubsub_addr = SocketAddr::new(ip_addr, port); let ledger_dir = tempfile::tempdir_in(farf_dir()).unwrap(); let ledger_path = ledger_dir.path(); let snapshot_output_dir = tempfile::tempdir_in(farf_dir()).unwrap(); let snapshot_output_path = snapshot_output_dir.path(); let snapshot_path = snapshot_output_path.join("snapshot"); let account_paths: Vec<PathBuf> = vec![ledger_path.join("accounts")]; let port = solana_net_utils::find_available_port_in_range(ip_addr, (8301, 8400)).unwrap(); let gossip_addr = SocketAddr::new(ip_addr, port); let dynamic_port_range = solana_net_utils::parse_port_range("8401-8500").unwrap(); let bind_address = solana_net_utils::parse_host("127.0.0.1").unwrap(); let node = Node::new_with_external_ip( &identity_keypair.pubkey(), &gossip_addr, dynamic_port_range, bind_address, ); info!("The peer id: {:?}", &contact_info.id); let entry_points = vec![ContactInfo::new_gossip_entry_point(&contact_info.gossip)]; let (cluster_info, _rpc_contact_info, _snapshot_info) = replica_util::get_rpc_peer_info( identity_keypair, &entry_points, ledger_path, &node, None, &contact_info.id, snapshot_output_path, socket_addr_space, ); info!("The cluster info:\n{:?}", cluster_info.contact_info_trace()); let config = ReplicaNodeConfig { rpc_source_addr: contact_info.rpc, rpc_addr, rpc_pubsub_addr, ledger_path: ledger_path.to_path_buf(), snapshot_output_dir: snapshot_output_path.to_path_buf(), snapshot_path, account_paths, snapshot_info: archive_snapshot_hash, cluster_info, rpc_config: JsonRpcConfig::default(), snapshot_config: None, pubsub_config: PubSubConfig::default(), socket_addr_space, account_indexes: AccountSecondaryIndexes::default(), accounts_db_caching_enabled: false, replica_exit: Arc::new(RwLock::new(Exit::default())), }; let _replica_node = ReplicaNode::new(config); }
35.41844
100
0.669704
141cc44315a7bb5c2cd9ffa12982fa37436d8267
7,423
#![allow(dead_code)] use std::collections::VecDeque; #[derive(Debug, Eq, PartialEq)] struct Packet { version: u8, packet_type: u8, payload: Payload, } impl Packet { fn from_hex_string(text: &str) -> Self { Packet::read(&mut BitQueue::from_hex_string(text)) } fn read(queue: &mut BitQueue) -> Self { let version = queue.read_bits_as_num(3) as u8; let packet_type = queue.read_bits_as_num(3) as u8; let payload = match packet_type { 4 => Packet::read_literal(queue), _ => Packet::read_operator(queue), }; Packet { version, packet_type, payload, } } fn read_literal(queue: &mut BitQueue) -> Payload { let mut result = 0; loop { result <<= 4; let next = queue.read_bits_as_num(5); if next & 0b10000 == 0 { // last octet. result += next; return Payload::Literal { value: result }; } else { result += next & 0b01111 } } } fn read_operator(queue: &mut BitQueue) -> Payload { let len = Packet::read_length(queue); let packets = Packet::read_packets(&len, queue); Payload::Operator { length: len, subpackets: packets, } } fn read_length(queue: &mut BitQueue) -> Length { let len_type = queue.read_bits_as_num(1); if len_type == 0 { Length::Bits { value: queue.read_bits_as_num(15) as u16, } } else { Length::PacketCount { value: queue.read_bits_as_num(11) as u16, } } } fn read_packets(len: &Length, queue: &mut BitQueue) -> Vec<Packet> { match len { Length::Bits { value: bit_count } => { let mut result: Vec<Packet> = Vec::new(); let initial_size = queue.value.len(); loop { result.push(Packet::read(queue)); let read = (initial_size - queue.value.len()) as u16; if read == *bit_count { return result; } if read > *bit_count { panic!( "unaligned packages! read: {}, expected: {}", read, bit_count ); } } } Length::PacketCount { value: packet_count, } => (0..*packet_count).map(|_| Packet::read(queue)).collect(), } } fn eval(&self) -> u64 { match &self.payload { Payload::Literal { value } => *value, Payload::Operator { length: _, subpackets, } => { let args = subpackets.iter().map(|x| x.eval()).collect::<Vec<u64>>(); match self.packet_type { 0 => args.into_iter().sum(), 1 => args.into_iter().product(), 2 => args.into_iter().min().unwrap(), 3 => args.into_iter().max().unwrap(), 5 => { if args[0] > args[1] { 1 } else { 0 } } 6 => { if args[0] < args[1] { 1 } else { 0 } } 7 => { if args[0] == args[1] { 1 } else { 0 } } _ => panic!("Unknown packet type: {}", self.packet_type), } } } } } #[derive(Debug, Eq, PartialEq)] enum Payload { Literal { value: u64, }, Operator { length: Length, subpackets: Vec<Packet>, }, } #[derive(Debug, Eq, PartialEq)] enum Length { Bits { value: u16 }, PacketCount { value: u16 }, } struct BitQueue { value: VecDeque<bool>, } impl BitQueue { fn new() -> Self { BitQueue { value: VecDeque::new(), } } fn from_hex_string(text: &str) -> Self { let mut result = BitQueue::new(); for ch in text.trim().chars() { result.add_char(ch); } result } fn add_char(&mut self, ch: char) { if !ch.is_ascii() { panic!("not ascii: {}", ch); } let val = match ch { '0'..='9' => ch as u8 - '0' as u8, 'A'..='F' => ch as u8 - 'A' as u8 + 10, _ => panic!("Unsupported char: {}", ch), }; self.value.push_back(val & 0b1000 > 0); self.value.push_back(val & 0b0100 > 0); self.value.push_back(val & 0b0010 > 0); self.value.push_back(val & 0b0001 > 0); } fn read_bits_as_num(&mut self, count: u8) -> u64 { let mut result = 0; for _ in 0..count { result = result * 2 + if self.value.pop_front().unwrap() { 1 } else { 0 } } result } } fn total_version(p: &Packet) -> u32 { match &p.payload { Payload::Operator { length: _, subpackets, } => subpackets.iter().map(total_version).sum::<u32>() + p.version as u32, Payload::Literal { value: _ } => p.version as u32, } } fn part1(text: &str) -> u32 { total_version(&Packet::from_hex_string(text)) } fn part2(text: &str) -> u64 { Packet::from_hex_string(text).eval() } #[cfg(test)] mod tests { use super::*; #[test] fn simple_packet() { let mut queue = BitQueue::from_hex_string("D2FE28"); println!("{:?}", Packet::read(&mut queue)) } #[test] fn len_type_0_packet() { let mut queue = BitQueue::from_hex_string("38006F45291200"); println!("{:?}", Packet::read(&mut queue)) } #[test] fn len_type_1_packet() { let mut queue = BitQueue::from_hex_string("EE00D40C823060"); println!("{:#?}", Packet::read(&mut queue)) } #[test] fn part1() { assert_eq!(super::part1("8A004A801A8002F478"), 16); assert_eq!(super::part1("620080001611562C8802118E34"), 12); assert_eq!(super::part1("C0015000016115A2E0802F182340"), 23); assert_eq!(super::part1("A0016C880162017C3686B18A3D4780"), 31); println!("part1: {}", super::part1(include_str!("../resources/day16.txt"))); } #[test] fn part2() { assert_eq!(super::part2("C200B40A82"), 3); assert_eq!(super::part2("04005AC33890"), 54); assert_eq!(super::part2("880086C3E88112"), 7); assert_eq!(super::part2("CE00C43D881120"), 9); assert_eq!(super::part2("D8005AC2A8F0"), 1); assert_eq!(super::part2("F600BC2D8F"), 0); assert_eq!(super::part2("9C005AC2F8F0"), 0); assert_eq!(super::part2("9C0141080250320F1802104A08"), 1); println!("part2: {}", super::part2(include_str!("../resources/day16.txt"))); } }
28.660232
85
0.453455
28e38e3f68cd420914402b0debb1714095cd28a4
4,366
use crate::tfpb::graph::GraphDef; use crate::tfpb::node_def::NodeDef; use tract_core::internal::*; pub type TfOpRegister = OpRegister<NodeDef>; pub struct Tensorflow { pub op_register: TfOpRegister, } impl Tensorflow { // From the node_def.proto documentation: // Each input is "node:src_output" with "node" being a string name and // "src_output" indicating which output tensor to use from "node". If // "src_output" is 0 the ":0" suffix can be omitted. Regular inputs may // optionally be followed by control inputs that have the format "^node". fn parse_input(i: &str) -> TractResult<(&str, usize)> { let pair = if i.starts_with("^") { (&i[1..], 0) } else { let splits: Vec<_> = i.splitn(2, ':').collect(); (splits[0], if splits.len() > 1 { splits[1].parse::<usize>()? } else { 0 }) }; Ok(pair) } } impl Framework<NodeDef, GraphDef> for Tensorflow { fn op_builder_for_name(&self, name: &str) -> Option<&OpBuilder<NodeDef>> { self.op_register.get(name) } fn proto_model_for_read(&self, r: &mut std::io::Read) -> TractResult<GraphDef> { Ok(::protobuf::parse_from_reader::<GraphDef>(r).map_err(|e| format!("{:?}", e))?) } fn model_for_proto_model(&self, graph: &GraphDef) -> TractResult<InferenceModel> { let mut model = InferenceModel::default(); // compute min output arity for all nodes let mut arities = HashMap::new(); for pbnode in graph.get_node().iter() { for i in pbnode.get_input().iter() { let (node, slot) = Self::parse_input(i)?; let arity = arities.entry(node).or_insert(1); *arity = (*arity).max(slot + 1); } } for pbnode in graph.get_node().iter() { let name = pbnode.get_name().to_string(); let output_arity = arities.get(&*name).cloned().unwrap_or(1); let facts = tvec!(TensorFact::default(); output_arity); let node_id = model.add_node( name.clone(), self.build_op(&*pbnode.get_op(), pbnode) .map_err(|e| format!("While building node {}, {}", name, e.description()))?, facts, )?; if pbnode.get_op() == "PlaceHolder" { let dt = pbnode.get_attr_datum_type("dtype")?; let mut fact = TensorFact::dt(dt); if let Some(shape) = pbnode.get_attr_opt_shape("shape")? { fact = fact.with_shape(shape) } model.set_outlet_fact(OutletId::new(node_id, 0), fact)?; } } for (node_id, pbnode) in graph.get_node().iter().enumerate() { for (ix, i) in pbnode.get_input().iter().enumerate() { let input = Self::parse_input(i)?; let prec = model.node_by_name(input.0)?.id; let outlet = OutletId::new(prec, input.1); let inlet = InletId::new(node_id, ix); model.add_edge(outlet, inlet)?; } } // variable -> assign rewire // in protobuf: // * VariableV2 has a single output (a byref tensor) // * Assign consumes this by_ref tensor on #0 and somehow performs // updates on it (it has a second input on #1 for the value to // assign) // // in tract: // * VariableV2 has two outputs: first is the value, second is an // opaque ptr to be used by Assign (pointing to the state) // * Assign will plug a third input (#2) into the VariableV2 // output #1 to access the opaque ptr for id in 0..model.nodes().len() { use crate::ops::vars::*; if model.node(id).op_is::<Assign>() { let prec = model.node(id).inputs[0]; let var_id = model.node(prec.node).op_as::<VariableV2>().map(|v| v.id.clone()); if let (Some(var_id), Some(assign)) = (var_id, model.node_mut(id).op_as_mut::<Assign>()) { assign.var_id = Some(var_id); } else { bail!("Model contains unlinked Assign/Variable2"); } } } Ok(model) } }
40.425926
96
0.535502
21b730f53b5869667bd7754e95160b15ec4b7752
11,131
use alloc::string::String; use alloc::sync::{Arc, Weak}; use core::any::Any; use rcore_fs::vfs::*; use std::io::{Read, Seek, SeekFrom, Write}; use std::os::unix::fs::{DirEntryExt, FileTypeExt}; use std::path::{Path, PathBuf}; use std::sync::{SgxMutex as Mutex, SgxMutexGuard as MutexGuard}; use std::untrusted::fs; use std::untrusted::path::PathEx; /// Untrusted file system at host pub struct HostFS { path: PathBuf, self_ref: Weak<HostFS>, } /// INode for `HostFS` pub struct HNode { path: PathBuf, file: Mutex<Option<fs::File>>, fs: Arc<HostFS>, } impl FileSystem for HostFS { fn sync(&self) -> Result<()> { warn!("HostFS: sync is unimplemented"); Ok(()) } fn root_inode(&self) -> Arc<dyn INode> { Arc::new(HNode { path: self.path.clone(), file: Mutex::new(None), fs: self.self_ref.upgrade().unwrap(), }) } fn info(&self) -> FsInfo { warn!("HostFS: FsInfo is unimplemented"); Default::default() } } impl HostFS { /// Create a new `HostFS` from host `path` pub fn new(path: impl AsRef<Path>) -> Arc<HostFS> { HostFS { path: path.as_ref().to_path_buf(), self_ref: Weak::default(), } .wrap() } /// Wrap pure `HostFS` with Arc /// Used in constructors fn wrap(self) -> Arc<Self> { // Create an Arc, make a Weak from it, then put it into the struct. // It's a little tricky. let fs = Arc::new(self); let weak = Arc::downgrade(&fs); let ptr = Arc::into_raw(fs) as *mut Self; unsafe { (*ptr).self_ref = weak; } unsafe { Arc::from_raw(ptr) } } } // workaround for unable to `impl From<std::io::Error> for FsError` macro_rules! try_std { ($ret: expr) => { $ret.map_err(|e| e.into_fs_error())? }; } impl INode for HNode { fn read_at(&self, offset: usize, buf: &mut [u8]) -> Result<usize> { let mut guard = self.open_file()?; let file = guard.as_mut().unwrap(); try_std!(file.seek(SeekFrom::Start(offset as u64))); let len = try_std!(file.read(buf)); Ok(len) } fn write_at(&self, offset: usize, buf: &[u8]) -> Result<usize> { let mut guard = self.open_file()?; let file = guard.as_mut().unwrap(); try_std!(file.seek(SeekFrom::Start(offset as u64))); let len = try_std!(file.write(buf)); Ok(len) } fn poll(&self) -> Result<PollStatus> { let metadata = try_std!(self.path.metadata()); if !metadata.is_file() { return Err(FsError::NotFile); } Ok(PollStatus { read: true, write: !metadata.permissions().readonly(), error: false, }) } fn metadata(&self) -> Result<Metadata> { let metadata = try_std!(self.path.metadata()); Ok(metadata.into_fs_metadata()) } fn set_metadata(&self, metadata: &Metadata) -> Result<()> { warn!("HostFS: set_metadata() is unimplemented"); Ok(()) } fn sync_all(&self) -> Result<()> { let mut guard = self.open_file()?; let file = guard.as_mut().unwrap(); try_std!(file.sync_all()); Ok(()) } fn sync_data(&self) -> Result<()> { let mut guard = self.open_file()?; let file = guard.as_mut().unwrap(); try_std!(file.sync_data()); Ok(()) } fn resize(&self, len: usize) -> Result<()> { let mut guard = self.open_file()?; let file = guard.as_mut().unwrap(); try_std!(file.set_len(len as u64)); Ok(()) } fn create(&self, name: &str, type_: FileType, mode: u32) -> Result<Arc<dyn INode>> { let new_path = self.path.join(name); if new_path.exists() { return Err(FsError::EntryExist); } match type_ { FileType::File => { try_std!(fs::File::create(&new_path)); } FileType::Dir => { try_std!(fs::create_dir(&new_path)); } _ => { warn!("only support creating regular file or directory in HostFS"); return Err(FsError::PermError); } } Ok(Arc::new(HNode { path: new_path, file: Mutex::new(None), fs: self.fs.clone(), })) } fn link(&self, name: &str, other: &Arc<dyn INode>) -> Result<()> { let other = other.downcast_ref::<Self>().ok_or(FsError::NotSameFs)?; try_std!(fs::hard_link(&other.path, &self.path.join(name))); Ok(()) } fn unlink(&self, name: &str) -> Result<()> { let new_path = self.path.join(name); if new_path.is_file() { try_std!(fs::remove_file(new_path)); } else if new_path.is_dir() { try_std!(fs::remove_dir(new_path)); } else { return Err(FsError::EntryNotFound); } Ok(()) } fn move_(&self, old_name: &str, target: &Arc<dyn INode>, new_name: &str) -> Result<()> { let old_path = self.path.join(old_name); let new_path = { let target = target.downcast_ref::<Self>().ok_or(FsError::NotSameFs)?; target.path.join(new_name) }; try_std!(fs::rename(&old_path, &new_path)); Ok(()) } fn find(&self, name: &str) -> Result<Arc<dyn INode>> { let new_path = self.path.join(name); if !new_path.exists() { return Err(FsError::EntryNotFound); } Ok(Arc::new(HNode { path: new_path, file: Mutex::new(None), fs: self.fs.clone(), })) } fn get_entry(&self, id: usize) -> Result<String> { if !self.path.is_dir() { return Err(FsError::NotDir); } if let Some(entry) = try_std!(self.path.read_dir()).nth(id) { try_std!(entry) .file_name() .into_string() .map_err(|_| FsError::InvalidParam) } else { return Err(FsError::EntryNotFound); } } fn iterate_entries(&self, ctx: &mut DirentWriterContext) -> Result<usize> { if !self.path.is_dir() { return Err(FsError::NotDir); } let idx = ctx.pos(); let mut total_written_len = 0; for entry in try_std!(self.path.read_dir()).skip(idx) { let entry = try_std!(entry); let written_len = match ctx.write_entry( &entry .file_name() .into_string() .map_err(|_| FsError::InvalidParam)?, entry.ino(), entry .file_type() .map_err(|_| FsError::InvalidParam)? .into_fs_filetype(), ) { Ok(written_len) => written_len, Err(e) => { if total_written_len == 0 { return Err(e); } else { break; } } }; total_written_len += written_len; } Ok(total_written_len) } fn io_control(&self, cmd: u32, data: usize) -> Result<()> { warn!("HostFS: io_control is unimplemented"); Ok(()) } fn fs(&self) -> Arc<dyn FileSystem> { self.fs.clone() } fn as_any_ref(&self) -> &dyn Any { self } } impl HNode { /// Ensure to open the file and store a `File` into `self.file`, /// return the `MutexGuard`. /// If the type of `self.path` is not file, then return Err fn open_file(&self) -> Result<MutexGuard<Option<fs::File>>> { if !self.path.exists() { return Err(FsError::EntryNotFound); } if !self.path.is_file() { return Err(FsError::NotFile); } let mut maybe_file = self.file.lock().unwrap(); if maybe_file.is_none() { let file = try_std!(fs::OpenOptions::new() .read(true) .write(true) .create(true) .open(&self.path)); *maybe_file = Some(file); } Ok(maybe_file) } } trait IntoFsError { fn into_fs_error(self) -> FsError; } impl IntoFsError for std::io::Error { fn into_fs_error(self) -> FsError { use std::io::ErrorKind; match self.kind() { ErrorKind::NotFound => FsError::EntryNotFound, ErrorKind::AlreadyExists => FsError::EntryExist, ErrorKind::WouldBlock => FsError::Again, ErrorKind::InvalidInput => FsError::InvalidParam, ErrorKind::InvalidData => FsError::InvalidParam, _ => FsError::NotSupported, } } } trait IntoFsFileType { fn into_fs_filetype(self) -> FileType; } impl IntoFsFileType for fs::FileType { fn into_fs_filetype(self) -> FileType { if self.is_dir() { FileType::Dir } else if self.is_file() { FileType::File } else if self.is_symlink() { FileType::SymLink } else if self.is_block_device() { FileType::BlockDevice } else if self.is_char_device() { FileType::CharDevice } else if self.is_fifo() { FileType::NamedPipe } else if self.is_socket() { FileType::Socket } else { unimplemented!("unknown file type") } } } trait IntoFsMetadata { fn into_fs_metadata(self) -> Metadata; } impl IntoFsMetadata for fs::Metadata { fn into_fs_metadata(self) -> Metadata { use sgx_trts::libc; use std::os::fs::MetadataExt; Metadata { dev: self.st_dev() as usize, inode: self.st_ino() as usize, size: self.st_size() as usize, blk_size: self.st_blksize() as usize, blocks: self.st_blocks() as usize, atime: Timespec { sec: self.st_atime(), nsec: self.st_atime_nsec() as i32, }, mtime: Timespec { sec: self.st_mtime(), nsec: self.st_mtime_nsec() as i32, }, ctime: Timespec { sec: self.st_ctime(), nsec: self.st_ctime_nsec() as i32, }, type_: match self.st_mode() & 0xf000 { libc::S_IFCHR => FileType::CharDevice, libc::S_IFBLK => FileType::BlockDevice, libc::S_IFDIR => FileType::Dir, libc::S_IFREG => FileType::File, libc::S_IFLNK => FileType::SymLink, libc::S_IFSOCK => FileType::Socket, _ => unimplemented!("unknown file type"), }, mode: self.st_mode() as u16 & 0o777, nlinks: self.st_nlink() as usize, uid: self.st_uid() as usize, gid: self.st_gid() as usize, rdev: self.st_rdev() as usize, } } }
29.841823
92
0.511454
7979a8e673c62eca07f2f28bce0a4f7ea8d58936
55,362
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. use epoll; use std::cmp; use std::convert::From; use std::fs::File; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::os::linux::fs::MetadataExt; use std::os::unix::io::{AsRawFd, RawFd}; use std::result; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc; use std::sync::Arc; use logger::{Metric, METRICS}; use memory_model::{DataInit, GuestAddress, GuestMemory, GuestMemoryError}; use rate_limiter::{RateLimiter, TokenType}; use utils::eventfd::EventFd; use virtio_gen::virtio_blk::*; use super::{ ActivateError, ActivateResult, DescriptorChain, EpollConfigConstructor, Queue, VirtioDevice, TYPE_BLOCK, VIRTIO_MMIO_INT_VRING, }; use crate::{DeviceEventT, EpollHandler, Error as DeviceError}; const CONFIG_SPACE_SIZE: usize = 8; const SECTOR_SHIFT: u8 = 9; pub const SECTOR_SIZE: u64 = (0x01 as u64) << SECTOR_SHIFT; const QUEUE_SIZE: u16 = 256; const NUM_QUEUES: usize = 1; const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE]; // New descriptors are pending on the virtio queue. const QUEUE_AVAIL_EVENT: DeviceEventT = 0; // Rate limiter budget is now available. const RATE_LIMITER_EVENT: DeviceEventT = 1; // Number of DeviceEventT events supported by this implementation. pub const BLOCK_EVENTS_COUNT: usize = 2; #[derive(Debug)] enum Error { /// Guest gave us bad memory addresses. GuestMemory(GuestMemoryError), /// Guest gave us a write only descriptor that protocol says to read from. UnexpectedWriteOnlyDescriptor, /// Guest gave us a read only descriptor that protocol says to write to. UnexpectedReadOnlyDescriptor, /// Guest gave us too few descriptors in a descriptor chain. DescriptorChainTooShort, /// Guest gave us a descriptor that was too short to use. DescriptorLengthTooSmall, /// Getting a block's metadata fails for any reason. GetFileMetadata, /// The requested operation would cause a seek beyond disk end. InvalidOffset, } #[derive(Debug)] enum ExecuteError { BadRequest(Error), Flush(io::Error), Read(GuestMemoryError), Seek(io::Error), Write(GuestMemoryError), Unsupported(u32), } impl ExecuteError { fn status(&self) -> u32 { match *self { ExecuteError::BadRequest(_) => VIRTIO_BLK_S_IOERR, ExecuteError::Flush(_) => VIRTIO_BLK_S_IOERR, ExecuteError::Read(_) => VIRTIO_BLK_S_IOERR, ExecuteError::Seek(_) => VIRTIO_BLK_S_IOERR, ExecuteError::Write(_) => VIRTIO_BLK_S_IOERR, ExecuteError::Unsupported(_) => VIRTIO_BLK_S_UNSUPP, } } } #[derive(Clone, Copy, Debug, PartialEq)] enum RequestType { In, Out, Flush, GetDeviceID, Unsupported(u32), } impl From<u32> for RequestType { fn from(value: u32) -> Self { match value { VIRTIO_BLK_T_IN => RequestType::In, VIRTIO_BLK_T_OUT => RequestType::Out, VIRTIO_BLK_T_FLUSH => RequestType::Flush, VIRTIO_BLK_T_GET_ID => RequestType::GetDeviceID, t => RequestType::Unsupported(t), } } } fn build_device_id(disk_image: &File) -> result::Result<String, Error> { let blk_metadata = match disk_image.metadata() { Err(_) => return Err(Error::GetFileMetadata), Ok(m) => m, }; // This is how kvmtool does it. let device_id = format!( "{}{}{}", blk_metadata.st_dev(), blk_metadata.st_rdev(), blk_metadata.st_ino() ) .to_owned(); Ok(device_id) } fn build_disk_image_id(disk_image: &File) -> Vec<u8> { let mut default_disk_image_id = vec![0; VIRTIO_BLK_ID_BYTES as usize]; match build_device_id(disk_image) { Err(_) => { warn!("Could not generate device id. We'll use a default."); } Ok(m) => { // The kernel only knows to read a maximum of VIRTIO_BLK_ID_BYTES. // This will also zero out any leftover bytes. let disk_id = m.as_bytes(); let bytes_to_copy = cmp::min(disk_id.len(), VIRTIO_BLK_ID_BYTES as usize); default_disk_image_id[..bytes_to_copy].clone_from_slice(&disk_id[..bytes_to_copy]) } } default_disk_image_id } struct Request { request_type: RequestType, sector: u64, data_addr: GuestAddress, data_len: u32, status_addr: GuestAddress, } /// The request header represents the mandatory fields of each block device request. /// /// A request header contains the following fields: /// * request_type: an u32 value mapping to a read, write or flush operation. /// * reserved: 32 bits are reserved for future extensions of the Virtio Spec. /// * sector: an u64 value representing the offset where a read/write is to occur. /// /// The header simplifies reading the request from memory as all request follow /// the same memory layout. #[derive(Copy, Clone)] #[repr(C)] struct RequestHeader { request_type: u32, _reserved: u32, sector: u64, } // Safe because RequestHeader only contains plain data. unsafe impl DataInit for RequestHeader {} impl RequestHeader { /// Reads the request header from GuestMemory starting at `addr`. /// /// Virtio 1.0 specifies that the data is transmitted by the driver in little-endian /// format. Firecracker currently runs only on little endian platforms so we don't /// need to do an explicit little endian read as all reads are little endian by default. /// When running on a big endian platform, this code should not compile, and support /// for explicit little endian reads is required. #[cfg(target_endian = "little")] fn read_from(memory: &GuestMemory, addr: GuestAddress) -> result::Result<Self, Error> { let request_header: RequestHeader = memory .read_obj_from_addr(addr) .map_err(Error::GuestMemory)?; Ok(request_header) } } impl Request { fn parse(avail_desc: &DescriptorChain, mem: &GuestMemory) -> result::Result<Request, Error> { // The head contains the request type which MUST be readable. if avail_desc.is_write_only() { return Err(Error::UnexpectedWriteOnlyDescriptor); } let request_header = RequestHeader::read_from(mem, avail_desc.addr)?; let mut req = Request { request_type: RequestType::from(request_header.request_type), sector: request_header.sector, data_addr: GuestAddress(0), data_len: 0, status_addr: GuestAddress(0), }; let data_desc; let status_desc; let desc = avail_desc .next_descriptor() .ok_or(Error::DescriptorChainTooShort)?; if !desc.has_next() { status_desc = desc; // Only flush requests are allowed to skip the data descriptor. if req.request_type != RequestType::Flush { return Err(Error::DescriptorChainTooShort); } } else { data_desc = desc; status_desc = data_desc .next_descriptor() .ok_or(Error::DescriptorChainTooShort)?; if data_desc.is_write_only() && req.request_type == RequestType::Out { return Err(Error::UnexpectedWriteOnlyDescriptor); } if !data_desc.is_write_only() && req.request_type == RequestType::In { return Err(Error::UnexpectedReadOnlyDescriptor); } if !data_desc.is_write_only() && req.request_type == RequestType::GetDeviceID { return Err(Error::UnexpectedReadOnlyDescriptor); } req.data_addr = data_desc.addr; req.data_len = data_desc.len; } // The status MUST always be writable. if !status_desc.is_write_only() { return Err(Error::UnexpectedReadOnlyDescriptor); } if status_desc.len < 1 { return Err(Error::DescriptorLengthTooSmall); } req.status_addr = status_desc.addr; Ok(req) } fn execute<T: Seek + Read + Write>( &self, disk: &mut T, disk_nsectors: u64, mem: &GuestMemory, disk_id: &[u8], ) -> result::Result<u32, ExecuteError> { let mut top: u64 = u64::from(self.data_len) / SECTOR_SIZE; if u64::from(self.data_len) % SECTOR_SIZE != 0 { top += 1; } top = top .checked_add(self.sector) .ok_or(ExecuteError::BadRequest(Error::InvalidOffset))?; if top > disk_nsectors { return Err(ExecuteError::BadRequest(Error::InvalidOffset)); } disk.seek(SeekFrom::Start(self.sector << SECTOR_SHIFT)) .map_err(ExecuteError::Seek)?; match self.request_type { RequestType::In => { mem.read_to_memory(self.data_addr, disk, self.data_len as usize) .map_err(ExecuteError::Read)?; METRICS.block.read_bytes.add(self.data_len as usize); METRICS.block.read_count.inc(); return Ok(self.data_len); } RequestType::Out => { mem.write_from_memory(self.data_addr, disk, self.data_len as usize) .map_err(ExecuteError::Write)?; METRICS.block.write_bytes.add(self.data_len as usize); METRICS.block.write_count.inc(); } RequestType::Flush => match disk.flush() { Ok(_) => { METRICS.block.flush_count.inc(); return Ok(0); } Err(e) => return Err(ExecuteError::Flush(e)), }, RequestType::GetDeviceID => { if (self.data_len as usize) < disk_id.len() { return Err(ExecuteError::BadRequest(Error::InvalidOffset)); } mem.write_slice_at_addr(disk_id, self.data_addr) .map_err(ExecuteError::Write)?; } RequestType::Unsupported(t) => return Err(ExecuteError::Unsupported(t)), }; Ok(0) } } /// Handler that drives the execution of the Block devices pub struct BlockEpollHandler { queues: Vec<Queue>, mem: GuestMemory, disk_image: File, disk_nsectors: u64, interrupt_status: Arc<AtomicUsize>, interrupt_evt: EventFd, queue_evt: EventFd, rate_limiter: RateLimiter, disk_image_id: Vec<u8>, } impl BlockEpollHandler { fn process_queue(&mut self, queue_index: usize) -> bool { let queue = &mut self.queues[queue_index]; let mut used_any = false; while let Some(head) = queue.pop(&self.mem) { let len; match Request::parse(&head, &self.mem) { Ok(request) => { // If limiter.consume() fails it means there is no more TokenType::Ops // budget and rate limiting is in effect. if !self.rate_limiter.consume(1, TokenType::Ops) { // Stop processing the queue and return this descriptor chain to the // avail ring, for later processing. queue.undo_pop(); break; } // Exercise the rate limiter only if this request is of data transfer type. if request.request_type == RequestType::In || request.request_type == RequestType::Out { // If limiter.consume() fails it means there is no more TokenType::Bytes // budget and rate limiting is in effect. if !self .rate_limiter .consume(u64::from(request.data_len), TokenType::Bytes) { // Revert the OPS consume(). self.rate_limiter.manual_replenish(1, TokenType::Ops); // Stop processing the queue and return this descriptor chain to the // avail ring, for later processing. queue.undo_pop(); break; } } let status = match request.execute( &mut self.disk_image, self.disk_nsectors, &self.mem, &self.disk_image_id, ) { Ok(l) => { len = l; VIRTIO_BLK_S_OK } Err(e) => { error!("Failed to execute request: {:?}", e); METRICS.block.invalid_reqs_count.inc(); len = 1; // We need at least 1 byte for the status. e.status() } }; // We use unwrap because the request parsing process already checked that the // status_addr was valid. self.mem .write_obj_at_addr(status, request.status_addr) .unwrap(); } Err(e) => { error!("Failed to parse available descriptor chain: {:?}", e); METRICS.block.execute_fails.inc(); len = 0; } } queue.add_used(&self.mem, head.index, len); used_any = true; } used_any } fn signal_used_queue(&self) -> result::Result<(), DeviceError> { self.interrupt_status .fetch_or(VIRTIO_MMIO_INT_VRING as usize, Ordering::SeqCst); self.interrupt_evt.write(1).map_err(|e| { error!("Failed to signal used queue: {:?}", e); METRICS.block.event_fails.inc(); DeviceError::FailedSignalingUsedQueue(e) }) } /// Update the backing file for the Block device pub fn update_disk_image(&mut self, disk_image: File) -> result::Result<(), DeviceError> { self.disk_image = disk_image; self.disk_nsectors = self .disk_image .seek(SeekFrom::End(0)) .map_err(DeviceError::IoError)? / SECTOR_SIZE; self.disk_image_id = build_disk_image_id(&self.disk_image); METRICS.block.update_count.inc(); Ok(()) } } impl EpollHandler for BlockEpollHandler { fn handle_event( &mut self, device_event: DeviceEventT, _evset: epoll::Events, ) -> result::Result<(), DeviceError> { match device_event { QUEUE_AVAIL_EVENT => { METRICS.block.queue_event_count.inc(); if let Err(e) = self.queue_evt.read() { error!("Failed to get queue event: {:?}", e); METRICS.block.event_fails.inc(); Err(DeviceError::FailedReadingQueue { event_type: "queue event", underlying: e, }) } else if !self.rate_limiter.is_blocked() && self.process_queue(0) { self.signal_used_queue() } else { // While limiter is blocked, don't process any more requests. Ok(()) } } RATE_LIMITER_EVENT => { METRICS.block.rate_limiter_event_count.inc(); // Upon rate limiter event, call the rate limiter handler // and restart processing the queue. if self.rate_limiter.event_handler().is_ok() && self.process_queue(0) { self.signal_used_queue() } else { Ok(()) } } unknown => Err(DeviceError::UnknownEvent { device: "block", event: unknown, }), } } } pub struct EpollConfig { q_avail_token: u64, rate_limiter_token: u64, epoll_raw_fd: RawFd, sender: mpsc::Sender<Box<dyn EpollHandler>>, } impl EpollConfigConstructor for EpollConfig { fn new( first_token: u64, epoll_raw_fd: RawFd, sender: mpsc::Sender<Box<dyn EpollHandler>>, ) -> Self { EpollConfig { q_avail_token: first_token + u64::from(QUEUE_AVAIL_EVENT), rate_limiter_token: first_token + u64::from(RATE_LIMITER_EVENT), epoll_raw_fd, sender, } } } /// Virtio device for exposing block level read/write operations on a host file. pub struct Block { disk_image: Option<File>, disk_nsectors: u64, avail_features: u64, acked_features: u64, config_space: Vec<u8>, epoll_config: EpollConfig, rate_limiter: Option<RateLimiter>, } pub fn build_config_space(disk_size: u64) -> Vec<u8> { // We only support disk size, which uses the first two words of the configuration space. // If the image is not a multiple of the sector size, the tail bits are not exposed. // The config space is little endian. let mut config = Vec::with_capacity(CONFIG_SPACE_SIZE); let num_sectors = disk_size >> SECTOR_SHIFT; for i in 0..8 { config.push((num_sectors >> (8 * i)) as u8); } config } impl Block { /// Create a new virtio block device that operates on the given file. /// /// The given file must be seekable and sizable. pub fn new( mut disk_image: File, is_disk_read_only: bool, epoll_config: EpollConfig, rate_limiter: Option<RateLimiter>, ) -> io::Result<Block> { let disk_size = disk_image.seek(SeekFrom::End(0))? as u64; if disk_size % SECTOR_SIZE != 0 { warn!( "Disk size {} is not a multiple of sector size {}; \ the remainder will not be visible to the guest.", disk_size, SECTOR_SIZE ); } let mut avail_features = (1u64 << VIRTIO_F_VERSION_1) | (1u64 << VIRTIO_BLK_F_FLUSH); if is_disk_read_only { avail_features |= 1u64 << VIRTIO_BLK_F_RO; }; Ok(Block { disk_image: Some(disk_image), disk_nsectors: disk_size / SECTOR_SIZE, avail_features, acked_features: 0u64, config_space: build_config_space(disk_size), epoll_config, rate_limiter, }) } } impl VirtioDevice for Block { fn device_type(&self) -> u32 { TYPE_BLOCK } fn queue_max_sizes(&self) -> &[u16] { QUEUE_SIZES } fn avail_features(&self) -> u64 { self.avail_features } fn acked_features(&self) -> u64 { self.acked_features } fn set_acked_features(&mut self, acked_features: u64) { self.acked_features = acked_features; } fn read_config(&self, offset: u64, mut data: &mut [u8]) { let config_len = self.config_space.len() as u64; if offset >= config_len { error!("Failed to read config space"); METRICS.block.cfg_fails.inc(); return; } if let Some(end) = offset.checked_add(data.len() as u64) { // This write can't fail, offset and end are checked against config_len. data.write_all(&self.config_space[offset as usize..cmp::min(end, config_len) as usize]) .unwrap(); } } fn write_config(&mut self, offset: u64, data: &[u8]) { let data_len = data.len() as u64; let config_len = self.config_space.len() as u64; if offset + data_len > config_len { error!("Failed to write config space"); METRICS.block.cfg_fails.inc(); return; } let (_, right) = self.config_space.split_at_mut(offset as usize); right.copy_from_slice(&data[..]); } fn activate( &mut self, mem: GuestMemory, interrupt_evt: EventFd, status: Arc<AtomicUsize>, queues: Vec<Queue>, mut queue_evts: Vec<EventFd>, ) -> ActivateResult { if queues.len() != NUM_QUEUES || queue_evts.len() != NUM_QUEUES { error!( "Cannot perform activate. Expected {} queue(s), got {}", NUM_QUEUES, queues.len() ); METRICS.block.activate_fails.inc(); return Err(ActivateError::BadActivate); } if let Some(disk_image) = self.disk_image.take() { let queue_evt = queue_evts.remove(0); let queue_evt_raw_fd = queue_evt.as_raw_fd(); let disk_image_id = build_disk_image_id(&disk_image); let handler = BlockEpollHandler { queues, mem, disk_image, disk_nsectors: self.disk_nsectors, interrupt_status: status, interrupt_evt, queue_evt, rate_limiter: self.rate_limiter.take().unwrap_or_default(), disk_image_id, }; let rate_limiter_rawfd = handler.rate_limiter.as_raw_fd(); // The channel should be open at this point. self.epoll_config .sender .send(Box::new(handler)) .expect("Failed to send through the channel"); //TODO: barrier needed here by any chance? epoll::ctl( self.epoll_config.epoll_raw_fd, epoll::ControlOptions::EPOLL_CTL_ADD, queue_evt_raw_fd, epoll::Event::new(epoll::Events::EPOLLIN, self.epoll_config.q_avail_token), ) .map_err(|e| { METRICS.block.activate_fails.inc(); ActivateError::EpollCtl(e) })?; if rate_limiter_rawfd != -1 { epoll::ctl( self.epoll_config.epoll_raw_fd, epoll::ControlOptions::EPOLL_CTL_ADD, rate_limiter_rawfd, epoll::Event::new(epoll::Events::EPOLLIN, self.epoll_config.rate_limiter_token), ) .map_err(|e| { METRICS.block.activate_fails.inc(); ActivateError::EpollCtl(e) })?; } return Ok(()); } METRICS.block.activate_fails.inc(); Err(ActivateError::BadActivate) } } #[cfg(test)] mod tests { extern crate tempfile; use self::tempfile::{tempfile, NamedTempFile}; use super::*; use libc; use memory_model::Address; use std::fs::{metadata, OpenOptions}; use std::sync::mpsc::Receiver; use std::thread; use std::time::Duration; use std::u32; use crate::virtio::queue::tests::*; const EPOLLIN: epoll::Events = epoll::Events::EPOLLIN; /// Will read $metric, run the code in $block, then assert metric has increased by $delta. macro_rules! check_metric_after_block { ($metric:expr, $delta:expr, $block:expr) => {{ let before = $metric.count(); let _ = $block; assert_eq!($metric.count(), before + $delta, "unexpected metric value"); }}; } impl BlockEpollHandler { fn set_queue(&mut self, idx: usize, q: Queue) { self.queues[idx] = q; } fn get_rate_limiter(&self) -> &RateLimiter { &self.rate_limiter } fn set_rate_limiter(&mut self, rate_limiter: RateLimiter) { self.rate_limiter = rate_limiter; } } struct DummyBlock { block: Block, epoll_raw_fd: i32, _receiver: Receiver<Box<dyn EpollHandler>>, } impl DummyBlock { fn new(is_disk_read_only: bool) -> Self { let epoll_raw_fd = epoll::create(true).unwrap(); let (sender, _receiver) = mpsc::channel(); let epoll_config = EpollConfig::new(0, epoll_raw_fd, sender); let f: File = tempfile().unwrap(); f.set_len(0x1000).unwrap(); // Rate limiting is enabled but with a high operation rate (10 million ops/s). let rate_limiter = RateLimiter::new(0, None, 0, 100_000, None, 10).unwrap(); DummyBlock { block: Block::new(f, is_disk_read_only, epoll_config, Some(rate_limiter)).unwrap(), epoll_raw_fd, _receiver, } } fn block(&mut self) -> &mut Block { &mut self.block } } impl Drop for DummyBlock { fn drop(&mut self) { unsafe { libc::close(self.epoll_raw_fd) }; } } fn default_test_blockepollhandler(mem: &GuestMemory) -> (BlockEpollHandler, VirtQueue) { let mut dummy = DummyBlock::new(false); let b = dummy.block(); let vq = VirtQueue::new(GuestAddress(0), &mem, 16); assert!(vq.end().0 < 0x1000); let queues = vec![vq.create_queue()]; let mut disk_image = b.disk_image.take().unwrap(); let disk_nsectors = disk_image.seek(SeekFrom::End(0)).unwrap() / SECTOR_SIZE; let status = Arc::new(AtomicUsize::new(0)); let interrupt_evt = EventFd::new(libc::EFD_NONBLOCK).unwrap(); let queue_evt = EventFd::new(libc::EFD_NONBLOCK).unwrap(); let disk_image_id_str = build_device_id(&disk_image).unwrap(); let mut disk_image_id = vec![0; VIRTIO_BLK_ID_BYTES as usize]; let disk_image_id_bytes = disk_image_id_str.as_bytes(); let bytes_to_copy = cmp::min(disk_image_id_bytes.len(), VIRTIO_BLK_ID_BYTES as usize); disk_image_id[..bytes_to_copy].clone_from_slice(&disk_image_id_bytes[..bytes_to_copy]); ( BlockEpollHandler { queues, mem: mem.clone(), disk_image, disk_nsectors, interrupt_status: status, interrupt_evt, queue_evt, rate_limiter: RateLimiter::default(), disk_image_id, }, vq, ) } // Helper function for varying the parameters of the function activating a block device. fn activate_block_with_modifiers( b: &mut Block, bad_qlen: bool, bad_evtlen: bool, ) -> ActivateResult { let m = GuestMemory::new(&[(GuestAddress(0), 0x1000)]).unwrap(); let ievt = EventFd::new(libc::EFD_NONBLOCK).unwrap(); let stat = Arc::new(AtomicUsize::new(0)); let vq = VirtQueue::new(GuestAddress(0), &m, 16); let mut queues = vec![vq.create_queue()]; let mut queue_evts = vec![EventFd::new(libc::EFD_NONBLOCK).unwrap()]; // Invalidate queues list to test this failure case. if bad_qlen { queues.pop(); } // Invalidate queue-events list to test this failure case. if bad_evtlen { queue_evts.pop(); } b.activate(m.clone(), ievt, stat, queues, queue_evts) } fn invoke_handler_for_queue_event(h: &mut BlockEpollHandler) { // leave at least one event here so that reading it later won't block h.interrupt_evt.write(1).unwrap(); // trigger the queue event h.queue_evt.write(1).unwrap(); // handle event h.handle_event(QUEUE_AVAIL_EVENT, EPOLLIN).unwrap(); // validate the queue operation finished successfully assert_eq!(h.interrupt_evt.read().unwrap(), 2); } // Writes at address 0x0 the request_type, reserved, sector. fn write_request_header(mem: &GuestMemory, request_type: u32, sector: u64) { let addr = GuestAddress(0); mem.write_obj_at_addr::<u32>(request_type, addr).unwrap(); mem.write_obj_at_addr::<u64>(sector, addr.checked_add(8).unwrap()) .unwrap(); } #[test] fn test_read_request_header() { let mem = GuestMemory::new(&[(GuestAddress(0), 0x1000)]).unwrap(); let addr = GuestAddress(0); let sector = 123_454_321; // Test that all supported request types are read correctly from memory. let supported_request_types = vec![ VIRTIO_BLK_T_IN, VIRTIO_BLK_T_OUT, VIRTIO_BLK_T_FLUSH, VIRTIO_BLK_T_GET_ID, ]; for request_type in supported_request_types { write_request_header(&mem, request_type, sector); let request_header = RequestHeader::read_from(&mem, addr).unwrap(); assert_eq!(request_header.request_type, request_type); assert_eq!(request_header.sector, sector); } // Test that trying to read a request header that goes outside of the // memory boundary fails. assert!(RequestHeader::read_from(&mem, GuestAddress(0x1000)).is_err()); } #[test] fn test_request_type_from() { assert_eq!(RequestType::from(VIRTIO_BLK_T_IN), RequestType::In); assert_eq!(RequestType::from(VIRTIO_BLK_T_OUT), RequestType::Out); assert_eq!(RequestType::from(VIRTIO_BLK_T_FLUSH), RequestType::Flush); assert_eq!( RequestType::from(VIRTIO_BLK_T_GET_ID), RequestType::GetDeviceID ); assert_eq!(RequestType::from(42), RequestType::Unsupported(42)); } #[test] fn test_parse() { let m = &GuestMemory::new(&[(GuestAddress(0), 0x10000)]).unwrap(); let vq = VirtQueue::new(GuestAddress(0), &m, 16); assert!(vq.end().0 < 0x1000); vq.avail.ring[0].set(0); vq.avail.idx.set(1); { let mut q = vq.create_queue(); // write only request type descriptor vq.dtable[0].set(0x1000, 0x1000, VIRTQ_DESC_F_WRITE, 1); m.write_obj_at_addr::<u32>(VIRTIO_BLK_T_OUT, GuestAddress(0x1000)) .unwrap(); m.write_obj_at_addr::<u64>(114, GuestAddress(0x1000 + 8)) .unwrap(); assert!(match Request::parse(&q.pop(m).unwrap(), m) { Err(Error::UnexpectedWriteOnlyDescriptor) => true, _ => false, }); } { let mut q = vq.create_queue(); // chain too short; no data_desc vq.dtable[0].flags.set(0); assert!(match Request::parse(&q.pop(m).unwrap(), m) { Err(Error::DescriptorChainTooShort) => true, _ => false, }); } { let mut q = vq.create_queue(); // chain too short; no status desc vq.dtable[0].flags.set(VIRTQ_DESC_F_NEXT); vq.dtable[1].set(0x2000, 0x1000, 0, 2); assert!(match Request::parse(&q.pop(m).unwrap(), m) { Err(Error::DescriptorChainTooShort) => true, _ => false, }); } { let mut q = vq.create_queue(); // write only data for OUT vq.dtable[1] .flags .set(VIRTQ_DESC_F_NEXT | VIRTQ_DESC_F_WRITE); vq.dtable[2].set(0x3000, 0, 0, 0); assert!(match Request::parse(&q.pop(m).unwrap(), m) { Err(Error::UnexpectedWriteOnlyDescriptor) => true, _ => false, }); } { let mut q = vq.create_queue(); // read only data for IN m.write_obj_at_addr::<u32>(VIRTIO_BLK_T_IN, GuestAddress(0x1000)) .unwrap(); vq.dtable[1].flags.set(VIRTQ_DESC_F_NEXT); assert!(match Request::parse(&q.pop(m).unwrap(), m) { Err(Error::UnexpectedReadOnlyDescriptor) => true, _ => false, }); } { let mut q = vq.create_queue(); // status desc not writable vq.dtable[1] .flags .set(VIRTQ_DESC_F_NEXT | VIRTQ_DESC_F_WRITE); assert!(match Request::parse(&q.pop(m).unwrap(), m) { Err(Error::UnexpectedReadOnlyDescriptor) => true, _ => false, }); } { let mut q = vq.create_queue(); // status desc too small vq.dtable[2].flags.set(VIRTQ_DESC_F_WRITE); assert!(match Request::parse(&q.pop(m).unwrap(), m) { Err(Error::DescriptorLengthTooSmall) => true, _ => false, }); } { let mut q = vq.create_queue(); // should be OK now vq.dtable[2].len.set(0x1000); let r = Request::parse(&q.pop(m).unwrap(), m).unwrap(); assert_eq!(r.request_type, RequestType::In); assert_eq!(r.sector, 114); assert_eq!(r.data_addr, GuestAddress(0x2000)); assert_eq!(r.data_len, 0x1000); assert_eq!(r.status_addr, GuestAddress(0x3000)); } } #[test] #[allow(clippy::cognitive_complexity)] fn test_virtio_device() { let mut dummy = DummyBlock::new(true); let b = dummy.block(); // Test `device_type()`. { assert_eq!(b.device_type(), TYPE_BLOCK); } // Test `queue_max_sizes()`. { let x = b.queue_max_sizes(); assert_eq!(x, QUEUE_SIZES); // power of 2? for &y in x { assert!(y > 0 && y & (y - 1) == 0); } } // Test `read_config()`. { let mut num_sectors = [0u8; 4]; b.read_config(0, &mut num_sectors); // size is 0x1000, so num_sectors is 8 (4096/512). assert_eq!([0x08, 0x00, 0x00, 0x00], num_sectors); let mut msw_sectors = [0u8; 4]; b.read_config(4, &mut msw_sectors); // size is 0x1000, so msw_sectors is 0. assert_eq!([0x00, 0x00, 0x00, 0x00], msw_sectors); // Invalid read. num_sectors = [0xd, 0xe, 0xa, 0xd]; check_metric_after_block!( &METRICS.block.cfg_fails, 1, b.read_config(CONFIG_SPACE_SIZE as u64 + 1, &mut num_sectors) ); // Validate read failed. assert_eq!(num_sectors, [0xd, 0xe, 0xa, 0xd]); } // Test `features()` and `ack_features()`. { let features: u64 = (1u64 << VIRTIO_BLK_F_RO) | (1u64 << VIRTIO_F_VERSION_1) | (1u64 << VIRTIO_BLK_F_FLUSH); assert_eq!(b.avail_features_by_page(0), features as u32); assert_eq!(b.avail_features_by_page(1), (features >> 32) as u32); for i in 2..10 { assert_eq!(b.avail_features_by_page(i), 0u32); } for i in 0..10 { b.ack_features_by_page(i, u32::MAX); } assert_eq!(b.acked_features, features); } // Test `activate()`. { // It should fail when not enough queues and/or evts are provided. check_metric_after_block!( &METRICS.block.activate_fails, 1, assert!(match activate_block_with_modifiers(b, true, false) { Err(ActivateError::BadActivate) => true, _ => false, }) ); check_metric_after_block!( &METRICS.block.activate_fails, 1, assert!(match activate_block_with_modifiers(b, false, true) { Err(ActivateError::BadActivate) => true, _ => false, }) ); check_metric_after_block!( &METRICS.block.activate_fails, 1, assert!(match activate_block_with_modifiers(b, true, true) { Err(ActivateError::BadActivate) => true, _ => false, }) ); // Otherwise, it should be ok. assert!(activate_block_with_modifiers(b, false, false).is_ok()); // Second activate shouldn't be ok anymore. check_metric_after_block!( &METRICS.block.activate_fails, 1, assert!(match activate_block_with_modifiers(b, false, false) { Err(ActivateError::BadActivate) => true, _ => false, }) ); } // Test `write_config()`. { let new_config: [u8; 8] = [0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; b.write_config(0, &new_config); let mut new_config_read = [0u8; 8]; b.read_config(0, &mut new_config_read); assert_eq!(new_config, new_config_read); // Invalid write. check_metric_after_block!(&METRICS.block.cfg_fails, 1, b.write_config(5, &new_config)); // Make sure nothing got written. new_config_read = [0u8; 8]; b.read_config(0, &mut new_config_read); assert_eq!(new_config, new_config_read); } } #[test] fn test_invalid_event_handler() { let m = GuestMemory::new(&[(GuestAddress(0), 0x10000)]).unwrap(); let (mut h, _vq) = default_test_blockepollhandler(&m); let r = h.handle_event(BLOCK_EVENTS_COUNT as DeviceEventT, EPOLLIN); match r { Err(DeviceError::UnknownEvent { event, device }) => { assert_eq!(event, BLOCK_EVENTS_COUNT as DeviceEventT); assert_eq!(device, "block"); } _ => panic!("invalid"), } } // Cannot easily test failures for // * queue_evt.read // * interrupt_evt.write #[test] #[allow(clippy::cognitive_complexity)] fn test_handler() { let m = GuestMemory::new(&[(GuestAddress(0), 0x10000)]).unwrap(); let (mut h, vq) = default_test_blockepollhandler(&m); let blk_metadata = h.disk_image.metadata(); for i in 0..3 { vq.avail.ring[i].set(i as u16); vq.dtable[i].set( (0x1000 * (i + 1)) as u64, 0x1000, VIRTQ_DESC_F_NEXT, (i + 1) as u16, ); } vq.dtable[1] .flags .set(VIRTQ_DESC_F_NEXT | VIRTQ_DESC_F_WRITE); vq.dtable[2].flags.set(VIRTQ_DESC_F_WRITE); vq.avail.idx.set(1); // dtable[1] is the data descriptor let data_addr = GuestAddress(vq.dtable[1].addr.get()); // dtable[2] is the status descriptor let status_addr = GuestAddress(vq.dtable[2].addr.get()); { // let's start with a request that does not parse // request won't be valid bc the first desc is write-only vq.dtable[0] .flags .set(VIRTQ_DESC_F_NEXT | VIRTQ_DESC_F_WRITE); m.write_obj_at_addr::<u32>(VIRTIO_BLK_T_IN, GuestAddress(0x1000)) .unwrap(); invoke_handler_for_queue_event(&mut h); assert_eq!(vq.used.idx.get(), 1); assert_eq!(vq.used.ring[0].get().id, 0); assert_eq!(vq.used.ring[0].get().len, 0); } // now we generate some request execute failures { // reset the queue to reuse descriptors & memory vq.used.idx.set(0); h.set_queue(0, vq.create_queue()); // first desc no longer writable vq.dtable[0].flags.set(VIRTQ_DESC_F_NEXT); vq.dtable[1].flags.set(VIRTQ_DESC_F_NEXT); // let's generate a seek execute error caused by a very large sector number m.write_obj_at_addr::<u32>(VIRTIO_BLK_T_OUT, GuestAddress(0x1000)) .unwrap(); m.write_obj_at_addr::<u64>(0x000f_ffff_ffff, GuestAddress(0x1000 + 8)) .unwrap(); invoke_handler_for_queue_event(&mut h); assert_eq!(vq.used.idx.get(), 1); assert_eq!(vq.used.ring[0].get().id, 0); assert_eq!(vq.used.ring[0].get().len, 1); assert_eq!( m.read_obj_from_addr::<u32>(status_addr).unwrap(), VIRTIO_BLK_S_IOERR ); } { vq.used.idx.set(0); h.set_queue(0, vq.create_queue()); vq.dtable[1] .flags .set(VIRTQ_DESC_F_NEXT | VIRTQ_DESC_F_WRITE); // set sector to a valid number but large enough that the full 0x1000 read will fail m.write_obj_at_addr::<u32>(VIRTIO_BLK_T_IN, GuestAddress(0x1000)) .unwrap(); m.write_obj_at_addr::<u64>(10, GuestAddress(0x1000 + 8)) .unwrap(); invoke_handler_for_queue_event(&mut h); assert_eq!(vq.used.idx.get(), 1); assert_eq!(vq.used.ring[0].get().id, 0); assert_eq!(vq.used.ring[0].get().len, 1); assert_eq!( m.read_obj_from_addr::<u32>(status_addr).unwrap(), VIRTIO_BLK_S_IOERR ); } // test unsupported block commands // currently 0, 1, 4, 8 are supported { vq.used.idx.set(0); h.set_queue(0, vq.create_queue()); // set sector to 0 m.write_obj_at_addr::<u64>(0, GuestAddress(0x1000 + 8)) .unwrap(); // ... but generate an unsupported request m.write_obj_at_addr::<u32>(16, GuestAddress(0x1000)) .unwrap(); invoke_handler_for_queue_event(&mut h); assert_eq!(vq.used.idx.get(), 1); assert_eq!(vq.used.ring[0].get().id, 0); assert_eq!(vq.used.ring[0].get().len, 1); assert_eq!( m.read_obj_from_addr::<u32>(status_addr).unwrap(), VIRTIO_BLK_S_UNSUPP ); } // now let's write something and read it back { // write vq.used.idx.set(0); h.set_queue(0, vq.create_queue()); m.write_obj_at_addr::<u32>(VIRTIO_BLK_T_OUT, GuestAddress(0x1000)) .unwrap(); // make data read only, 8 bytes in len, and set the actual value to be written vq.dtable[1].flags.set(VIRTQ_DESC_F_NEXT); vq.dtable[1].len.set(8); m.write_obj_at_addr::<u64>(123_456_789, data_addr).unwrap(); check_metric_after_block!( &METRICS.block.write_count, 1, invoke_handler_for_queue_event(&mut h) ); assert_eq!(vq.used.idx.get(), 1); assert_eq!(vq.used.ring[0].get().id, 0); assert_eq!(vq.used.ring[0].get().len, 0); assert_eq!( m.read_obj_from_addr::<u32>(status_addr).unwrap(), VIRTIO_BLK_S_OK ); } { // read vq.used.idx.set(0); h.set_queue(0, vq.create_queue()); m.write_obj_at_addr::<u32>(VIRTIO_BLK_T_IN, GuestAddress(0x1000)) .unwrap(); vq.dtable[1] .flags .set(VIRTQ_DESC_F_NEXT | VIRTQ_DESC_F_WRITE); check_metric_after_block!( &METRICS.block.read_count, 1, invoke_handler_for_queue_event(&mut h) ); assert_eq!(vq.used.idx.get(), 1); assert_eq!(vq.used.ring[0].get().id, 0); assert_eq!(vq.used.ring[0].get().len, vq.dtable[1].len.get()); assert_eq!( m.read_obj_from_addr::<u32>(status_addr).unwrap(), VIRTIO_BLK_S_OK ); assert_eq!(m.read_obj_from_addr::<u64>(data_addr).unwrap(), 123_456_789); } { // testing that the flush request completes successfully, // when a data descriptor is provided vq.used.idx.set(0); h.set_queue(0, vq.create_queue()); m.write_obj_at_addr::<u32>(VIRTIO_BLK_T_FLUSH, GuestAddress(0x1000)) .unwrap(); invoke_handler_for_queue_event(&mut h); assert_eq!(vq.used.idx.get(), 1); assert_eq!(vq.used.ring[0].get().id, 0); assert_eq!(vq.used.ring[0].get().len, 0); assert_eq!( m.read_obj_from_addr::<u32>(status_addr).unwrap(), VIRTIO_BLK_S_OK ); } { // testing that the flush request completes successfully, // without a data descriptor vq.used.idx.set(0); h.set_queue(0, vq.create_queue()); vq.dtable[0].next.set(2); m.write_obj_at_addr::<u32>(VIRTIO_BLK_T_FLUSH, GuestAddress(0x1000)) .unwrap(); invoke_handler_for_queue_event(&mut h); assert_eq!(vq.used.idx.get(), 1); assert_eq!(vq.used.ring[0].get().id, 0); assert_eq!(vq.used.ring[0].get().len, 0); assert_eq!( m.read_obj_from_addr::<u32>(status_addr).unwrap(), VIRTIO_BLK_S_OK ); vq.dtable[0].next.set(1); } { // testing that the driver receives the correct device id vq.used.idx.set(0); h.set_queue(0, vq.create_queue()); vq.dtable[1].len.set(VIRTIO_BLK_ID_BYTES); m.write_obj_at_addr::<u32>(VIRTIO_BLK_T_GET_ID, GuestAddress(0x1000)) .unwrap(); invoke_handler_for_queue_event(&mut h); assert_eq!(vq.used.idx.get(), 1); assert_eq!(vq.used.ring[0].get().id, 0); assert_eq!(vq.used.ring[0].get().len, 0); assert_eq!( m.read_obj_from_addr::<u32>(status_addr).unwrap(), VIRTIO_BLK_S_OK ); assert!(blk_metadata.is_ok()); let blk_meta = blk_metadata.unwrap(); let expected_device_id = format!( "{}{}{}", blk_meta.st_dev(), blk_meta.st_rdev(), blk_meta.st_ino() ); let mut buf = [0; VIRTIO_BLK_ID_BYTES as usize]; assert_eq!( m.read_slice_at_addr(&mut buf, data_addr).unwrap(), VIRTIO_BLK_ID_BYTES as usize ); let chars_to_trim: &[char] = &['\u{0}']; let received_device_id = String::from_utf8(buf.to_ascii_lowercase()) .unwrap() .trim_matches(chars_to_trim) .to_string(); assert_eq!(received_device_id, expected_device_id); } { // test that a device ID request will fail, if it fails to provide enough buffer space vq.used.idx.set(0); h.set_queue(0, vq.create_queue()); vq.dtable[1].len.set(VIRTIO_BLK_ID_BYTES - 1); m.write_obj_at_addr::<u32>(VIRTIO_BLK_T_GET_ID, GuestAddress(0x1000)) .unwrap(); invoke_handler_for_queue_event(&mut h); assert_eq!(vq.used.idx.get(), 1); assert_eq!(vq.used.ring[0].get().id, 0); assert_eq!(vq.used.ring[0].get().len, 1); assert_eq!( m.read_obj_from_addr::<u32>(status_addr).unwrap(), VIRTIO_BLK_S_IOERR ); } // test the bandwidth rate limiter { // create bandwidth rate limiter that allows only 80 bytes/s with bucket size of 8 bytes let mut rl = RateLimiter::new(8, None, 100, 0, None, 0).unwrap(); // use up the budget assert!(rl.consume(8, TokenType::Bytes)); vq.used.idx.set(0); h.set_queue(0, vq.create_queue()); h.set_rate_limiter(rl); m.write_obj_at_addr::<u32>(VIRTIO_BLK_T_OUT, GuestAddress(0x1000)) .unwrap(); // make data read only, 8 bytes in len, and set the actual value to be written vq.dtable[1].flags.set(VIRTQ_DESC_F_NEXT); vq.dtable[1].len.set(8); m.write_obj_at_addr::<u64>(123_456_789, data_addr).unwrap(); // following write procedure should fail because of bandwidth rate limiting { // leave at least one event here so that reading it later won't block h.interrupt_evt.write(1).unwrap(); // trigger the attempt to write h.queue_evt.write(1).unwrap(); h.handle_event(QUEUE_AVAIL_EVENT, EPOLLIN).unwrap(); // assert that limiter is blocked assert!(h.get_rate_limiter().is_blocked()); // assert that no operation actually completed (limiter blocked it) assert_eq!(h.interrupt_evt.read().unwrap(), 1); // make sure the data is still queued for processing assert_eq!(vq.used.idx.get(), 0); } // wait for 100ms to give the rate-limiter timer a chance to replenish // wait for an extra 50ms to make sure the timerfd event makes its way from the kernel thread::sleep(Duration::from_millis(150)); // following write procedure should succeed because bandwidth should now be available { // leave at least one event here so that reading it later won't block h.interrupt_evt.write(1).unwrap(); h.handle_event(RATE_LIMITER_EVENT, EPOLLIN).unwrap(); // validate the rate_limiter is no longer blocked assert!(!h.get_rate_limiter().is_blocked()); // make sure the virtio queue operation completed this time assert_eq!(h.interrupt_evt.read().unwrap(), 2); // make sure the data queue advanced assert_eq!(vq.used.idx.get(), 1); assert_eq!(vq.used.ring[0].get().id, 0); assert_eq!(vq.used.ring[0].get().len, 0); assert_eq!( m.read_obj_from_addr::<u32>(status_addr).unwrap(), VIRTIO_BLK_S_OK ); } } // test the ops/s rate limiter { // create ops rate limiter that allows only 10 ops/s with bucket size of 1 ops let mut rl = RateLimiter::new(0, None, 0, 1, None, 100).unwrap(); // use up the budget assert!(rl.consume(1, TokenType::Ops)); vq.used.idx.set(0); h.set_queue(0, vq.create_queue()); h.set_rate_limiter(rl); m.write_obj_at_addr::<u32>(VIRTIO_BLK_T_OUT, GuestAddress(0x1000)) .unwrap(); // make data read only, 8 bytes in len, and set the actual value to be written vq.dtable[1].flags.set(VIRTQ_DESC_F_NEXT); vq.dtable[1].len.set(8); m.write_obj_at_addr::<u64>(123_456_789, data_addr).unwrap(); // following write procedure should fail because of ops rate limiting { // leave at least one event here so that reading it later won't block h.interrupt_evt.write(1).unwrap(); // trigger the attempt to write h.queue_evt.write(1).unwrap(); h.handle_event(QUEUE_AVAIL_EVENT, EPOLLIN).unwrap(); // assert that limiter is blocked assert!(h.get_rate_limiter().is_blocked()); // assert that no operation actually completed (limiter blocked it) assert_eq!(h.interrupt_evt.read().unwrap(), 1); // make sure the data is still queued for processing assert_eq!(vq.used.idx.get(), 0); } // do a second write that still fails but this time on the fast path { // leave at least one event here so that reading it later won't block h.interrupt_evt.write(1).unwrap(); // trigger the attempt to write h.queue_evt.write(1).unwrap(); h.handle_event(QUEUE_AVAIL_EVENT, EPOLLIN).unwrap(); // assert that limiter is blocked assert!(h.get_rate_limiter().is_blocked()); // assert that no operation actually completed (limiter blocked it) assert_eq!(h.interrupt_evt.read().unwrap(), 1); // make sure the data is still queued for processing assert_eq!(vq.used.idx.get(), 0); } // wait for 100ms to give the rate-limiter timer a chance to replenish // wait for an extra 50ms to make sure the timerfd event makes its way from the kernel thread::sleep(Duration::from_millis(150)); // following write procedure should succeed because ops budget should now be available { // leave at least one event here so that reading it later won't block h.interrupt_evt.write(1).unwrap(); h.handle_event(RATE_LIMITER_EVENT, EPOLLIN).unwrap(); // validate the rate_limiter is no longer blocked assert!(!h.get_rate_limiter().is_blocked()); // make sure the virtio queue operation completed this time assert_eq!(h.interrupt_evt.read().unwrap(), 2); // make sure the data queue advanced assert_eq!(vq.used.idx.get(), 1); assert_eq!(vq.used.ring[0].get().id, 0); assert_eq!(vq.used.ring[0].get().len, 0); assert_eq!( m.read_obj_from_addr::<u32>(status_addr).unwrap(), VIRTIO_BLK_S_OK ); } } // test block device update handler { let f = NamedTempFile::new().unwrap(); let path = f.path().to_path_buf(); let mdata = metadata(&path).unwrap(); let mut id = vec![0; VIRTIO_BLK_ID_BYTES as usize]; let str_id = format!("{}{}{}", mdata.st_dev(), mdata.st_rdev(), mdata.st_ino()); let part_id = str_id.as_bytes(); id[..cmp::min(part_id.len(), VIRTIO_BLK_ID_BYTES as usize)].clone_from_slice( &part_id[..cmp::min(part_id.len(), VIRTIO_BLK_ID_BYTES as usize)], ); let file = OpenOptions::new() .read(true) .write(true) .open(path) .unwrap(); h.update_disk_image(file).unwrap(); assert_eq!(h.disk_image.metadata().unwrap().st_ino(), mdata.st_ino()); assert_eq!(h.disk_image_id, id); } } }
35.996099
100
0.546295
e914df687a3bd642a5b7c868e8d541b82084fc5e
147,251
// Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Translates and validates specification language fragments as they are output from the Move //! compiler's expansion phase and adds them to the environment (which was initialized from the //! byte code). This includes identifying the Move sub-language supported by the specification //! system, as well as type checking it and translating it to the spec language ast. use std::collections::{BTreeMap, BTreeSet, LinkedList, VecDeque}; use itertools::Itertools; use num::{BigUint, FromPrimitive, Num}; use bytecode_source_map::source_map::SourceMap; #[allow(unused_imports)] use log::{debug, info, warn}; use move_lang::{ compiled_unit::{FunctionInfo, SpecInfo}, expansion::ast::{self as EA}, hlir::ast::{BaseType, SingleType}, naming::ast::TParam, parser::ast::{self as PA, FunctionName}, shared::{unique_map::UniqueMap, Name}, }; use vm::{ access::ModuleAccess, file_format::{FunctionDefinitionIndex, StructDefinitionIndex}, views::{FunctionHandleView, StructHandleView}, CompiledModule, }; use crate::{ ast::{ Condition, ConditionKind, Exp, LocalVarDecl, ModuleName, Operation, QualifiedSymbol, Spec, SpecFunDecl, SpecVarDecl, Value, }, env::{ FieldId, FunId, FunctionData, GlobalEnv, Loc, ModuleId, MoveIrLoc, NodeId, SpecFunId, SpecVarId, StructData, StructId, SCRIPT_AST_FUN_NAME, SCRIPT_BYTECODE_FUN_NAME, }, project_1st, project_2nd, symbol::{Symbol, SymbolPool}, ty::{PrimitiveType, Substitution, Type, TypeDisplayContext, BOOL_TYPE}, }; use move_ir_types::location::Spanned; use regex::Regex; // ================================================================================================= /// # Translator /// A translator. This is used to translate a sequence of modules in acyclic dependency order. The /// translator maintains the incremental state of this process, such that the various tables /// are extended with each module translated. Each table is a mapping from fully qualified names /// (module names plus item name in the module) to the entity. #[derive(Debug)] pub struct Translator<'env> { /// The global environment we are building. pub env: &'env mut GlobalEnv, /// A symbol table for specification functions. Because of overloading, and entry can /// contain multiple functions. spec_fun_table: BTreeMap<QualifiedSymbol, Vec<SpecFunEntry>>, /// A symbol table for specification variables. spec_var_table: BTreeMap<QualifiedSymbol, SpecVarEntry>, /// A symbol table for specification schemas. spec_schema_table: BTreeMap<QualifiedSymbol, SpecSchemaEntry>, // A symbol table for structs. struct_table: BTreeMap<QualifiedSymbol, StructEntry>, /// A reverse mapping from ModuleId/StructId pairs to QualifiedSymbol. This /// is used for visualization of types in error messages. reverse_struct_table: BTreeMap<(ModuleId, StructId), QualifiedSymbol>, /// A symbol table for functions. fun_table: BTreeMap<QualifiedSymbol, FunEntry>, } /// A declaration of a specification function or operator in the translator state. #[derive(Debug, Clone)] struct SpecFunEntry { loc: Loc, oper: Operation, type_params: Vec<Type>, arg_types: Vec<Type>, result_type: Type, } /// A declaration of a specification variable in the translator state. #[derive(Debug, Clone)] struct SpecVarEntry { loc: Loc, module_id: ModuleId, var_id: SpecVarId, type_params: Vec<Type>, type_: Type, } /// A declaration of a schema in the translator state. #[derive(Debug)] struct SpecSchemaEntry { loc: Loc, name: QualifiedSymbol, module_id: ModuleId, type_params: Vec<(Symbol, Type)>, // The local variables declared in the schema. vars: Vec<(Symbol, Type)>, // The specifications in in this schema. spec: Spec, // All variables in scope of this schema, including those introduced by included schemas. all_vars: BTreeMap<Symbol, LocalVarEntry>, // The specification included from other schemas, after renaming and type instantiation. included_spec: Spec, } /// A declaration of a struct. #[derive(Debug, Clone)] struct StructEntry { loc: Loc, module_id: ModuleId, struct_id: StructId, is_resource: bool, type_params: Vec<(Symbol, Type)>, fields: Option<BTreeMap<Symbol, (usize, Type)>>, } /// A declaration of a function. #[derive(Debug, Clone)] struct FunEntry { loc: Loc, module_id: ModuleId, fun_id: FunId, is_public: bool, type_params: Vec<(Symbol, Type)>, params: Vec<(Symbol, Type)>, result_type: Type, } /// ## General impl<'env> Translator<'env> { /// Creates a translator. pub fn new(env: &'env mut GlobalEnv) -> Self { let mut translator = Translator { env, spec_fun_table: BTreeMap::new(), spec_var_table: BTreeMap::new(), spec_schema_table: BTreeMap::new(), struct_table: BTreeMap::new(), reverse_struct_table: BTreeMap::new(), fun_table: BTreeMap::new(), }; translator.declare_builtins(); translator } /// Shortcut for translating a Move AST location into ours. pub fn to_loc(&self, loc: &move_ir_types::location::Loc) -> Loc { self.env.to_loc(loc) } /// Reports a type checking error. fn error(&self, at: &Loc, msg: &str) { self.env.error(at, msg) } /// Defines a spec function. fn define_spec_fun( &mut self, loc: &Loc, name: QualifiedSymbol, module_id: ModuleId, fun_id: SpecFunId, type_params: Vec<Type>, arg_types: Vec<Type>, result_type: Type, ) { let entry = SpecFunEntry { loc: loc.clone(), oper: Operation::Function(module_id, fun_id), type_params, arg_types, result_type, }; // TODO: check whether overloads are distinguishable self.spec_fun_table .entry(name) .or_insert_with(|| vec![]) .push(entry); } /// Defines a spec variable. fn define_spec_var( &mut self, loc: &Loc, name: QualifiedSymbol, module_id: ModuleId, var_id: SpecVarId, type_params: Vec<Type>, type_: Type, ) { let entry = SpecVarEntry { loc: loc.clone(), module_id, var_id, type_params, type_, }; if let Some(old) = self.spec_var_table.insert(name.clone(), entry) { let var_name = name.display(self.env.symbol_pool()); self.error(loc, &format!("duplicate declaration of `{}`", var_name)); self.error(&old.loc, &format!("previous declaration of `{}`", var_name)); } } /// Defines a spec schema. fn define_spec_schema( &mut self, loc: &Loc, name: QualifiedSymbol, module_id: ModuleId, type_params: Vec<(Symbol, Type)>, vars: Vec<(Symbol, Type)>, ) { let entry = SpecSchemaEntry { loc: loc.clone(), name: name.clone(), module_id, type_params, vars, spec: Spec::default(), all_vars: BTreeMap::new(), included_spec: Spec::default(), }; if let Some(old) = self.spec_schema_table.insert(name.clone(), entry) { let schema_display = name.display(self.env.symbol_pool()); self.error( loc, &format!("duplicate declaration of `{}`", schema_display), ); self.error( &old.loc, &format!("previous declaration of `{}`", schema_display), ); } } /// Defines a struct type. fn define_struct( &mut self, loc: Loc, name: QualifiedSymbol, module_id: ModuleId, struct_id: StructId, is_resource: bool, type_params: Vec<(Symbol, Type)>, fields: Option<BTreeMap<Symbol, (usize, Type)>>, ) { let entry = StructEntry { loc, module_id, struct_id, is_resource, type_params, fields, }; // Duplicate declarations have been checked by the move compiler. assert!(self.struct_table.insert(name.clone(), entry).is_none()); self.reverse_struct_table .insert((module_id, struct_id), name); } /// Defines a function. fn define_fun( &mut self, loc: Loc, name: QualifiedSymbol, module_id: ModuleId, fun_id: FunId, is_public: bool, type_params: Vec<(Symbol, Type)>, params: Vec<(Symbol, Type)>, result_type: Type, ) { let entry = FunEntry { loc, module_id, fun_id, is_public, type_params, params, result_type, }; // Duplicate declarations have been checked by the move compiler. assert!(self.fun_table.insert(name, entry).is_none()); } /// Looks up a type (struct), reporting an error if it is not found. fn lookup_type(&self, loc: &Loc, name: &QualifiedSymbol) -> Type { self.struct_table .get(name) .cloned() .map(|e| Type::Struct(e.module_id, e.struct_id, project_2nd(&e.type_params))) .unwrap_or_else(|| { self.error( loc, &format!("undeclared `{}`", name.display_full(self.env.symbol_pool())), ); Type::Error }) } } /// # Builtins impl<'env> Translator<'env> { /// Declares builtins in the translator. This adds functions and operators /// to the translator which will be treated the same as user defined specification functions /// during translation. fn declare_builtins(&mut self) { let loc = self.env.internal_loc(); let bool_t = &Type::new_prim(PrimitiveType::Bool); let num_t = &Type::new_prim(PrimitiveType::Num); let range_t = &Type::new_prim(PrimitiveType::Range); let address_t = &Type::new_prim(PrimitiveType::Address); let param_t = &Type::TypeParameter(0); let add_builtin = |trans: &mut Translator, name: QualifiedSymbol, entry: SpecFunEntry| { trans .spec_fun_table .entry(name) .or_insert_with(|| vec![]) .push(entry); }; { // Binary operators. let mut declare_bin = |op: PA::BinOp_, oper: Operation, param_type: &Type, result_type: &Type| { add_builtin( self, self.bin_op_symbol(&op), SpecFunEntry { loc: loc.clone(), oper, type_params: vec![], arg_types: vec![param_type.clone(), param_type.clone()], result_type: result_type.clone(), }, ); }; use PA::BinOp_::*; declare_bin(Add, Operation::Add, num_t, num_t); declare_bin(Sub, Operation::Sub, num_t, num_t); declare_bin(Mul, Operation::Mul, num_t, num_t); declare_bin(Mod, Operation::Mod, num_t, num_t); declare_bin(Div, Operation::Div, num_t, num_t); declare_bin(BitOr, Operation::BitOr, num_t, num_t); declare_bin(BitAnd, Operation::BitAnd, num_t, num_t); declare_bin(Xor, Operation::Xor, num_t, num_t); declare_bin(Shl, Operation::Shl, num_t, num_t); declare_bin(Shr, Operation::Shr, num_t, num_t); declare_bin(Range, Operation::Range, num_t, range_t); declare_bin(Implies, Operation::Implies, bool_t, bool_t); declare_bin(And, Operation::And, bool_t, bool_t); declare_bin(Or, Operation::Or, bool_t, bool_t); declare_bin(Lt, Operation::Lt, num_t, bool_t); declare_bin(Le, Operation::Le, num_t, bool_t); declare_bin(Gt, Operation::Gt, num_t, bool_t); declare_bin(Ge, Operation::Ge, num_t, bool_t); // Eq and Neq have special treatment because they are generic. add_builtin( self, self.bin_op_symbol(&PA::BinOp_::Eq), SpecFunEntry { loc: loc.clone(), oper: Operation::Eq, type_params: vec![param_t.clone()], arg_types: vec![param_t.clone(), param_t.clone()], result_type: bool_t.clone(), }, ); add_builtin( self, self.bin_op_symbol(&PA::BinOp_::Neq), SpecFunEntry { loc: loc.clone(), oper: Operation::Neq, type_params: vec![param_t.clone()], arg_types: vec![param_t.clone(), param_t.clone()], result_type: bool_t.clone(), }, ); } { // Unary operators. add_builtin( self, self.unary_op_symbol(&PA::UnaryOp_::Not), SpecFunEntry { loc: loc.clone(), oper: Operation::Not, type_params: vec![], arg_types: vec![bool_t.clone()], result_type: bool_t.clone(), }, ); } { // Builtin functions. let vector_t = &Type::Vector(Box::new(param_t.clone())); let pred_t = &Type::Fun(vec![param_t.clone()], Box::new(bool_t.clone())); let pred_num_t = &Type::Fun(vec![num_t.clone()], Box::new(bool_t.clone())); // Transaction metadata add_builtin( self, self.builtin_fun_symbol("sender"), SpecFunEntry { loc: loc.clone(), oper: Operation::Sender, type_params: vec![], arg_types: vec![], result_type: address_t.clone(), }, ); // constants (max_u8(), etc.) add_builtin( self, self.builtin_fun_symbol("max_u8"), SpecFunEntry { loc: loc.clone(), oper: Operation::MaxU8, type_params: vec![], arg_types: vec![], result_type: num_t.clone(), }, ); add_builtin( self, self.builtin_fun_symbol("max_u64"), SpecFunEntry { loc: loc.clone(), oper: Operation::MaxU64, type_params: vec![], arg_types: vec![], result_type: num_t.clone(), }, ); add_builtin( self, self.builtin_fun_symbol("max_u128"), SpecFunEntry { loc: loc.clone(), oper: Operation::MaxU128, type_params: vec![], arg_types: vec![], result_type: num_t.clone(), }, ); // Vectors add_builtin( self, self.builtin_fun_symbol("len"), SpecFunEntry { loc: loc.clone(), oper: Operation::Len, type_params: vec![param_t.clone()], arg_types: vec![vector_t.clone()], result_type: num_t.clone(), }, ); add_builtin( self, self.builtin_fun_symbol("all"), SpecFunEntry { loc: loc.clone(), oper: Operation::All, type_params: vec![param_t.clone()], arg_types: vec![vector_t.clone(), pred_t.clone()], result_type: bool_t.clone(), }, ); add_builtin( self, self.builtin_fun_symbol("any"), SpecFunEntry { loc: loc.clone(), oper: Operation::Any, type_params: vec![param_t.clone()], arg_types: vec![vector_t.clone(), pred_t.clone()], result_type: bool_t.clone(), }, ); add_builtin( self, self.builtin_fun_symbol("update"), SpecFunEntry { loc: loc.clone(), oper: Operation::Update, type_params: vec![param_t.clone()], arg_types: vec![vector_t.clone(), num_t.clone(), param_t.clone()], result_type: vector_t.clone(), }, ); // Ranges add_builtin( self, self.builtin_fun_symbol("all"), SpecFunEntry { loc: loc.clone(), oper: Operation::All, type_params: vec![], arg_types: vec![range_t.clone(), pred_num_t.clone()], result_type: bool_t.clone(), }, ); add_builtin( self, self.builtin_fun_symbol("any"), SpecFunEntry { loc: loc.clone(), oper: Operation::Any, type_params: vec![], arg_types: vec![range_t.clone(), pred_num_t.clone()], result_type: bool_t.clone(), }, ); // Resources. add_builtin( self, self.builtin_fun_symbol("global"), SpecFunEntry { loc: loc.clone(), oper: Operation::Global, type_params: vec![param_t.clone()], arg_types: vec![address_t.clone()], result_type: param_t.clone(), }, ); add_builtin( self, self.builtin_fun_symbol("exists"), SpecFunEntry { loc: loc.clone(), oper: Operation::Exists, type_params: vec![param_t.clone()], arg_types: vec![address_t.clone()], result_type: bool_t.clone(), }, ); // Old add_builtin( self, self.builtin_fun_symbol("old"), SpecFunEntry { loc, oper: Operation::Old, type_params: vec![param_t.clone()], arg_types: vec![param_t.clone()], result_type: param_t.clone(), }, ); } } /// Returns the qualified symbol for the binary operator. fn bin_op_symbol(&self, op: &PA::BinOp_) -> QualifiedSymbol { QualifiedSymbol { module_name: self.builtin_module(), symbol: self.env.symbol_pool().make(&op.symbol()), } } /// Returns the qualified symbol for the unary operator. fn unary_op_symbol(&self, op: &PA::UnaryOp_) -> QualifiedSymbol { QualifiedSymbol { module_name: self.builtin_module(), symbol: self.env.symbol_pool().make(&op.symbol()), } } /// Returns the qualified symbol for a builtin function. fn builtin_fun_symbol(&self, name: &str) -> QualifiedSymbol { QualifiedSymbol { module_name: self.builtin_module(), symbol: self.env.symbol_pool().make(name), } } /// Returns the symbol for the builtin function `old`. fn old_symbol(&self) -> Symbol { self.env.symbol_pool().make("old") } /// Returns the name for the pseudo builtin module. pub fn builtin_module(&self) -> ModuleName { ModuleName::new(BigUint::default(), self.env.symbol_pool().make("$$")) } } // ================================================================================================= /// # Module Translation /// A module translator. #[derive(Debug)] pub struct ModuleTranslator<'env, 'translator> { parent: &'translator mut Translator<'env>, /// Counter for NodeId in this module. node_counter: usize, /// A map from node id to associated location. loc_map: BTreeMap<NodeId, Loc>, /// A map from node id to associated type. type_map: BTreeMap<NodeId, Type>, /// A map from node id to associated instantiation of type parameters. pub instantiation_map: BTreeMap<NodeId, Vec<Type>>, /// Id of the currently build module. module_id: ModuleId, /// Name of the currently build module. module_name: ModuleName, /// Translated specification functions. spec_funs: Vec<SpecFunDecl>, /// During the definition analysis, the index into `spec_funs` we are currently /// handling spec_fun_index: usize, /// Translated specification variables. spec_vars: Vec<SpecVarDecl>, /// Translated function specifications. fun_specs: BTreeMap<Symbol, Spec>, /// Translated struct specifications. struct_specs: BTreeMap<Symbol, Spec>, /// Translated module spec module_spec: Spec, } /// # Entry Points impl<'env, 'translator> ModuleTranslator<'env, 'translator> { pub fn new( parent: &'translator mut Translator<'env>, module_id: ModuleId, module_name: ModuleName, ) -> Self { Self { parent, node_counter: 0, loc_map: BTreeMap::new(), type_map: BTreeMap::new(), instantiation_map: BTreeMap::new(), module_id, module_name, spec_funs: vec![], spec_fun_index: 0, spec_vars: vec![], fun_specs: BTreeMap::new(), struct_specs: BTreeMap::new(), module_spec: Spec::default(), } } /// Translates the given module definition from the move compiler's expansion phase, /// combined with a compiled module (bytecode) and a source map, and enters it into /// this global environment. Any type check or others errors encountered will be collected /// in the environment for later processing. Dependencies of this module are guaranteed to /// have been analyzed and being already part of the environment. /// /// Translation happens in three phases: /// /// 1. In the *declaration analysis*, we collect all information about structs, functions, /// spec functions, spec vars, and schemas in a module. We do not yet analyze function /// bodies, conditions, and invariants, which we can only analyze after we know all /// global declarations (declaration of globals is order independent, and they can have /// cyclic references). /// 2. In the *definition analysis*, we visit the definitions we have skipped in step (1), /// specifically analyzing and type checking expressions and schema inclusions. /// 3. In the *population phase*, we populate the global environment with the information /// from this module. pub fn translate( &mut self, loc: Loc, module_def: EA::ModuleDefinition, compiled_module: CompiledModule, source_map: SourceMap<MoveIrLoc>, function_infos: UniqueMap<FunctionName, FunctionInfo>, ) { self.decl_ana(&module_def); self.def_ana(&module_def, function_infos); self.populate_env_from_result(loc, compiled_module, source_map); } } /// # Basic Helpers /// A value which we pass in to spec block analyzers, describing the resolved target of the spec /// block. #[derive(Debug)] enum SpecBlockContext<'a> { Module, Struct(QualifiedSymbol), Function(QualifiedSymbol), FunctionCode(QualifiedSymbol, &'a SpecInfo), Schema(QualifiedSymbol), } impl<'env, 'translator> ModuleTranslator<'env, 'translator> { /// Shortcut for accessing the symbol pool. fn symbol_pool(&self) -> &SymbolPool { self.parent.env.symbol_pool() } /// Creates a new node id. fn new_node_id(&mut self) -> NodeId { let node_id = NodeId::new(self.node_counter); self.node_counter += 1; node_id } /// Qualifies the given symbol by the current module. fn qualified_by_module(&self, sym: Symbol) -> QualifiedSymbol { QualifiedSymbol { module_name: self.module_name.clone(), symbol: sym, } } /// Qualifies the given name by the current module. fn qualified_by_module_from_name(&self, name: &Name) -> QualifiedSymbol { let sym = self.symbol_pool().make(&name.value); self.qualified_by_module(sym) } /// Converts a ModuleAccess into its parts, an optional ModuleName and base name. fn module_access_to_parts(&self, access: &EA::ModuleAccess) -> (Option<ModuleName>, Symbol) { match &access.value { EA::ModuleAccess_::Name(n) => (None, self.symbol_pool().make(n.value.as_str())), EA::ModuleAccess_::ModuleAccess(m, n) => { let module_name = ModuleName::from_str( &m.0.value.address.to_string(), self.symbol_pool().make(m.0.value.name.0.value.as_str()), ); (Some(module_name), self.symbol_pool().make(n.value.as_str())) } } } /// Converts a ModuleAccess into a qualified symbol which can be used for lookup of /// types or functions. fn module_access_to_qualified(&self, access: &EA::ModuleAccess) -> QualifiedSymbol { let (module_name_opt, symbol) = self.module_access_to_parts(access); let module_name = module_name_opt.unwrap_or_else(|| self.module_name.clone()); QualifiedSymbol { module_name, symbol, } } /// Creates a SpecBlockContext from the given SpecBlockTarget. The context is used during /// definition analysis when visiting a schema block member (condition, invariant, etc.). /// This returns None if the SpecBlockTarget cannnot be resolved; error reporting happens /// at caller side. fn get_spec_block_context<'pa>( &self, target: &'pa PA::SpecBlockTarget, ) -> Option<SpecBlockContext<'pa>> { match &target.value { PA::SpecBlockTarget_::Code => None, PA::SpecBlockTarget_::Function(name) => { let qsym = self.qualified_by_module_from_name(&name.0); if self.parent.fun_table.contains_key(&qsym) { Some(SpecBlockContext::Function(qsym)) } else { None } } PA::SpecBlockTarget_::Structure(name) => { let qsym = self.qualified_by_module_from_name(&name.0); if self.parent.struct_table.contains_key(&qsym) { Some(SpecBlockContext::Struct(qsym)) } else { None } } PA::SpecBlockTarget_::Schema(name, _) => { let qsym = self.qualified_by_module_from_name(&name); if self.parent.spec_schema_table.contains_key(&qsym) { Some(SpecBlockContext::Schema(qsym)) } else { None } } PA::SpecBlockTarget_::Module => Some(SpecBlockContext::Module), } } } /// # Declaration Analysis impl<'env, 'translator> ModuleTranslator<'env, 'translator> { fn decl_ana(&mut self, module_def: &EA::ModuleDefinition) { for (name, struct_def) in &module_def.structs { self.decl_ana_struct(&name, struct_def); } for (name, fun_def) in &module_def.functions { self.decl_ana_fun(&name, fun_def); } for spec in &module_def.specs { self.decl_ana_spec_block(spec); } } fn decl_ana_struct(&mut self, name: &PA::StructName, def: &EA::StructDefinition) { let qsym = self.qualified_by_module_from_name(&name.0); let struct_id = StructId::new(qsym.symbol); let mut et = ExpTranslator::new(self); let type_params = et.analyze_and_add_type_params(&def.type_parameters); et.parent.parent.define_struct( et.to_loc(&def.loc), qsym, et.parent.module_id, struct_id, def.resource_opt.is_some(), type_params, None, // will be filled in during definition analysis ); } fn decl_ana_fun(&mut self, name: &PA::FunctionName, def: &EA::Function) { let qsym = self.qualified_by_module_from_name(&name.0); let fun_id = FunId::new(qsym.symbol); let mut et = ExpTranslator::new(self); et.enter_scope(); let type_params = et.analyze_and_add_type_params(&def.signature.type_parameters); et.enter_scope(); let params = et.analyze_and_add_params(&def.signature.parameters); let result_type = et.translate_type(&def.signature.return_type); let is_public = matches!(def.visibility, PA::FunctionVisibility::Public(..)); et.parent.parent.define_fun( et.to_loc(&def.loc), qsym, et.parent.module_id, fun_id, is_public, type_params, params, result_type, ); } fn decl_ana_spec_block(&mut self, block: &EA::SpecBlock) { use EA::SpecBlockMember_::*; // Process any spec block members which introduce global declarations. for member in &block.value.members { let loc = self.parent.env.to_loc(&member.loc); match &member.value { Function { name, signature, .. } => self.decl_ana_spec_fun(&loc, name, signature), Variable { is_global: true, name, type_, type_parameters, } => self.decl_ana_global_var(&loc, name, type_parameters, type_), _ => {} } } // If this is a schema spec block, process its declaration. if let PA::SpecBlockTarget_::Schema(name, type_params) = &block.value.target.value { self.decl_ana_schema(&block, &name, &type_params); } } fn decl_ana_spec_fun( &mut self, loc: &Loc, name: &PA::FunctionName, signature: &EA::FunctionSignature, ) { let name = self.symbol_pool().make(&name.0.value); let (type_params, params, result_type) = { let et = &mut ExpTranslator::new(self); let type_params = et.analyze_and_add_type_params(&signature.type_parameters); et.enter_scope(); let params = et.analyze_and_add_params(&signature.parameters); let result_type = et.translate_type(&signature.return_type); et.finalize_types(); (type_params, params, result_type) }; // Add the function to the symbol table. let fun_id = SpecFunId::new(self.spec_funs.len()); self.parent.define_spec_fun( loc, self.qualified_by_module(name), self.module_id, fun_id, type_params.iter().map(|(_, ty)| ty.clone()).collect(), params.iter().map(|(_, ty)| ty.clone()).collect(), result_type.clone(), ); // Add a prototype of the SpecFunDecl to the module translator. This // will for now have an empty body which we fill in during a 2nd pass. let fun_decl = SpecFunDecl { loc: loc.clone(), name, type_params, params, result_type, used_spec_vars: BTreeSet::new(), is_pure: true, body: None, }; self.spec_funs.push(fun_decl); } fn decl_ana_global_var( &mut self, loc: &Loc, name: &Name, type_params: &[(Name, PA::Kind)], type_: &EA::Type, ) { let name = self.symbol_pool().make(name.value.as_str()); let (type_params, type_) = { let et = &mut ExpTranslator::new(self); let type_params = et.analyze_and_add_type_params(type_params); let type_ = et.translate_type(type_); (type_params, type_) }; if type_.is_reference() { self.parent.error( loc, &format!( "`{}` cannot have reference type", name.display(self.symbol_pool()) ), ) } // Add the variable to the symbol table. let var_id = SpecVarId::new(self.spec_vars.len()); self.parent.define_spec_var( loc, self.qualified_by_module(name), self.module_id, var_id, project_2nd(&type_params), type_.clone(), ); // Add the variable to the module translator. let var_decl = SpecVarDecl { loc: loc.clone(), name, type_params, type_, }; self.spec_vars.push(var_decl); } fn decl_ana_schema( &mut self, block: &EA::SpecBlock, name: &Name, type_params: &[(Name, PA::Kind)], ) { let qsym = self.qualified_by_module_from_name(name); let mut et = ExpTranslator::new(self); et.enter_scope(); let type_params = et.analyze_and_add_type_params(&type_params); // Extract local variables. let mut vars = vec![]; for member in &block.value.members { if let EA::SpecBlockMember_::Variable { is_global: false, name, type_, type_parameters, } = &member.value { if !type_parameters.is_empty() { et.error( &et.to_loc(&member.loc), "schema variable cannot have type parameters", ); } let name = et.symbol_pool().make(&name.value); let type_ = et.translate_type(type_); vars.push((name, type_)); } } // Add schema declaration prototype to the symbol table. let loc = et.to_loc(&block.loc); self.parent .define_spec_schema(&loc, qsym, self.module_id, type_params, vars); } } /// # Definition Analysis impl<'env, 'translator> ModuleTranslator<'env, 'translator> { fn def_ana( &mut self, module_def: &EA::ModuleDefinition, function_infos: UniqueMap<FunctionName, FunctionInfo>, ) { // Analyze all structs. for (name, def) in &module_def.structs { self.def_ana_struct(&name, def); } // Analyze all schemas. This must be done before other things because schemas need to be // ready for inclusion. We also must do this recursively, so use a visited set to detect // cycles. { let schema_defs: BTreeMap<QualifiedSymbol, &EA::SpecBlock> = module_def .specs .iter() .filter_map(|block| { if let PA::SpecBlockTarget_::Schema(name, ..) = &block.value.target.value { let qsym = self.qualified_by_module_from_name(name); Some((qsym, block)) } else { None } }) .collect(); let mut visited = BTreeSet::new(); let mut visiting = vec![]; for (name, block) in schema_defs.iter() { self.def_ana_schema( &schema_defs, &mut visited, &mut visiting, name.clone(), block, ); } } // Analyze all module level spec blocks (except schemas) for spec in &module_def.specs { if matches!(spec.value.target.value, PA::SpecBlockTarget_::Schema(..)) { continue; } match self.get_spec_block_context(&spec.value.target) { Some(context) => self.def_ana_spec_block(&context, spec), None => { let loc = self.parent.env.to_loc(&spec.value.target.loc); self.parent.error(&loc, "unresolved spec target"); } } } // Analyze in-function spec blocks. for (name, fun_def) in &module_def.functions { let fun_spec_info = &function_infos.get(&name).unwrap().spec_info; let qsym = self.qualified_by_module_from_name(&name.0); for (spec_id, spec_block) in fun_def.specs.iter() { for member in &spec_block.value.members { let loc = &self.parent.env.to_loc(&member.loc); match &member.value { EA::SpecBlockMember_::Condition { kind, exp } => { let context = SpecBlockContext::FunctionCode( qsym.clone(), &fun_spec_info[spec_id], ); if let Some((kind, exp)) = self.extract_condition_kind(&context, kind, exp) { self.def_ana_condition(loc, &context, kind, exp); } } _ => { self.parent.error(&loc, "item not allowed"); } } } } } // Perform post analyzes of spec var usage in spec functions. self.compute_spec_var_usage(); // Perform post reduction of module invariants. self.reduce_module_invariants(); } } /// ## Struct Definition Analysis impl<'env, 'translator> ModuleTranslator<'env, 'translator> { fn def_ana_struct(&mut self, name: &PA::StructName, def: &EA::StructDefinition) { let qsym = self.qualified_by_module_from_name(&name.0); let type_params = self .parent .struct_table .get(&qsym) .expect("struct invalid") .type_params .clone(); let mut et = ExpTranslator::new(self); let loc = et.to_loc(&name.0.loc); for (name, ty) in type_params { et.define_type_param(&loc, name, ty); } let fields = match &def.fields { EA::StructFields::Defined(fields) => { let mut field_map = BTreeMap::new(); for (ref field_name, (idx, ty)) in fields.iter() { let field_sym = et.symbol_pool().make(&field_name.0.value); let field_ty = et.translate_type(&ty); field_map.insert(field_sym, (*idx, field_ty)); } Some(field_map) } EA::StructFields::Native(_) => None, }; self.parent .struct_table .get_mut(&qsym) .expect("struct invalid") .fields = fields; } } /// ## Spec Block Definition Analysis impl<'env, 'translator> ModuleTranslator<'env, 'translator> { fn def_ana_spec_block(&mut self, context: &SpecBlockContext<'_>, block: &EA::SpecBlock) { use EA::SpecBlockMember_::*; for member in &block.value.members { let loc = &self.parent.env.to_loc(&member.loc); match &member.value { Condition { kind, exp } => { if let Some((kind, exp)) = self.extract_condition_kind(context, kind, exp) { self.def_ana_condition(loc, context, kind, exp) } } Function { signature, body, .. } => self.def_ana_spec_fun(signature, body), Include { name, type_arguments, arguments, } => self.def_ana_schema_inclusion_outside_schema( loc, context, None, name, type_arguments.as_deref(), arguments, ), Apply { name, type_arguments, arguments, patterns, exclusion_patterns, } => self.def_ana_schema_apply( loc, context, name, type_arguments.as_deref(), arguments, patterns, exclusion_patterns, ), Pragma { properties } => self.def_ana_pragma(loc, context, properties), Variable { .. } => { /* nothing to do right now */ } } } } } /// ## Pragma Definition Analysis impl<'env, 'translator> ModuleTranslator<'env, 'translator> { /// Definition analysis for a pragma. fn def_ana_pragma( &mut self, _loc: &Loc, context: &SpecBlockContext, properties: &[PA::PragmaProperty], ) { // For now we pass properties just on. We may want to check against a set of known // property names and types. for prop in properties { let prop_name = self.symbol_pool().make(&prop.value.name.value); let value = if let Some(pv) = &prop.value.value { let mut et = ExpTranslator::new(self); if let Some((v, _)) = et.translate_value(pv) { v } else { // Error reported continue; } } else { Value::Bool(true) }; self.update_spec(context, move |spec| { spec.properties.insert(prop_name, value); }); } } } /// ## General Helpers for Definition Analysis impl<'env, 'translator> ModuleTranslator<'env, 'translator> { /// Updates the Spec of a given context via an update function. fn update_spec<F>(&mut self, context: &SpecBlockContext, update: F) where F: FnOnce(&mut Spec), { use SpecBlockContext::*; match context { Function(name) => update( &mut self .fun_specs .entry(name.symbol) .or_insert_with(Spec::default), ), FunctionCode(name, spec_info) => update( &mut self .fun_specs .entry(name.symbol) .or_insert_with(Spec::default) .on_impl .entry(spec_info.offset) .or_insert_with(Spec::default), ), Schema(name) => update( &mut self .parent .spec_schema_table .get_mut(name) .expect("schema defined") .spec, ), Struct(name) => update( &mut self .struct_specs .entry(name.symbol) .or_insert_with(Spec::default), ), Module => update(&mut self.module_spec), } } /// Sets up an expression translator for the given spec block context. If kind /// is given, includes all the symbols which can be consumed by the condition, /// otherwise only defines type parameters. fn exp_translator_for_context<'module_translator>( &'module_translator mut self, loc: &Loc, context: &SpecBlockContext, kind_opt: Option<&ConditionKind>, ) -> ExpTranslator<'env, 'translator, 'module_translator> { use SpecBlockContext::*; let allow_old = if let Some(kind) = kind_opt { kind.allows_old() } else { false }; match context { Function(name) => { let entry = &self .parent .fun_table .get(name) .expect("invalid spec block context") .clone(); let mut et = ExpTranslator::new_with_old(self, allow_old); for (n, ty) in &entry.type_params { et.define_type_param(loc, *n, ty.clone()); } if let Some(kind) = kind_opt { et.enter_scope(); for (n, ty) in &entry.params { et.define_local(loc, *n, ty.clone(), None); } // Define the placeholders for the result values of a function if this is an // Ensures condition. if matches!(kind, ConditionKind::Ensures) { et.enter_scope(); if let Type::Tuple(ts) = &entry.result_type { for (i, ty) in ts.iter().enumerate() { let name = et.symbol_pool().make(&format!("result_{}", i + 1)); et.define_local(loc, name, ty.clone(), Some(Operation::Result(i))); } } else { let name = et.symbol_pool().make("result"); et.define_local( loc, name, entry.result_type.clone(), Some(Operation::Result(0)), ); } } } et } FunctionCode(name, spec_info) => { let entry = &self .parent .fun_table .get(name) .expect("invalid spec block context") .clone(); let mut et = ExpTranslator::new_with_old(self, allow_old); for (n, ty) in &entry.type_params { et.define_type_param(loc, *n, ty.clone()); } if kind_opt.is_some() { et.enter_scope(); for (n, info) in &spec_info.used_locals { let sym = et.symbol_pool().make(n.0.value.as_str()); let ty = et.translate_hlir_single_type(&info.type_); if ty == Type::Error { et.error( loc, "[internal] error in translating hlir type to prover type", ); } et.define_local(loc, sym, ty, Some(Operation::Local(sym))); } } et } Struct(name) => { let entry = &self .parent .struct_table .get(name) .expect("invalid spec block context") .clone(); let mut et = ExpTranslator::new_with_old(self, allow_old); for (n, ty) in &entry.type_params { et.define_type_param(loc, *n, ty.clone()); } if kind_opt.is_some() { if let Some(fields) = &entry.fields { et.enter_scope(); for (n, (_, ty)) in fields { et.define_local( loc, *n, ty.clone(), Some(Operation::Select( entry.module_id, entry.struct_id, FieldId::new(*n), )), ); } } } et } Module => ExpTranslator::new(self), Schema(name) => { let entry = self .parent .spec_schema_table .get(name) .expect("schema defined"); // Unfortunately need to clone elements from the entry because we need mut borrow // of self for expression translator. let type_params = entry.type_params.clone(); let all_vars = entry.all_vars.clone(); let mut et = ExpTranslator::new_with_old(self, allow_old); for (n, ty) in type_params { et.define_type_param(loc, n, ty); } if kind_opt.is_some() { et.enter_scope(); for (n, entry) in all_vars { et.define_local(loc, n, entry.type_, None); } } et } } } } /// ## Condition Definition Analysis impl<'env, 'translator> ModuleTranslator<'env, 'translator> { /// Check whether the condition is allowed in the given context. Return true if so, otherwise /// report an error and return false. fn check_condition_is_valid( &mut self, context: &SpecBlockContext, loc: &Loc, kind: &ConditionKind, error_msg: &str, ) -> bool { use SpecBlockContext::*; let ok = match context { Module => kind.allowed_on_module(), Struct(_) => kind.allowed_on_struct(), Function(name) => { let entry = self.parent.fun_table.get(name).expect("function defined"); if entry.is_public { kind.allowed_on_public_fun_decl() } else { kind.allowed_on_private_fun_decl() } } FunctionCode(_, _) => kind.allowed_on_fun_impl(), Schema(_) => true, }; if !ok { self.parent.error(loc, &format!("`{}` {}", kind, error_msg)); } ok } /// Add the given conditions to the context, after checking whether they are valid in the /// context. Reports errors for invalid conditions. fn add_conditions_to_context( &mut self, context: &SpecBlockContext, loc: &Loc, conditions: Vec<Condition>, error_msg: &str, ) { for cond in conditions { // If this is an invariant on a function decl, transform it into a pair of // requires and ensures. let derived_conds = match cond { Condition { loc, kind: kind @ ConditionKind::Invariant, exp, } | Condition { loc, kind: kind @ ConditionKind::InvariantModule, exp, } if matches!(context, SpecBlockContext::Function(..)) => { let requires_kind = if kind == ConditionKind::InvariantModule { ConditionKind::RequiresModule } else { ConditionKind::Requires }; vec![ Condition { loc: loc.clone(), kind: requires_kind, exp: exp.clone(), }, Condition { loc, kind: ConditionKind::Ensures, exp, }, ] } _ => vec![cond], }; for derived_cond in derived_conds { if self.check_condition_is_valid(context, loc, &derived_cond.kind, error_msg) { self.update_spec(context, |spec| spec.conditions.push(derived_cond)); } } } } /// Definition analysis for a condition. fn def_ana_condition( &mut self, loc: &Loc, context: &SpecBlockContext, kind: ConditionKind, exp: &EA::Exp, ) { if kind == ConditionKind::Decreases { self.parent .error(loc, "decreases specification not supported currently"); return; } let expected_type = self.expected_type_for_condition(&kind); let mut et = self.exp_translator_for_context(loc, context, Some(&kind)); let translated = et.translate_exp(exp, &expected_type); et.finalize_types(); self.add_conditions_to_context( context, loc, vec![Condition { loc: loc.clone(), kind, exp: translated, }], "not allowed in this context", ); } /// Compute the expected type for the expression in a condition. fn expected_type_for_condition(&mut self, kind: &ConditionKind) -> Type { if let Some((mid, vid, ty_args)) = kind.get_spec_var_target() { if mid == self.module_id { self.spec_vars[vid.as_usize()] .type_ .clone() .instantiate(&ty_args) } else { let module_env = self.parent.env.get_module(mid); module_env .get_spec_var(vid) .type_ .clone() .instantiate(&ty_args) } } else { BOOL_TYPE.clone() } } /// Extracts a condition kind based on the parsed kind and the associated expression. This /// identifies a spec var assignment expression and moves the var to the SpecConditionKind enum /// we use in our AST, returning the rhs expression of the assignment; otherwise it returns /// the passed expression. fn extract_condition_kind<'a>( &mut self, context: &SpecBlockContext, kind: &PA::SpecConditionKind, exp: &'a EA::Exp, ) -> Option<(ConditionKind, &'a EA::Exp)> { use ConditionKind::*; use PA::SpecConditionKind as PK; let loc = self.parent.env.to_loc(&exp.loc); match kind { PK::Assert => Some((Assert, exp)), PK::Assume => Some((Assume, exp)), PK::Decreases => Some((Decreases, exp)), PK::Ensures => Some((Ensures, exp)), PK::Requires => Some((Requires, exp)), PK::AbortsIf => Some((AbortsIf, exp)), PK::RequiresModule => Some((RequiresModule, exp)), PK::Invariant => Some((Invariant, exp)), PK::InvariantModule => Some((InvariantModule, exp)), PK::InvariantUpdate => { if let Some((mid, vid, tys, exp1)) = self.extract_assignment(context, exp) { Some((VarUpdate(mid, vid, tys), exp1)) } else { Some((InvariantUpdate, exp)) } } PK::InvariantPack => { if let Some((mid, vid, tys, exp1)) = self.extract_assignment(context, exp) { Some((VarPack(mid, vid, tys), exp1)) } else { self.parent .error(&loc, "expected assignment to spec variable"); None } } PK::InvariantUnpack => { if let Some((mid, vid, tys, exp1)) = self.extract_assignment(context, exp) { Some((VarUnpack(mid, vid, tys), exp1)) } else { self.parent .error(&loc, "expected assignment to spec variable"); None } } } } /// Extracts an assignment from an expression, returning the assigned spec var and /// rhs expression. fn extract_assignment<'a>( &mut self, context: &SpecBlockContext, exp: &'a EA::Exp, ) -> Option<(ModuleId, SpecVarId, Vec<Type>, &'a EA::Exp)> { if let EA::Exp_::Assign(list, rhs) = &exp.value { let var_loc = self.parent.to_loc(&list.loc); if list.value.len() != 1 { self.parent.error( &var_loc, "[current restriction] tuples not supported in assignment", ); return None; } if let EA::LValue_::Var(maccess, tys_opt) = &list.value[0].value { let var_name = self.module_access_to_qualified(maccess); let mut et = self.exp_translator_for_context(&var_loc, context, None); let tys = tys_opt .as_ref() .map(|tys| et.translate_types(tys)) .unwrap_or_else(|| vec![]); if let Some(spec_var) = et.parent.parent.spec_var_table.get(&var_name) { Some((spec_var.module_id, spec_var.var_id, tys, rhs.as_ref())) } else { et.error( &var_loc, &format!( "spec global `{}` undeclared", var_name.display(et.symbol_pool()) ), ); None } } else { self.parent.error( &var_loc, "[current restriction] unpack not supported in assignment", ); None } } else { None } } } /// ## Spec Function Definition Analysis impl<'env, 'translator> ModuleTranslator<'env, 'translator> { /// Definition analysis for a specification helper function. fn def_ana_spec_fun(&mut self, _signature: &EA::FunctionSignature, body: &EA::FunctionBody) { if let EA::FunctionBody_::Defined(seq) = &body.value { let entry = &self.spec_funs[self.spec_fun_index]; let type_params = entry.type_params.clone(); let params = entry.params.clone(); let result_type = entry.result_type.clone(); let mut et = ExpTranslator::new(self); let loc = et.to_loc(&body.loc); for (n, ty) in type_params { et.define_type_param(&loc, n, ty); } et.enter_scope(); for (n, ty) in params { et.define_local(&loc, n, ty, None); } let translated = et.translate_seq(&loc, seq, &result_type); et.finalize_types(); self.spec_funs[self.spec_fun_index].body = Some(translated); } self.spec_fun_index += 1; } } /// ## Schema Definition Analysis impl<'env, 'translator> ModuleTranslator<'env, 'translator> { /// Definition analysis for a schema. This proceeds in two steps: first we ensure recursively /// that all included schemas are analyzed, checking for cycles. Then we actually analyze this /// schema's content. fn def_ana_schema( &mut self, schema_defs: &BTreeMap<QualifiedSymbol, &EA::SpecBlock>, visited: &mut BTreeSet<QualifiedSymbol>, visiting: &mut Vec<QualifiedSymbol>, name: QualifiedSymbol, block: &EA::SpecBlock, ) { if !visited.insert(name.clone()) { // Already analyzed. return; } visiting.push(name.clone()); // First recursively visit all schema includes and ensure they are analyzed. for (include_loc, included_name, ..) in self.iter_schema_includes(&block.value.members) { let include_loc = self.parent.env.to_loc(include_loc); let included_name = self.module_access_to_qualified(included_name); if included_name.module_name == self.module_name { // A schema in the module we are currently analyzing. We need to check // for cycles before recursively analyzing it. if visiting.contains(&included_name) { self.parent.error( &include_loc, &format!( "cyclic schema dependency: {} -> {}", visiting .iter() .map(|name| format!("{}", name.display_simple(self.symbol_pool()))) .join(" -> "), included_name.display_simple(self.symbol_pool()) ), ) } else if let Some(included_block) = schema_defs.get(&included_name) { // Recursively analyze it, if its defined. If not, we report an undeclared // error in 2nd phase. self.def_ana_schema( schema_defs, visited, visiting, included_name, included_block, ); } } } // Now actually analyze this schema. self.def_ana_schema_content(name, block); // Remove from visiting list visiting.pop(); } /// Analysis of schema after it is ensured that all included schemas are fully analyzed. fn def_ana_schema_content(&mut self, name: QualifiedSymbol, block: &EA::SpecBlock) { let loc = self.parent.env.to_loc(&block.loc); let entry = self .parent .spec_schema_table .get(&name) .expect("schema defined"); // Process all schema includes. We need to do this before we type check expressions to have // all variables from includes in the environment. let type_params = entry.type_params.clone(); let mut all_vars: BTreeMap<Symbol, LocalVarEntry> = entry .vars .iter() .map(|(n, ty)| { ( *n, LocalVarEntry { loc: loc.clone(), type_: ty.clone(), operation: None, }, ) }) .collect(); let mut included_spec = Spec::default(); for (include_loc, include_name, type_arguments, arguments) in self.iter_schema_includes(&block.value.members) { let include_loc = self.parent.env.to_loc(include_loc); let include_name = self.module_access_to_qualified(include_name); self.def_ana_schema_inclusion( &type_params, &mut all_vars, &mut included_spec, true, &include_loc, include_name, type_arguments, arguments, ); } // Store the results back to the schema entry. { let entry = self .parent .spec_schema_table .get_mut(&name) .expect("schema defined"); entry.all_vars = all_vars; entry.included_spec = included_spec; } // Now process all conditions and invariants. for member in &block.value.members { let member_loc = self.parent.to_loc(&member.loc); match &member.value { EA::SpecBlockMember_::Variable { is_global: false, .. } => { /* handled during decl analysis */ } EA::SpecBlockMember_::Include { .. } => { /* handled above */ } EA::SpecBlockMember_::Condition { kind, exp } => { let context = SpecBlockContext::Schema(name.clone()); if let Some((kind, exp)) = self.extract_condition_kind(&context, kind, exp) { self.def_ana_condition(&member_loc, &context, kind, exp); } else { // Error reported. } } _ => { self.parent.error(&member_loc, "item not allowed in schema"); } }; } } /// Extracts all schema inclusions from a list of spec block members. fn iter_schema_includes<'a>( &self, members: &'a [EA::SpecBlockMember], ) -> impl Iterator< Item = ( &'a MoveIrLoc, &'a EA::ModuleAccess, Option<&'a [EA::Type]>, &'a [(Name, EA::Exp)], ), > { members.iter().filter_map(|m| { if let EA::SpecBlockMember_::Include { name, type_arguments, arguments, } = &m.value { Some(( &m.loc, name, type_arguments.as_deref(), arguments.as_slice(), )) } else { None } }) } /// Analyzes a schema inclusion. Depending on whether `allow_new_vars` is true, this will /// add new variables to `vars`, and match types of existing ones. All conditions and invariants /// from the schema are rewritten for the inclusion context and added to the provided vectors. fn def_ana_schema_inclusion( &mut self, context_type_params: &[(Symbol, Type)], vars: &mut BTreeMap<Symbol, LocalVarEntry>, spec: &mut Spec, allow_new_vars: bool, loc: &Loc, schema_name: QualifiedSymbol, type_arguments: Option<&[EA::Type]>, arguments: &[(Name, EA::Exp)], ) { // We need to temporarily detach the schema entry from the parent table because of // borrowing problems, as we need to traverse it while at the same type mutate self. let schema_entry = if let Some(e) = self.parent.spec_schema_table.remove(&schema_name) { e } else { self.parent.error( loc, &format!( "schema `{}` undeclared", schema_name.display(self.symbol_pool()) ), ); return; }; let mut et = ExpTranslator::new(self); for (n, ty) in context_type_params { et.define_type_param(loc, *n, ty.clone()) } let type_arguments = &et.translate_types_opt(type_arguments); if schema_entry.type_params.len() != type_arguments.len() { self.parent.error( loc, &format!( "wrong number of type arguments (expected {}, got {})", schema_entry.type_params.len(), type_arguments.len() ), ); // Don't forget to put schema back. self.parent .spec_schema_table .insert(schema_name, schema_entry); return; } // Define locals as we need them for checking schema arguments. et.enter_scope(); for ( n, LocalVarEntry { loc, type_, operation, }, ) in vars.iter() { et.define_local(loc, *n, type_.clone(), operation.clone()); } let mut argument_map: BTreeMap<Symbol, Exp> = arguments .iter() .map(|(schema_var, exp)| { let pool = et.symbol_pool(); let schema_sym = pool.make(&schema_var.value); let schema_type = if let Some(LocalVarEntry { type_, .. }) = schema_entry.all_vars.get(&schema_sym) { type_.instantiate(type_arguments) } else { et.error( &et.to_loc(&schema_var.loc), &format!("`{}` not declared in schema", schema_sym.display(pool)), ); Type::Error }; // Check the expression in the argument list. // Note we currently only use the vars defined so far in this context. Variables // which are introduced by schemas after the inclusion of this one are not in scope. let exp = et.translate_exp(exp, &schema_type); et.finalize_types(); (schema_sym, exp) }) .collect(); // Go over all variables in the schema which are not in the argument map and either match // them against existing one or declare new, if allowed. for (name, LocalVarEntry { type_, .. }) in &schema_entry.all_vars { if argument_map.contains_key(name) { continue; } let ty = type_.instantiate(type_arguments); let pool = self.symbol_pool(); if let Some(entry) = vars.get(name) { // Name already exists in inclusion context, check its type. let mut subs = Substitution::new(); let tctx = &TypeDisplayContext::WithEnv { env: self.parent.env, }; let compatible = subs.unify(&tctx, &entry.type_, &ty).is_ok(); if !compatible { self.parent.error( loc, &format!( "incompatible type of included `{}`; type in schema: `{}`, type in inclusion context: `{}`", name.display(pool), ty.display(tctx), entry.type_.display(tctx), )); } // Put into argument map. let node_id = self.new_node_id(); self.type_map.insert(node_id, entry.type_.clone()); self.loc_map.insert(node_id, entry.loc.clone()); let exp = if let Some(oper) = &entry.operation { Exp::Call(node_id, oper.clone(), vec![]) } else { Exp::LocalVar(node_id, *name) }; argument_map.insert(*name, exp); } else if allow_new_vars { // Name does not yet exists in inclusion context, but is allowed to be introduced. // This happens if we include a schema in another schema. vars.insert( *name, LocalVarEntry { loc: loc.clone(), type_: ty.clone(), operation: None, }, ); } else { self.parent.error( loc, &format!( "`{}` cannot be matched to an existing name in inclusion context", name.display(pool) ), ); } } // Go over all conditions in the schema, rewrite them, and add to the inclusion conditions. for Condition { loc, kind, exp } in schema_entry .spec .conditions .iter() .chain(schema_entry.included_spec.conditions.iter()) { let mut rewriter = ExpRewriter::new(self, schema_entry.module_id, &argument_map, type_arguments); spec.conditions.push(Condition { loc: loc.clone(), kind: kind.clone(), exp: rewriter.rewrite(exp), }); } // Put schema entry back. self.parent .spec_schema_table .insert(schema_name, schema_entry); } /// Analyze schema inclusion in the spec block for a function, struct or module. This /// instantiates the schema and adds all conditions and invariants it contains to the context. /// /// The `alt_context_type_params` allows to use different type parameter names as would /// otherwise be inferred from the SchemaBlockContext. This is used for the apply weaving /// operator which allows to use different type parameter names than the function declarations /// to which it is applied to. fn def_ana_schema_inclusion_outside_schema( &mut self, loc: &Loc, context: &SpecBlockContext, alt_context_type_params: Option<&[(Symbol, Type)]>, name: &EA::ModuleAccess, type_arguments: Option<&[EA::Type]>, arguments: &[(Name, EA::Exp)], ) { let name = self.module_access_to_qualified(name); // Compute the type parameters and variables this spec block uses. We do this by constructing // an expression translator and immediately extracting from it. Depending on whether in // function or struct context, we use a condition/invariant kind which defines the maximum // of available symbols. We need to potentially revise this to only declare variables which // have a proper use in a condition/invariant, depending on what is actually included in // the block. let (mut vars, context_type_params) = match context { SpecBlockContext::Function(..) | SpecBlockContext::FunctionCode(..) => { let et = self.exp_translator_for_context(loc, context, Some(&ConditionKind::Ensures)); (et.extract_var_map(), et.extract_type_params()) } SpecBlockContext::Struct(..) => { let et = self.exp_translator_for_context( loc, context, Some(&ConditionKind::InvariantUpdate), ); (et.extract_var_map(), et.extract_type_params()) } SpecBlockContext::Module => (BTreeMap::new(), vec![]), SpecBlockContext::Schema { .. } => panic!("unexpected schema context"), }; let mut spec = Spec::default(); // Analyze the schema inclusion. This will instantiate conditions for // this block. self.def_ana_schema_inclusion( if let Some(type_params) = alt_context_type_params { type_params } else { &context_type_params }, &mut vars, &mut spec, false, loc, name, type_arguments, arguments, ); // Write the conditions to the context item. // TODO: merge pragma properties as well? self.add_conditions_to_context( context, loc, spec.conditions, "(included from schema) not allowed in this context", ); } fn def_ana_schema_apply( &mut self, loc: &Loc, context: &SpecBlockContext, name: &EA::ModuleAccess, type_arguments: Option<&[EA::Type]>, arguments: &[(Name, EA::Exp)], patterns: &[PA::SpecApplyPattern], exclusion_patterns: &[PA::SpecApplyPattern], ) { if !matches!(context, SpecBlockContext::Module) { self.parent.error( loc, "the `apply` schema weaving operator can only be used inside a `spec module` block", ); return; } for fun_name in self.parent.fun_table.keys().cloned().collect_vec() { // Note we need the vector clone above to avoid borrowing self for the // whole loop. let entry = self.parent.fun_table.get(&fun_name).unwrap(); if entry.module_id != self.module_id { // Not a function from this module continue; } let is_public = entry.is_public; let type_arg_count = entry.type_params.len(); let is_excluded = exclusion_patterns.iter().any(|p| { self.apply_pattern_matches(fun_name.symbol, is_public, type_arg_count, true, p) }); if is_excluded { // Explicitly excluded from matching. continue; } if let Some(matched) = patterns.iter().find(|p| { self.apply_pattern_matches(fun_name.symbol, is_public, type_arg_count, false, p) }) { // This is a match, so apply this schema to this function. let type_params = { let mut et = ExpTranslator::new(self); et.analyze_and_add_type_params(&matched.value.type_parameters); et.extract_type_params() }; self.def_ana_schema_inclusion_outside_schema( loc, &SpecBlockContext::Function(fun_name), Some(&type_params), name, type_arguments, arguments, ); } } } /// Returns true if the pattern matches the function of name, type arity, and /// visibility. /// /// The `ignore_type_args` parameter is used for exclusion matches. In exclusion matches we /// do not want to include type args because its to easy for a user to get this wrong, so /// we match based only on visibility and name pattern. On the other hand, we want a user /// in inclusion matches to use a pattern like `*<X>` to match any generic function with /// one type argument. fn apply_pattern_matches( &self, name: Symbol, is_public: bool, type_arg_count: usize, ignore_type_args: bool, pattern: &PA::SpecApplyPattern, ) -> bool { if !ignore_type_args && pattern.value.type_parameters.len() != type_arg_count { return false; } if let Some(v) = &pattern.value.visibility { match v { PA::FunctionVisibility::Public(..) => { if !is_public { return false; } } PA::FunctionVisibility::Internal => { if is_public { return false; } } } } let rex = Regex::new(&format!( "^{}$", pattern .value .name_pattern .iter() .map(|p| match &p.value { PA::SpecApplyFragment_::Wildcard => ".*".to_string(), PA::SpecApplyFragment_::NamePart(n) => n.value.clone(), }) .join("") )) .expect("regex valid"); rex.is_match(self.symbol_pool().string(name).as_str()) } } /// ## Spec Var Usage Analysis impl<'env, 'translator> ModuleTranslator<'env, 'translator> { /// Compute spec var usage of spec funs. fn compute_spec_var_usage(&mut self) { let mut visited = BTreeSet::new(); for idx in 0..self.spec_funs.len() { self.compute_spec_var_usage_for_fun(&mut visited, idx); } // Check for purity requirements. All data invariants must be pure expressions and // not depend on global state. let check_pure = |mid: ModuleId, fid: SpecFunId| { if mid.to_usize() < self.parent.env.get_module_count() { // This is calling a function from another module we already have // translated. let module_env = self.parent.env.get_module(mid); module_env.get_spec_fun(fid).is_pure } else { // This is calling a function from the module we are currently translating. self.spec_funs[fid.as_usize()].is_pure } }; for struct_spec in self.struct_specs.values() { for cond in &struct_spec.conditions { if cond.kind == ConditionKind::Invariant && !cond.exp.is_pure(&check_pure) { self.parent.error( &cond.loc, "data invariants cannot depend on global state \ (directly or indirectly uses a global spec var or resource storage).", ); } } } } /// Compute spec var usage for a given spec fun, defined via its index into the spec_funs /// vector of the currently translated module. This recursively computes the values for /// functions called from this one; the visited set is there to break cycles. fn compute_spec_var_usage_for_fun(&mut self, visited: &mut BTreeSet<usize>, fun_idx: usize) { if !visited.insert(fun_idx) { return; } // Detach the current SpecFunDecl body so we can traverse it while at the same time mutating // the full self. Rust requires us to do so (at least the author doesn't know better yet), // but moving it should be not too expensive. let body = if self.spec_funs[fun_idx].body.is_some() { std::mem::replace(&mut self.spec_funs[fun_idx].body, None).unwrap() } else { // Native function: assume it is impure. We need a modifier to declare otherwise self.spec_funs[fun_idx].is_pure = false; return; }; let mut used_spec_vars = BTreeSet::new(); let mut is_pure = true; body.visit(&mut |e: &Exp| { match e { Exp::SpecVar(_, mid, vid) => { used_spec_vars.insert((*mid, *vid)); is_pure = false; } Exp::Call(_, Operation::Function(mid, fid), _) => { if mid.to_usize() < self.parent.env.get_module_count() { // This is calling a function from another module we already have // translated. let module_env = self.parent.env.get_module(*mid); let fun_decl = module_env.get_spec_fun(*fid); used_spec_vars.extend(&fun_decl.used_spec_vars); is_pure = is_pure && fun_decl.is_pure } else { // This is calling a function from the module we are currently translating. // Need to recursively ensure we have computed used_spec_vars because of // arbitrary call graphs, including cyclic. self.compute_spec_var_usage_for_fun(visited, fid.as_usize()); let fun_decl = &self.spec_funs[fid.as_usize()]; used_spec_vars.extend(&fun_decl.used_spec_vars); is_pure = is_pure && fun_decl.is_pure; } } Exp::Call(_, Operation::Sender, _) | Exp::Call(_, Operation::Global, _) | Exp::Call(_, Operation::Exists, _) => is_pure = false, _ => {} } }); // Store result back. let fun_decl = &mut self.spec_funs[fun_idx]; fun_decl.body = Some(body); fun_decl.used_spec_vars = used_spec_vars; fun_decl.is_pure = is_pure; } } /// ## Module Invariant Reduction impl<'env, 'translator> ModuleTranslator<'env, 'translator> { /// Reduce module invariants by making them requires/ensures on each function. fn reduce_module_invariants(&mut self) { for mut cond in self.module_spec.conditions.iter().cloned().collect_vec() { assert_eq!(cond.kind, ConditionKind::Invariant); // An Invariant on module level becomes an InvariantModule on function level // (which is then further reduced to a pair of RequiresModule and Ensures). // Only public functions receive it. cond.kind = ConditionKind::InvariantModule; for qname in self .parent .fun_table .keys() .filter(|qn| qn.module_name == self.module_name) .cloned() .collect_vec() { let entry = self.parent.fun_table.get(&qname).unwrap(); if entry.is_public { let context = SpecBlockContext::Function(qname); // The below should not generate an error because of the above assert. self.add_conditions_to_context( &context, &cond.loc.clone(), vec![cond.clone()], "[internal] (included via module level invariant) not allowed in this context", ) } } } } } /// # Environment Population impl<'env, 'translator> ModuleTranslator<'env, 'translator> { fn populate_env_from_result( &mut self, loc: Loc, module: CompiledModule, source_map: SourceMap<MoveIrLoc>, ) { let struct_data: BTreeMap<StructId, StructData> = (0..module.struct_defs().len()) .filter_map(|idx| { let def_idx = StructDefinitionIndex(idx as u16); let handle_idx = module.struct_def_at(def_idx).struct_handle; let handle = module.struct_handle_at(handle_idx); let view = StructHandleView::new(&module, handle); let name = self.symbol_pool().make(view.name().as_str()); if let Some(entry) = self .parent .struct_table .get(&self.qualified_by_module(name)) { let struct_spec = self .struct_specs .remove(&name) .unwrap_or_else(Spec::default); // Ensure that all invariant kinds Some(( StructId::new(name), self.parent.env.create_struct_data( &module, def_idx, name, entry.loc.clone(), struct_spec, ), )) } else { self.parent.error( &self.parent.env.internal_loc(), &format!("[internal] bytecode does not match AST: `{}` in bytecode but not in AST", name.display(self.symbol_pool()))); None } }) .collect(); let function_data: BTreeMap<FunId, FunctionData> = (0..module.function_defs().len()) .filter_map(|idx| { let def_idx = FunctionDefinitionIndex(idx as u16); let handle_idx = module.function_def_at(def_idx).function; let handle = module.function_handle_at(handle_idx); let view = FunctionHandleView::new(&module, handle); let mut name_str = view.name().as_str(); // Script functions have different names in AST and bytecode; adjust. if name_str == SCRIPT_BYTECODE_FUN_NAME { name_str = SCRIPT_AST_FUN_NAME; } let name = self.symbol_pool().make(name_str); let fun_spec = self.fun_specs.remove(&name).unwrap_or_else(Spec::default); if let Some(entry) = self.parent.fun_table.get(&self.qualified_by_module(name)) { let arg_names = project_1st(&entry.params); let type_arg_names = project_1st(&entry.type_params); Some((FunId::new(name), self.parent.env.create_function_data( &module, def_idx, name, entry.loc.clone(), arg_names, type_arg_names, fun_spec, ))) } else { let funs = self.parent.fun_table.iter().map(|(k, _)| { format!("{}", k.display_full(self.symbol_pool())) }).join(", "); self.parent.error( &self.parent.env.internal_loc(), &format!("[internal] bytecode does not match AST: `{}` in bytecode but not in AST (available in AST: {})", name.display(self.symbol_pool()), funs)); None } }) .collect(); self.parent.env.add( loc, module, source_map, struct_data, function_data, std::mem::take(&mut self.spec_vars), std::mem::take(&mut self.spec_funs), std::mem::take(&mut self.module_spec), std::mem::take(&mut self.loc_map), std::mem::take(&mut self.type_map), std::mem::take(&mut self.instantiation_map), ); } } // ================================================================================================= /// # Expression and Type Translation #[derive(Debug)] pub struct ExpTranslator<'env, 'translator, 'module_translator> { parent: &'module_translator mut ModuleTranslator<'env, 'translator>, /// A symbol table for type parameters. type_params_table: BTreeMap<Symbol, Type>, /// A scoped symbol table for local names. The first element in the list contains the most /// inner scope. local_table: LinkedList<BTreeMap<Symbol, LocalVarEntry>>, /// When compiling a condition, the result type of the function the condition is associated /// with. result_type: Option<Type>, /// Status for the `old(...)` expression form. old_status: OldExpStatus, /// The currently build type substitution. subs: Substitution, /// A counter for generating type variables. type_var_counter: u16, /// A marker to indicate the node_counter start state. node_counter_start: usize, } #[derive(Debug, Clone)] struct LocalVarEntry { loc: Loc, type_: Type, // If this local is associated with an operation, this is set. operation: Option<Operation>, } #[derive(Debug, PartialEq)] enum OldExpStatus { NotSupported, OutsideOld, InsideOld, } /// ## General impl<'env, 'translator, 'module_translator> ExpTranslator<'env, 'translator, 'module_translator> { fn new(parent: &'module_translator mut ModuleTranslator<'env, 'translator>) -> Self { let node_counter_start = parent.node_counter; Self { parent, type_params_table: BTreeMap::new(), local_table: LinkedList::new(), result_type: None, old_status: OldExpStatus::NotSupported, subs: Substitution::new(), type_var_counter: 0, node_counter_start, } } fn new_with_old( parent: &'module_translator mut ModuleTranslator<'env, 'translator>, allow_old: bool, ) -> Self { let mut et = ExpTranslator::new(parent); if allow_old { et.old_status = OldExpStatus::OutsideOld; } else { et.old_status = OldExpStatus::NotSupported; }; et } /// Extract a map from names to types from the scopes of this translator. fn extract_var_map(&self) -> BTreeMap<Symbol, LocalVarEntry> { let mut vars: BTreeMap<Symbol, LocalVarEntry> = BTreeMap::new(); for s in &self.local_table { vars.extend(s.clone()); } vars } // Extract type parameters from this translator. fn extract_type_params(&self) -> Vec<(Symbol, Type)> { self.type_params_table .iter() .map(|(n, ty)| (*n, ty.clone())) .collect_vec() } /// Shortcut for accessing symbol pool. fn symbol_pool(&self) -> &SymbolPool { self.parent.parent.env.symbol_pool() } /// Shortcut for translating a Move AST location into ours. fn to_loc(&self, loc: &move_ir_types::location::Loc) -> Loc { self.parent.parent.env.to_loc(loc) } /// Shortcut for reporting an error. fn error(&self, loc: &Loc, msg: &str) { self.parent.parent.error(loc, msg); } /// Creates a fresh type variable. fn fresh_type_var(&mut self) -> Type { let var = Type::Var(self.type_var_counter); self.type_var_counter += 1; var } /// Creates a new node id. fn new_node_id(&mut self) -> NodeId { self.parent.new_node_id() } /// Creates a new node id and assigns type and location to it. fn new_node_id_with_type_loc(&mut self, ty: &Type, loc: &Loc) -> NodeId { let id = self.new_node_id(); self.parent.loc_map.insert(id, loc.clone()); self.parent.type_map.insert(id, ty.clone()); id } /// Sets instantiation for the given node id. fn set_instantiation(&mut self, node_id: NodeId, instantiation: Vec<Type>) { self.parent.instantiation_map.insert(node_id, instantiation); } /// Finalizes types in this translator, producing errors if some could not be inferred /// and remained incomplete. fn finalize_types(&mut self) { if self.parent.parent.env.has_errors() { // Don't do that check if we already reported errors, as this would produce // useless followup errors. return; } for i in self.node_counter_start..self.parent.node_counter { let node_id = NodeId::new(i); if let Some(ty) = self.parent.type_map.get(&node_id) { let ty = self.finalize_type(node_id, ty); self.parent.type_map.insert(node_id.clone(), ty); } if let Some(inst) = self.parent.instantiation_map.get(&node_id) { let inst = inst .iter() .map(|ty| self.finalize_type(node_id, ty)) .collect_vec(); self.parent.instantiation_map.insert(node_id.clone(), inst); } } } /// Finalize the the given type, producing an error if it is not complete. fn finalize_type(&self, node_id: NodeId, ty: &Type) -> Type { let ty = self.subs.specialize(ty); if ty.is_incomplete() { // This type could not be fully inferred. let loc = if let Some(loc) = self.parent.loc_map.get(&node_id) { loc.clone() } else { self.parent.parent.env.unknown_loc() }; self.error( &loc, &format!( "unable to infer type: `{}`", ty.display(&self.type_display_context()) ), ); } ty } /// Constructs a type display context used to visualize types in error messages. fn type_display_context(&self) -> TypeDisplayContext<'_> { TypeDisplayContext::WithoutEnv { symbol_pool: self.symbol_pool(), reverse_struct_table: &self.parent.parent.reverse_struct_table, } } /// Creates an error expression. fn new_error_exp(&mut self) -> Exp { let id = self.new_node_id_with_type_loc(&Type::Error, &self.parent.parent.env.internal_loc()); Exp::Error(id) } /// Enters a new scope in the locals table. fn enter_scope(&mut self) { self.local_table.push_front(BTreeMap::new()); } /// Exits the most inner scope of the locals table. fn exit_scope(&mut self) { self.local_table.pop_front(); } /// Defines a type parameter. fn define_type_param(&mut self, loc: &Loc, name: Symbol, ty: Type) { if self.type_params_table.insert(name, ty).is_some() { let param_name = name.display(self.symbol_pool()); self.parent .parent .error(loc, &format!("duplicate declaration of `{}`", param_name)); } } /// Defines a local in the most inner scope. This produces an error /// if the name already exists. The invariant option is used for names /// which appear as locals in expressions, but are actually implicit selections /// of fields of an underlying struct. fn define_local(&mut self, loc: &Loc, name: Symbol, type_: Type, operation: Option<Operation>) { let entry = LocalVarEntry { loc: loc.clone(), type_, operation, }; if let Some(old) = self .local_table .front_mut() .expect("symbol table empty") .insert(name, entry) { let display = name.display(self.symbol_pool()); self.error(loc, &format!("duplicate declaration of `{}`", display)); self.error(&old.loc, &format!("previous declaration of `{}`", display)); } } /// Lookup a local in this translator. fn lookup_local(&mut self, name: Symbol) -> Option<&LocalVarEntry> { for scope in &self.local_table { if let Some(entry) = scope.get(&name) { return Some(entry); } } None } /// Analyzes the sequence of type parameters as they are provided via the source AST and enters /// them into the environment. Returns a vector for representing them in the target AST. fn analyze_and_add_type_params( &mut self, type_params: &[(Name, PA::Kind)], ) -> Vec<(Symbol, Type)> { type_params .iter() .enumerate() .map(|(i, (n, _))| { let ty = Type::TypeParameter(i as u16); let sym = self.symbol_pool().make(n.value.as_str()); self.define_type_param(&self.to_loc(&n.loc), sym, ty.clone()); (sym, ty) }) .collect_vec() } /// Analyzes the sequence of function parameters as they are provided via the source AST and /// enters them into the environment. Returns a vector for representing them in the target AST. fn analyze_and_add_params(&mut self, params: &[(PA::Var, EA::Type)]) -> Vec<(Symbol, Type)> { params .iter() .map(|(v, ty)| { let ty = self.translate_type(ty); let sym = self.symbol_pool().make(v.0.value.as_str()); self.define_local(&self.to_loc(&v.0.loc), sym, ty.clone(), None); (sym, ty) }) .collect_vec() } /// Displays a call target for error messages. fn display_call_target(&mut self, module: &Option<ModuleName>, name: Symbol) -> String { if let Some(m) = module { if m != &self.parent.parent.builtin_module() { // Only print the module name if it is not the pseudo builtin module. return format!( "{}", QualifiedSymbol { module_name: m.clone(), symbol: name, } .display(self.symbol_pool()) ); } } format!("{}", name.display(self.symbol_pool())) } /// Displays a call target candidate for error messages. fn display_call_cand( &mut self, module: &Option<ModuleName>, name: Symbol, entry: &SpecFunEntry, ) -> String { let target = self.display_call_target(module, name); let type_display_context = self.type_display_context(); format!( "{}({}): {}", target, entry .arg_types .iter() .map(|ty| ty.display(&type_display_context)) .join(", "), entry.result_type.display(&type_display_context) ) } } /// ## Type Translation impl<'env, 'translator, 'module_translator> ExpTranslator<'env, 'translator, 'module_translator> { /// Translates an hlir type into a target AST type. fn translate_hlir_single_type(&mut self, ty: &SingleType) -> Type { use move_lang::hlir::ast::SingleType_::*; match &ty.value { Ref(is_mut, ty) => { let ty = self.translate_hlir_base_type(&*ty); if ty == Type::Error { Type::Error } else { Type::Reference(*is_mut, Box::new(ty)) } } Base(ty) => self.translate_hlir_base_type(&*ty), } } fn translate_hlir_base_type(&mut self, ty: &BaseType) -> Type { use move_lang::{ hlir::ast::{BaseType_::*, TypeName_::*}, naming::ast::BuiltinTypeName_::*, }; match &ty.value { Param(TParam { user_specified_name, .. }) => { let sym = self.symbol_pool().make(user_specified_name.value.as_str()); self.type_params_table[&sym].clone() } Apply(_, type_name, args) => { let loc = self.to_loc(&type_name.loc); match &type_name.value { Builtin(builtin_type_name) => match &builtin_type_name.value { Address => Type::new_prim(PrimitiveType::Address), U8 => Type::new_prim(PrimitiveType::U8), U64 => Type::new_prim(PrimitiveType::U64), U128 => Type::new_prim(PrimitiveType::U128), Vector => Type::Vector(Box::new(self.translate_hlir_base_type(&args[0]))), Bool => Type::new_prim(PrimitiveType::Bool), }, ModuleType(m, n) => { let module_name = ModuleName::from_str( &m.0.value.address.to_string(), self.symbol_pool().make(m.0.value.name.0.value.as_str()), ); let symbol = self.symbol_pool().make(n.0.value.as_str()); let qsym = QualifiedSymbol { module_name, symbol, }; let rty = self.parent.parent.lookup_type(&loc, &qsym); if !args.is_empty() { // Replace type instantiation. if let Type::Struct(mid, sid, _) = &rty { let arg_types = self.translate_hlir_base_types(args); if arg_types.iter().any(|x| *x == Type::Error) { Type::Error } else { Type::Struct(*mid, *sid, arg_types) } } else { Type::Error } } else { rty } } } } _ => unreachable!(), } } fn translate_hlir_base_types(&mut self, tys: &[BaseType]) -> Vec<Type> { tys.iter() .map(|t| self.translate_hlir_base_type(t)) .collect() } /// Translates a source AST type into a target AST type. fn translate_type(&mut self, ty: &EA::Type) -> Type { use EA::Type_::*; match &ty.value { Apply(access, args) => { if let EA::ModuleAccess_::Name(n) = &access.value { // Attempt to resolve as primitive type. match n.value.as_str() { "bool" => return Type::new_prim(PrimitiveType::Bool), "u8" => return Type::new_prim(PrimitiveType::U8), "u64" => return Type::new_prim(PrimitiveType::U64), "u128" => return Type::new_prim(PrimitiveType::U128), "num" => return Type::new_prim(PrimitiveType::Num), "range" => return Type::new_prim(PrimitiveType::Range), "address" => return Type::new_prim(PrimitiveType::Address), "vector" => { if args.len() != 1 { self.error( &self.to_loc(&ty.loc), "expected one type argument for `vector`", ); return Type::Error; } else { return Type::Vector(Box::new(self.translate_type(&args[0]))); } } _ => {} } // Attempt to resolve as a type parameter. let sym = self.symbol_pool().make(n.value.as_str()); if let Some(ty) = self.type_params_table.get(&sym) { return ty.clone(); } } let loc = self.to_loc(&access.loc); let sym = self.parent.module_access_to_qualified(access); let rty = self.parent.parent.lookup_type(&loc, &sym); if !args.is_empty() { // Replace type instantiation. if let Type::Struct(mid, sid, params) = &rty { if params.len() != args.len() { self.error(&loc, "type argument count mismatch"); Type::Error } else { Type::Struct(*mid, *sid, self.translate_types(args)) } } else { self.error(&loc, "type cannot have type arguments"); Type::Error } } else { rty } } Ref(is_mut, ty) => Type::Reference(*is_mut, Box::new(self.translate_type(&*ty))), Fun(args, result) => Type::Fun( self.translate_types(&args), Box::new(self.translate_type(&*result)), ), Unit => Type::Tuple(vec![]), Multiple(vst) => Type::Tuple(self.translate_types(vst)), UnresolvedError => Type::Error, } } /// Translates a slice of single types. fn translate_types(&mut self, tys: &[EA::Type]) -> Vec<Type> { tys.iter().map(|t| self.translate_type(t)).collect() } /// Translates option a slice of single types. fn translate_types_opt(&mut self, tys_opt: Option<&[EA::Type]>) -> Vec<Type> { tys_opt .map(|tys| self.translate_types(tys)) .unwrap_or_else(|| vec![]) } } /// ## Expression Translation impl<'env, 'translator, 'module_translator> ExpTranslator<'env, 'translator, 'module_translator> { /// Translates an expression, with given expected type, which might be a type variable. fn translate_exp(&mut self, exp: &EA::Exp, expected_type: &Type) -> Exp { let loc = self.to_loc(&exp.loc); let make_value = |et: &mut ExpTranslator, val: Value, ty: Type| { let rty = et.check_type(&loc, &ty, expected_type); let id = et.new_node_id_with_type_loc(&rty, &loc); Exp::Value(id, val) }; match &exp.value { EA::Exp_::Value(v) => { if let Some((v, ty)) = self.translate_value(v) { make_value(self, v, ty) } else { self.new_error_exp() } } EA::Exp_::InferredNum(x) => { // We don't really need to infer type, because all ints are exchangeable. make_value( self, Value::Number(BigUint::from_u128(*x).unwrap()), Type::new_prim(PrimitiveType::U128), ) } EA::Exp_::Name(maccess, type_params) => { self.translate_name(&loc, maccess, type_params.as_deref(), expected_type) } EA::Exp_::Call(maccess, type_params, args) => { // Need to make a &[&Exp] out of args. let args = args.value.iter().map(|e| e).collect_vec(); self.translate_fun_call( expected_type, &loc, &maccess, type_params.as_deref(), &args, ) } EA::Exp_::Pack(maccess, generics, fields) => { self.translate_pack(&loc, maccess, generics, fields, expected_type) } EA::Exp_::IfElse(cond, then, else_) => { let then = self.translate_exp(&*then, expected_type); let else_ = self.translate_exp(&*else_, expected_type); let cond = self.translate_exp(&*cond, &Type::new_prim(PrimitiveType::Bool)); let id = self.new_node_id_with_type_loc(expected_type, &loc); Exp::IfElse(id, Box::new(cond), Box::new(then), Box::new(else_)) } EA::Exp_::Block(seq) => self.translate_seq(&loc, seq, expected_type), EA::Exp_::Lambda(bindings, exp) => { self.translate_lambda(&loc, bindings, exp, expected_type) } EA::Exp_::BinopExp(l, op, r) => { let args = vec![l.as_ref(), r.as_ref()]; let QualifiedSymbol { module_name, symbol, } = self.parent.parent.bin_op_symbol(&op.value); self.translate_call(&loc, &Some(module_name), symbol, None, &args, expected_type) } EA::Exp_::UnaryExp(op, exp) => { let args = vec![exp.as_ref()]; let QualifiedSymbol { module_name, symbol, } = self.parent.parent.unary_op_symbol(&op.value); self.translate_call(&loc, &Some(module_name), symbol, None, &args, expected_type) } EA::Exp_::ExpDotted(dotted) => self.translate_dotted(dotted, expected_type), EA::Exp_::Index(target, index) => { self.translate_index(&loc, target, index, expected_type) } EA::Exp_::ExpList(exps) => { let mut types = vec![]; let exps = exps .iter() .map(|exp| { let (ty, exp) = self.translate_exp_free(exp); types.push(ty); exp }) .collect_vec(); let ty = self.check_type(&loc, &Type::Tuple(types), expected_type); let id = self.new_node_id_with_type_loc(&ty, &loc); Exp::Call(id, Operation::Tuple, exps) } EA::Exp_::Unit => { let ty = self.check_type(&loc, &Type::Tuple(vec![]), expected_type); let id = self.new_node_id_with_type_loc(&ty, &loc); Exp::Call(id, Operation::Tuple, vec![]) } EA::Exp_::Assign(..) => { self.error(&loc, "assignment only allowed in spec var updates"); self.new_error_exp() } _ => { self.error(&loc, "expression construct not supported in specifications"); self.new_error_exp() } } } fn translate_value(&mut self, v: &PA::Value) -> Option<(Value, Type)> { let loc = self.to_loc(&v.loc); match &v.value { PA::Value_::Address(addr) => { let addr_str = &format!("{}", addr); if &addr_str[..2] == "0x" { let digits_only = &addr_str[2..]; Some(( Value::Address( BigUint::from_str_radix(digits_only, 16).expect("valid address"), ), Type::new_prim(PrimitiveType::Address), )) } else { self.error(&loc, "address string does not begin with '0x'"); None } } PA::Value_::U8(x) => Some(( Value::Number(BigUint::from_u8(*x).unwrap()), Type::new_prim(PrimitiveType::U8), )), PA::Value_::U64(x) => Some(( Value::Number(BigUint::from_u64(*x).unwrap()), Type::new_prim(PrimitiveType::U64), )), PA::Value_::U128(x) => Some(( Value::Number(BigUint::from_u128(*x).unwrap()), Type::new_prim(PrimitiveType::U128), )), PA::Value_::Bool(x) => Some((Value::Bool(*x), Type::new_prim(PrimitiveType::Bool))), PA::Value_::Bytearray(x) => { let ty = Type::Vector(Box::new(Type::new_prim(PrimitiveType::U8))); Some((Value::ByteArray(x.clone()), ty)) } } } fn translate_fun_call( &mut self, expected_type: &Type, loc: &Loc, maccess: &Spanned<EA::ModuleAccess_>, generics: Option<&[EA::Type]>, args: &[&EA::Exp], ) -> Exp { // First check whether this is an Invoke on a function value. if let EA::ModuleAccess_::Name(n) = &maccess.value { let sym = self.symbol_pool().make(&n.value); if let Some(entry) = self.lookup_local(sym) { // Check whether the local has the expected function type. let sym_ty = entry.type_.clone(); let (arg_types, args) = self.translate_exp_list(args); let fun_t = Type::Fun(arg_types, Box::new(expected_type.clone())); let sym_ty = self.check_type(&loc, &sym_ty, &fun_t); let local_id = self.new_node_id_with_type_loc(&sym_ty, &self.to_loc(&n.loc)); let local_var = Exp::LocalVar(local_id, sym); let id = self.new_node_id_with_type_loc(expected_type, &loc); return Exp::Invoke(id, Box::new(local_var), args); } } // Next treat this as a call to a global function. let (module_name, name) = self.parent.module_access_to_parts(maccess); let is_old = module_name.is_none() && name == self.parent.parent.old_symbol(); if is_old { match self.old_status { OldExpStatus::NotSupported => { self.error(&loc, "`old(..)` expression not allowed in this context"); } OldExpStatus::InsideOld => { self.error(&loc, "`old(..old(..)..)` not allowed"); } OldExpStatus::OutsideOld => { self.old_status = OldExpStatus::InsideOld; } } } let result = self.translate_call(&loc, &module_name, name, generics, args, expected_type); if is_old && self.old_status == OldExpStatus::InsideOld { self.old_status = OldExpStatus::OutsideOld; } result } /// Translates an expression without any known type expectation. This creates a fresh type /// variable and passes this in as expected type, then returns a pair of this type and the /// translated expression. fn translate_exp_free(&mut self, exp: &EA::Exp) -> (Type, Exp) { let tvar = self.fresh_type_var(); let exp = self.translate_exp(exp, &tvar); (tvar, exp) } /// Translates a sequence expression. fn translate_seq(&mut self, loc: &Loc, seq: &EA::Sequence, expected_type: &Type) -> Exp { let n = seq.len(); if n == 0 { self.error(loc, "block sequence cannot be empty"); return self.new_error_exp(); } // Process all items before the last one, which must be bindings, and accumulate // declarations for them. let mut decls = vec![]; let seq = seq.iter().collect_vec(); for item in &seq[0..seq.len() - 1] { match &item.value { EA::SequenceItem_::Bind(list, exp) => { let (t, e) = self.translate_exp_free(exp); if list.value.len() != 1 { self.error( &self.to_loc(&list.loc), "[current restriction] tuples not supported in let", ); return Exp::Error(self.parent.new_node_id()); } let bind_loc = self.to_loc(&list.value[0].loc); match &list.value[0].value { EA::LValue_::Var(maccess, _) => { let name = match &maccess.value { EA::ModuleAccess_::Name(n) => n, EA::ModuleAccess_::ModuleAccess(_, n) => n, }; // Declare the variable in the local environment. Currently we mimic // Rust/ML semantics here, allowing to shadow with each let. self.enter_scope(); let name = self.symbol_pool().make(&name.value); self.define_local(&bind_loc, name, t.clone(), None); let id = self.new_node_id_with_type_loc(&t, &bind_loc); decls.push(LocalVarDecl { id, name, binding: Some(e), }); } EA::LValue_::Unpack(..) => { self.error( &bind_loc, "[current restriction] unpack not supported in let", ); return Exp::Error(self.parent.new_node_id()); } } } _ => self.error( &self.to_loc(&item.loc), "only binding `let p = e; ...` allowed here", ), } } // Process the last element, which must be an Exp item. let last = match &seq[n - 1].value { EA::SequenceItem_::Seq(e) => self.translate_exp(e, expected_type), _ => { self.error( &self.to_loc(&seq[n - 1].loc), "expected an expression as the last element of the block", ); self.new_error_exp() } }; // Exit the scopes for variable bindings for _ in 0..decls.len() { self.exit_scope(); } let id = self.new_node_id_with_type_loc(expected_type, loc); Exp::Block(id, decls, Box::new(last)) } /// Translates a name. Reports an error if the name is not found. fn translate_name( &mut self, loc: &Loc, maccess: &EA::ModuleAccess, type_args: Option<&[EA::Type]>, expected_type: &Type, ) -> Exp { let spec_var_sym = match &maccess.value { EA::ModuleAccess_::ModuleAccess(..) => self.parent.module_access_to_qualified(maccess), EA::ModuleAccess_::Name(name) => { // First try to resolve simple name as local. let sym = self.symbol_pool().make(name.value.as_str()); if let Some(entry) = self.lookup_local(sym) { let oper_opt = entry.operation.clone(); let ty = entry.type_.clone(); let ty = self.check_type(loc, &ty, expected_type); let id = self.new_node_id_with_type_loc(&ty, loc); if let Some(oper) = oper_opt { return Exp::Call(id, oper, vec![]); } else { return Exp::LocalVar(id, sym); } } // If not found, treat as spec var. self.parent.qualified_by_module(sym) } }; if let Some(entry) = self.parent.parent.spec_var_table.get(&spec_var_sym) { let type_args = type_args.unwrap_or(&[]); if entry.type_params.len() != type_args.len() { self.error( loc, &format!( "generic count mismatch (expected {} but found {})", entry.type_params.len(), type_args.len() ), ); return self.new_error_exp(); } let ty = entry.type_.clone(); let module_id = entry.module_id; let var_id = entry.var_id; let instantiation = self.translate_types(type_args); let ty = ty.instantiate(&instantiation); let ty = self.check_type(loc, &ty, expected_type); let id = self.new_node_id_with_type_loc(&ty, loc); // Remember the instantiation as an attribute on the expression node. self.set_instantiation(id, instantiation); return Exp::SpecVar(id, module_id, var_id); } self.error( loc, &format!("undeclared `{}`", spec_var_sym.display(self.symbol_pool())), ); self.new_error_exp() } /// Translate an Index expression. fn translate_index( &mut self, loc: &Loc, target: &EA::Exp, index: &EA::Exp, expected_type: &Type, ) -> Exp { // We must concretize the type of index to decide whether this is a slice // or not. This is not compatible with full type inference, so we may // try to actually represent slicing explicitly in the syntax to fix this. // Alternatively, we could leave it to the backend to figure (after full // type inference) whether this is slice or index. let elem_ty = self.fresh_type_var(); let vector_ty = Type::Vector(Box::new(elem_ty.clone())); let vector_exp = self.translate_exp(target, &vector_ty); let (index_ty, ie) = self.translate_exp_free(index); let index_ty = self.subs.specialize(&index_ty); let (result_t, oper) = if let Type::Primitive(PrimitiveType::Range) = &index_ty { (vector_ty, Operation::Slice) } else { // If this is not (known to be) a range, assume its an index. self.check_type(&loc, &index_ty, &Type::new_prim(PrimitiveType::Num)); (elem_ty, Operation::Index) }; let result_t = self.check_type(loc, &result_t, expected_type); let id = self.new_node_id_with_type_loc(&result_t, &loc); Exp::Call(id, oper, vec![vector_exp, ie]) } /// Translate a Dotted expression. fn translate_dotted(&mut self, dotted: &EA::ExpDotted, expected_type: &Type) -> Exp { // Similar as with Index, we must concretize the type of the expression on which // field selection is performed, violating full type inference rules, so we can actually // check and retrieve the field. To avoid this, we would need to introduce the concept // of a type constraint to type unification, where the constraint would be // 'type var X where X has field F'. This makes unification significant more complex, // so lets see how far we get without this. match &dotted.value { EA::ExpDotted_::Exp(e) => self.translate_exp(e, expected_type), EA::ExpDotted_::Dot(e, n) => { let loc = self.to_loc(&dotted.loc); let field_name = self.symbol_pool().make(&n.value); let ty = self.fresh_type_var(); let exp = self.translate_dotted(e.as_ref(), &ty); // Try to concretize the type and check its a struct. let struct_ty = self.subs.specialize(&ty); if let Type::Struct(mid, sid, targs) = &struct_ty { // Lookup the StructEntry in the translator. It must be defined for valid // Type::Struct instances. let struct_name = self .parent .parent .reverse_struct_table .get(&(*mid, *sid)) .expect("invalid Type::Struct"); let entry = self .parent .parent .struct_table .get(struct_name) .expect("invalid Type::Struct") .clone(); // Lookup the field in the struct. if let Some(fields) = &entry.fields { if let Some((_, field_ty)) = fields.get(&field_name) { // We must instantiate the field type by the provided type args. let field_ty = field_ty.instantiate(targs); self.check_type(&loc, &field_ty, expected_type); let id = self.new_node_id_with_type_loc(&field_ty, &loc); Exp::Call( id, Operation::Select( entry.module_id, entry.struct_id, FieldId::new(field_name), ), vec![exp], ) } else { self.error( &loc, &format!( "field `{}` not declared in struct `{}`", field_name.display(self.symbol_pool()), struct_name.display(self.symbol_pool()) ), ); self.new_error_exp() } } else { self.error( &loc, &format!( "struct `{}` is native and does not support field selection", struct_name.display(self.symbol_pool()) ), ); self.new_error_exp() } } else { self.error( &loc, &format!( "type `{}` cannot be resolved as a struct", struct_ty.display(&self.type_display_context()), ), ); self.new_error_exp() } } } } /// Translates a call, performing overload resolution. Reports an error if the function cannot be found. /// This is used to resolve both calls to user spec functions and builtin operators. fn translate_call( &mut self, loc: &Loc, module: &Option<ModuleName>, name: Symbol, generics: Option<&[EA::Type]>, args: &[&EA::Exp], expected_type: &Type, ) -> Exp { // Translate generic arguments, if any. let generics = generics.as_ref().map(|ts| self.translate_types(&ts)); // Translate arguments. let (arg_types, args) = self.translate_exp_list(args); // Lookup candidates. let cand_modules = if let Some(m) = module { vec![m.clone()] } else { // For an unqualified name, resolve it both in this and in the builtin pseudo module. vec![ self.parent.module_name.clone(), self.parent.parent.builtin_module(), ] }; let mut cands = vec![]; for module_name in cand_modules { let full_name = QualifiedSymbol { module_name, symbol: name, }; if let Some(list) = self.parent.parent.spec_fun_table.get(&full_name) { cands.extend_from_slice(list); } } if cands.is_empty() { let display = self.display_call_target(module, name); self.error(loc, &format!("no function named `{}` found", display)); return self.new_error_exp(); } // Partition candidates in those which matched and which have been outruled. let mut outruled = vec![]; let mut matching = vec![]; for cand in &cands { if cand.arg_types.len() != args.len() { outruled.push(( cand, format!( "argument count mismatch (expected {} but found {})", cand.arg_types.len(), args.len() ), )); continue; } let (instantiation, diag) = self.make_instantiation(cand.type_params.len(), generics.clone()); if let Some(msg) = diag { outruled.push((cand, msg)); continue; } // Clone the current substitution, then unify arguments against parameter types. let mut subs = self.subs.clone(); let mut success = true; for (i, arg_ty) in arg_types.iter().enumerate() { let instantiated = cand.arg_types[i].instantiate(&instantiation); if let Err(err) = subs.unify(&self.type_display_context(), arg_ty, &instantiated) { outruled.push((cand, format!("{} for argument {}", err.message, i + 1))); success = false; break; } } if success { matching.push((cand, subs, instantiation)); } } // Deliver results, reporting errors if there are no or ambiguous matches. match matching.len() { 0 => { let display = self.display_call_target(module, name); let notes = outruled .iter() .map(|(cand, msg)| { format!( "outruled candidate `{}` ({})", self.display_call_cand(module, name, cand), msg ) }) .collect_vec(); self.parent.parent.env.error_with_notes( loc, &format!("no matching declaration of `{}`", display), notes, ); self.new_error_exp() } 1 => { let (cand, subs, instantiation) = matching.remove(0); // Commit the candidate substitution to this expression translator. self.subs = subs; // Check result type against expected type. let ty = self.check_type( loc, &cand.result_type.instantiate(&instantiation), expected_type, ); // Check pure requirement. // Construct result. let id = self.new_node_id_with_type_loc(&ty, loc); self.set_instantiation(id, instantiation); Exp::Call(id, cand.oper.clone(), args) } _ => { let display = self.display_call_target(module, name); let notes = matching .iter() .map(|(cand, _, _)| { format!( "matching candidate `{}`", self.display_call_cand(module, name, cand) ) }) .collect_vec(); self.parent.parent.env.error_with_notes( loc, &format!("ambiguous application of `{}`", display), notes, ); self.new_error_exp() } } } /// Translate a list of expressions and deliver them together with their types. fn translate_exp_list(&mut self, exps: &[&EA::Exp]) -> (Vec<Type>, Vec<Exp>) { let mut types = vec![]; let exps = exps .iter() .map(|e| { let (t, e) = self.translate_exp_free(e); types.push(t); e }) .collect_vec(); (types, exps) } /// Creates a type instantiation based on provided actual type parameters. fn make_instantiation( &mut self, param_count: usize, actuals: Option<Vec<Type>>, ) -> (Vec<Type>, Option<String>) { if let Some(types) = actuals { let n = types.len(); if n != param_count { ( types, Some(format!( "generic count mismatch (expected {} but found {})", param_count, n, )), ) } else { (types, None) } } else { // Create fresh type variables. ( (0..param_count) .map(|_| self.fresh_type_var()) .collect_vec(), None, ) } } fn translate_pack( &mut self, loc: &Loc, maccess: &EA::ModuleAccess, generics: &Option<Vec<EA::Type>>, fields: &EA::Fields<EA::Exp>, expected_type: &Type, ) -> Exp { let struct_name = self.parent.module_access_to_qualified(maccess); let struct_name_loc = self.to_loc(&maccess.loc); let generics = generics.as_ref().map(|ts| self.translate_types(&ts)); if let Some(entry) = self.parent.parent.struct_table.get(&struct_name) { let entry = entry.clone(); let (instantiation, diag) = self.make_instantiation(entry.type_params.len(), generics); if let Some(msg) = diag { self.error(loc, &msg); return self.new_error_exp(); } if let Some(field_decls) = &entry.fields { let mut fields_not_convered: BTreeSet<Symbol> = BTreeSet::new(); fields_not_convered.extend(field_decls.keys()); let mut args = BTreeMap::new(); for (ref name, (_, exp)) in fields.iter() { let field_name = self.symbol_pool().make(&name.0.value); if let Some((idx, field_ty)) = field_decls.get(&field_name) { let exp = self.translate_exp(exp, &field_ty.instantiate(&instantiation)); fields_not_convered.remove(&field_name); args.insert(idx, exp); } else { self.error( &self.to_loc(&name.0.loc), &format!( "field `{}` not declared in struct `{}`", field_name.display(self.symbol_pool()), struct_name.display(self.symbol_pool()) ), ); } } if !fields_not_convered.is_empty() { self.error( loc, &format!( "missing fields {}", fields_not_convered .iter() .map(|n| format!("`{}`", n.display(self.symbol_pool()))) .join(", ") ), ); self.new_error_exp() } else { let struct_ty = Type::Struct(entry.module_id, entry.struct_id, instantiation); let struct_ty = self.check_type(loc, &struct_ty, expected_type); let args = args .into_iter() .sorted_by_key(|(i, _)| *i) .map(|(_, e)| e) .collect_vec(); let id = self.new_node_id_with_type_loc(&struct_ty, loc); Exp::Call(id, Operation::Pack(entry.module_id, entry.struct_id), args) } } else { self.error( &struct_name_loc, &format!( "native struct `{}` cannot be packed", struct_name.display(self.symbol_pool()) ), ); self.new_error_exp() } } else { self.error( &struct_name_loc, &format!( "undeclared struct `{}`", struct_name.display(self.symbol_pool()) ), ); self.new_error_exp() } } fn translate_lambda( &mut self, loc: &Loc, bindings: &EA::LValueList, body: &EA::Exp, expected_type: &Type, ) -> Exp { // Enter the lambda variables into a new local scope and collect their declarations. self.enter_scope(); let mut decls = vec![]; let mut arg_types = vec![]; for bind in &bindings.value { let loc = self.to_loc(&bind.loc); match &bind.value { EA::LValue_::Var( Spanned { value: EA::ModuleAccess_::Name(n), .. }, _, ) => { let name = self.symbol_pool().make(&n.value); let ty = self.fresh_type_var(); let id = self.new_node_id_with_type_loc(&ty, &loc); self.define_local(&loc, name, ty.clone(), None); arg_types.push(ty); decls.push(LocalVarDecl { id, name, binding: None, }); } EA::LValue_::Unpack(..) | EA::LValue_::Var(..) => { self.error(&loc, "[current restriction] tuples not supported in lambda") } } } // Translate the body. let ty = self.fresh_type_var(); let rbody = self.translate_exp(body, &ty); // Check types and construct result. let rty = self.check_type(loc, &Type::Fun(arg_types, Box::new(ty)), expected_type); let id = self.new_node_id_with_type_loc(&rty, loc); Exp::Lambda(id, decls, Box::new(rbody)) } fn check_type(&mut self, loc: &Loc, ty: &Type, expected: &Type) -> Type { // Because of Rust borrow semantics, we must temporarily detach the substitution from // the translator. This is because we also need to inherently borrow self via the // type_display_context which is passed into unification. let mut subs = std::mem::replace(&mut self.subs, Substitution::new()); let result = match subs.unify(&self.type_display_context(), ty, expected) { Ok(t) => t, Err(err) => { self.error(&loc, &err.message); Type::Error } }; std::mem::replace(&mut self.subs, subs); result } } /// ## Expression Rewriting /// Rewriter for expressions, allowing to substitute locals by expressions as well as instantiate /// types. Currently used to rewrite conditions and invariants included from schemas. struct ExpRewriter<'env, 'translator, 'rewriter> { parent: &'rewriter mut ModuleTranslator<'env, 'translator>, argument_map: &'rewriter BTreeMap<Symbol, Exp>, type_args: &'rewriter [Type], shadowed: VecDeque<BTreeSet<Symbol>>, originating_module: ModuleId, } impl<'env, 'translator, 'rewriter> ExpRewriter<'env, 'translator, 'rewriter> { fn new( parent: &'rewriter mut ModuleTranslator<'env, 'translator>, originating_module: ModuleId, argument_map: &'rewriter BTreeMap<Symbol, Exp>, type_args: &'rewriter [Type], ) -> Self { ExpRewriter { parent, argument_map, type_args, shadowed: VecDeque::new(), originating_module, } } fn replace_local(&mut self, node_id: NodeId, sym: Symbol) -> Exp { for vars in &self.shadowed { if vars.contains(&sym) { let node_id = self.rewrite_attrs(node_id); return Exp::LocalVar(node_id, sym); } } if let Some(exp) = self.argument_map.get(&sym) { exp.clone() } else { let node_id = self.rewrite_attrs(node_id); Exp::LocalVar(node_id, sym) } } fn rewrite(&mut self, exp: &Exp) -> Exp { use Exp::*; match exp { LocalVar(id, sym) => self.replace_local(*id, *sym), Call(id, oper, args) => Call( self.rewrite_attrs(*id), oper.clone(), self.rewrite_vec(args), ), Invoke(id, target, args) => Invoke( self.rewrite_attrs(*id), Box::new(self.rewrite(target)), self.rewrite_vec(args), ), Lambda(id, vars, body) => { self.shadowed .push_front(vars.iter().map(|decl| decl.name).collect()); let res = Lambda( self.rewrite_attrs(*id), vars.clone(), Box::new(self.rewrite(body)), ); self.shadowed.pop_front(); res } Block(id, vars, body) => { self.shadowed .push_front(vars.iter().map(|decl| decl.name).collect()); let res = Block( self.rewrite_attrs(*id), vars.clone(), Box::new(self.rewrite(body)), ); self.shadowed.pop_front(); res } IfElse(id, cond, then, else_) => IfElse( self.rewrite_attrs(*id), Box::new(self.rewrite(cond)), Box::new(self.rewrite(then)), Box::new(self.rewrite(else_)), ), Error(..) | Value(..) | SpecVar(..) => exp.clone(), } } fn rewrite_vec(&mut self, exps: &[Exp]) -> Vec<Exp> { // For some reason, we don't get the lifetime right when we use a map. Figure out // why and remove this explicit treatment. let mut res = vec![]; for exp in exps { res.push(self.rewrite(exp)); } res } fn rewrite_attrs(&mut self, node_id: NodeId) -> NodeId { // Create a new node id and copy attributes over, after instantiation with type args. let (loc, ty, instantiation_opt) = if self.parent.module_id == self.originating_module { let loc = self .parent .loc_map .get(&node_id) .expect("loc defined") .clone(); let ty = self .parent .type_map .get(&node_id) .expect("type defined") .instantiate(self.type_args); let instantiation_opt = self.parent.instantiation_map.get(&node_id).map(|tys| { tys.iter() .map(|ty| ty.instantiate(self.type_args)) .collect_vec() }); (loc, ty, instantiation_opt) } else { let module_env = self.parent.parent.env.get_module(self.originating_module); let loc = module_env.get_node_loc(node_id); let ty = module_env.get_node_type(node_id); let instantiation = module_env.get_node_instantiation(node_id); ( loc, ty, if instantiation.is_empty() { None } else { Some(instantiation) }, ) }; let new_node_id = self.parent.new_node_id(); self.parent.loc_map.insert(new_node_id, loc); self.parent.type_map.insert(new_node_id, ty); if let Some(instantiation) = instantiation_opt { self.parent .instantiation_map .insert(new_node_id, instantiation); } new_node_id } }
38.924399
172
0.496886
b991ae6b027b786b88a74e872829d20760d24924
6,016
mod call; use bytes::Bytes; use call::{Encoding, GrpcWebCall}; use core::{ fmt, task::{Context, Poll}, }; use futures::{Future, Stream, TryStreamExt}; use http::{header::HeaderName, request::Request, response::Response, HeaderMap, HeaderValue}; use http_body::Body; use js_sys::{Array, Uint8Array}; use std::{error::Error, pin::Pin}; use std::collections::HashMap; use tonic::{body::BoxBody, client::GrpcService, Status}; use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen_futures::JsFuture; use wasm_streams::ReadableStream; use web_sys::{Headers, RequestInit}; #[derive(Debug, Clone, PartialEq)] pub enum ClientError { Err, FetchFailed(JsValue), } impl Error for ClientError {} impl fmt::Display for ClientError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self) } } pub type CredentialsMode = web_sys::RequestCredentials; pub type RequestMode = web_sys::RequestMode; #[derive(Clone)] pub struct Client { base_uri: String, credentials: CredentialsMode, mode: RequestMode, encoding: Encoding, user_headers: HashMap<String, String> } impl Client { pub fn new(base_uri: String) -> Self { Client { base_uri, credentials: CredentialsMode::SameOrigin, mode: RequestMode::Cors, encoding: Encoding::None, user_headers: Default::default() } } pub fn new_with_headermap(base_uri: String, user_headers: HashMap<String, String>) -> Self { Client { base_uri, credentials: CredentialsMode::SameOrigin, mode: RequestMode::Cors, encoding: Encoding::None, user_headers } } async fn request(self, rpc: Request<BoxBody>) -> Result<Response<BoxBody>, ClientError> { let mut uri = rpc.uri().to_string(); uri.insert_str(0, &self.base_uri); let headers = Headers::new().unwrap(); for (k, v) in rpc.headers().iter() { headers.set(k.as_str(), v.to_str().unwrap()).unwrap(); } for (k, v) in self.user_headers.iter() { headers.set(&*k, &*v).unwrap(); } headers.set("x-user-agent", "grpc-web-rust/0.1").unwrap(); headers.set("x-grpc-web", "1").unwrap(); headers .set("content-type", self.encoding.to_content_type()) .unwrap(); let body_bytes = hyper::body::to_bytes(rpc.into_body()).await.unwrap(); let body_array: Uint8Array = body_bytes.as_ref().into(); let body_js: &JsValue = body_array.as_ref(); let mut init = RequestInit::new(); init.method("POST") .mode(self.mode) .credentials(self.credentials) .body(Some(body_js)) .headers(headers.as_ref()); let request = web_sys::Request::new_with_str_and_init(&uri, &init).unwrap(); let window = web_sys::window().unwrap(); let fetch = JsFuture::from(window.fetch_with_request(&request)) .await .map_err(ClientError::FetchFailed)?; let fetch_res: web_sys::Response = fetch.dyn_into().unwrap(); let mut res = Response::builder().status(fetch_res.status()); let headers = res.headers_mut().unwrap(); for kv in js_sys::try_iter(fetch_res.headers().as_ref()) .unwrap() .unwrap() { let pair: Array = kv.unwrap().into(); headers.append( HeaderName::from_bytes(pair.get(0).as_string().unwrap().as_bytes()).unwrap(), HeaderValue::from_str(&pair.get(1).as_string().unwrap()).unwrap(), ); } let body_stream = ReadableStream::from_raw(fetch_res.body().unwrap().unchecked_into()); let body = GrpcWebCall::client_response( ReadableStreamBody::new(body_stream), Encoding::from_content_type(headers), ); Ok(res.body(BoxBody::new(body)).unwrap()) } } impl GrpcService<BoxBody> for Client { type ResponseBody = BoxBody; type Error = ClientError; type Future = Pin<Box<dyn Future<Output = Result<Response<BoxBody>, ClientError>>>>; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn call(&mut self, rpc: Request<BoxBody>) -> Self::Future { Box::pin(self.clone().request(rpc)) } } struct ReadableStreamBody { stream: Pin<Box<dyn Stream<Item = Result<Bytes, Status>>>>, } impl ReadableStreamBody { fn new(inner: ReadableStream) -> Self { ReadableStreamBody { stream: Box::pin( inner .into_stream() .map_ok(|buf_js| { let buffer = Uint8Array::new(&buf_js); let mut bytes_vec = vec![0; buffer.length() as usize]; buffer.copy_to(&mut bytes_vec); let bytes: Bytes = bytes_vec.into(); bytes }) .map_err(|_| Status::unknown("readablestream error")), ), } } } impl Body for ReadableStreamBody { type Data = Bytes; type Error = Status; fn poll_data( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Self::Data, Self::Error>>> { self.stream.as_mut().poll_next(cx) } fn poll_trailers( self: Pin<&mut Self>, _: &mut Context<'_>, ) -> Poll<Result<Option<HeaderMap>, Self::Error>> { Poll::Ready(Ok(None)) } fn is_end_stream(&self) -> bool { false } } // WARNING: these are required to satisfy the Body and Error traits, but JsValue is not thread-safe. // This shouldn't be an issue because wasm doesn't have threads currently. unsafe impl Sync for ReadableStreamBody {} unsafe impl Send for ReadableStreamBody {} unsafe impl Sync for ClientError {} unsafe impl Send for ClientError {}
30.693878
100
0.58893
5d998b77896cdbf14996def851040984471def3e
2,945
use crate::*; pub fn migrate(mut tester: impl tests::Tester) { let sql = r#" CREATE TABLE Test ( id INT, num INT, name TEXT )"#; tester.run(sql).unwrap(); let sqls = [ "INSERT INTO Test (id, num, name) VALUES (1, 2, \"Hello\")", "INSERT INTO Test (id, num, name) VALUES (1, 9, \"World\")", "INSERT INTO Test (id, num, name) VALUES (3, 4, \"Great\")", ]; sqls.iter().for_each(|sql| { tester.run(sql).unwrap(); }); let error_cases = vec![ ( ValueError::ExprNotSupported("3 * 2".to_owned()).into(), "INSERT INTO Test (id, num) VALUES (3 * 2, 1);", ), ( ValueError::FailedToParseNumber.into(), "INSERT INTO Test (id, num) VALUES (1.1, 1);", ), ( EvaluateError::UnsupportedCompoundIdentifier("Here.User.id".to_owned()).into(), "SELECT * FROM Test WHERE Here.User.id = 1", ), ( JoinError::NaturalOnJoinNotSupported.into(), "SELECT * FROM Test NATURAL JOIN Test", ), ( TableError::TableFactorNotSupported.into(), "SELECT * FROM (SELECT * FROM Test) as A;", ), ]; error_cases.into_iter().for_each(|(error, sql)| { let error = Err(error); assert_eq!(error, tester.run(sql)); }); use Value::*; let found = tester .run("SELECT id, num, name FROM Test") .expect("select"); let expected = select!( id | num | name I64 | I64 | Str; 1 2 "Hello".to_owned(); 1 9 "World".to_owned(); 3 4 "Great".to_owned() ); assert_eq!(expected, found); let found = tester .run("SELECT id, num, name FROM Test WHERE id = 1") .expect("select"); let expected = select!( id | num | name I64 | I64 | Str; 1 2 "Hello".to_owned(); 1 9 "World".to_owned() ); assert_eq!(expected, found); tester.run_and_print("UPDATE Test SET id = 2"); let found = tester .run("SELECT id, num, name FROM Test") .expect("select"); let expected = select!( id | num | name; I64 | I64 | Str; 2 2 "Hello".to_owned(); 2 9 "World".to_owned(); 2 4 "Great".to_owned() ); assert_eq!(expected, found); let found = tester.run("SELECT id FROM Test").expect("select"); let expected = select!(id; I64; 2; 2; 2); assert_eq!(expected, found); let found = tester.run("SELECT id, num FROM Test").expect("select"); let expected = select!(id | num; I64 | I64; 2 2; 2 9; 2 4); assert_eq!(expected, found); let found = tester .run("SELECT id, num FROM Test LIMIT 1 OFFSET 1") .expect("select"); let expected = select!(id | num; I64 | I64; 2 9); assert_eq!(expected, found); }
28.047619
91
0.513073
7a8208c12c0d1e3226923ddaffcd2bc128e9c3c5
12,796
//! This module contains paths to types and functions Clippy needs to know //! about. //! //! Whenever possible, please consider diagnostic items over hardcoded paths. //! See <https://github.com/rust-lang/rust-clippy/issues/5393> for more information. pub const ANY_TRAIT: [&str; 3] = ["core", "any", "Any"]; #[cfg(feature = "metadata-collector-lint")] pub const APPLICABILITY: [&str; 2] = ["rustc_lint_defs", "Applicability"]; #[cfg(feature = "metadata-collector-lint")] pub const APPLICABILITY_VALUES: [[&str; 3]; 4] = [ ["rustc_lint_defs", "Applicability", "Unspecified"], ["rustc_lint_defs", "Applicability", "HasPlaceholders"], ["rustc_lint_defs", "Applicability", "MaybeIncorrect"], ["rustc_lint_defs", "Applicability", "MachineApplicable"], ]; #[cfg(feature = "metadata-collector-lint")] pub const DIAGNOSTIC_BUILDER: [&str; 3] = ["rustc_errors", "diagnostic_builder", "DiagnosticBuilder"]; pub const ARC_PTR_EQ: [&str; 4] = ["alloc", "sync", "Arc", "ptr_eq"]; pub const ASMUT_TRAIT: [&str; 3] = ["core", "convert", "AsMut"]; pub const ASREF_TRAIT: [&str; 3] = ["core", "convert", "AsRef"]; pub(super) const BEGIN_PANIC: [&str; 3] = ["std", "panicking", "begin_panic"]; pub(super) const BEGIN_PANIC_FMT: [&str; 3] = ["std", "panicking", "begin_panic_fmt"]; /// Preferably use the diagnostic item `sym::Borrow` where possible pub const BORROW_TRAIT: [&str; 3] = ["core", "borrow", "Borrow"]; pub const BTREEMAP_CONTAINS_KEY: [&str; 6] = ["alloc", "collections", "btree", "map", "BTreeMap", "contains_key"]; pub const BTREEMAP_ENTRY: [&str; 6] = ["alloc", "collections", "btree", "map", "entry", "Entry"]; pub const BTREEMAP_INSERT: [&str; 6] = ["alloc", "collections", "btree", "map", "BTreeMap", "insert"]; pub const CLONE_TRAIT_METHOD: [&str; 4] = ["core", "clone", "Clone", "clone"]; pub const CMP_MAX: [&str; 3] = ["core", "cmp", "max"]; pub const CMP_MIN: [&str; 3] = ["core", "cmp", "min"]; pub const COW: [&str; 3] = ["alloc", "borrow", "Cow"]; pub const CSTRING_AS_C_STR: [&str; 5] = ["std", "ffi", "c_str", "CString", "as_c_str"]; pub const DEFAULT_TRAIT_METHOD: [&str; 4] = ["core", "default", "Default", "default"]; pub const DEREF_MUT_TRAIT_METHOD: [&str; 5] = ["core", "ops", "deref", "DerefMut", "deref_mut"]; /// Preferably use the diagnostic item `sym::deref_method` where possible pub const DEREF_TRAIT_METHOD: [&str; 5] = ["core", "ops", "deref", "Deref", "deref"]; pub const DIR_BUILDER: [&str; 3] = ["std", "fs", "DirBuilder"]; pub const DISPLAY_TRAIT: [&str; 3] = ["core", "fmt", "Display"]; pub const DOUBLE_ENDED_ITERATOR: [&str; 4] = ["core", "iter", "traits", "DoubleEndedIterator"]; pub const DROP: [&str; 3] = ["core", "mem", "drop"]; pub const DURATION: [&str; 3] = ["core", "time", "Duration"]; #[cfg(feature = "internal-lints")] pub const EARLY_CONTEXT: [&str; 2] = ["rustc_lint", "EarlyContext"]; pub const EXIT: [&str; 3] = ["std", "process", "exit"]; pub const F32_EPSILON: [&str; 4] = ["core", "f32", "<impl f32>", "EPSILON"]; pub const F64_EPSILON: [&str; 4] = ["core", "f64", "<impl f64>", "EPSILON"]; pub const FILE: [&str; 3] = ["std", "fs", "File"]; pub const FILE_TYPE: [&str; 3] = ["std", "fs", "FileType"]; pub const FROM_FROM: [&str; 4] = ["core", "convert", "From", "from"]; pub const FROM_ITERATOR: [&str; 5] = ["core", "iter", "traits", "collect", "FromIterator"]; pub const FROM_ITERATOR_METHOD: [&str; 6] = ["core", "iter", "traits", "collect", "FromIterator", "from_iter"]; pub const FROM_STR_METHOD: [&str; 5] = ["core", "str", "traits", "FromStr", "from_str"]; pub const FUTURE_FROM_GENERATOR: [&str; 3] = ["core", "future", "from_generator"]; pub const HASH: [&str; 3] = ["core", "hash", "Hash"]; pub const HASHMAP_CONTAINS_KEY: [&str; 6] = ["std", "collections", "hash", "map", "HashMap", "contains_key"]; pub const HASHMAP_ENTRY: [&str; 5] = ["std", "collections", "hash", "map", "Entry"]; pub const HASHMAP_INSERT: [&str; 6] = ["std", "collections", "hash", "map", "HashMap", "insert"]; #[cfg(feature = "internal-lints")] pub const IDENT: [&str; 3] = ["rustc_span", "symbol", "Ident"]; #[cfg(feature = "internal-lints")] pub const IDENT_AS_STR: [&str; 4] = ["rustc_span", "symbol", "Ident", "as_str"]; pub const INDEX: [&str; 3] = ["core", "ops", "Index"]; pub const INDEX_MUT: [&str; 3] = ["core", "ops", "IndexMut"]; pub const INSERT_STR: [&str; 4] = ["alloc", "string", "String", "insert_str"]; pub const IO_READ: [&str; 3] = ["std", "io", "Read"]; pub const IO_WRITE: [&str; 3] = ["std", "io", "Write"]; pub const IPADDR_V4: [&str; 5] = ["std", "net", "ip", "IpAddr", "V4"]; pub const IPADDR_V6: [&str; 5] = ["std", "net", "ip", "IpAddr", "V6"]; pub const ITER_REPEAT: [&str; 5] = ["core", "iter", "sources", "repeat", "repeat"]; #[allow(clippy::invalid_paths)] // internal lints do not know about all external crates pub const ITERTOOLS_NEXT_TUPLE: [&str; 3] = ["itertools", "Itertools", "next_tuple"]; #[cfg(feature = "internal-lints")] pub const KW_MODULE: [&str; 3] = ["rustc_span", "symbol", "kw"]; #[cfg(feature = "internal-lints")] pub const LATE_CONTEXT: [&str; 2] = ["rustc_lint", "LateContext"]; pub const LIBC_STRLEN: [&str; 2] = ["libc", "strlen"]; #[cfg(any(feature = "internal-lints", feature = "metadata-collector-lint"))] pub const LINT: [&str; 2] = ["rustc_lint_defs", "Lint"]; pub const MEM_DISCRIMINANT: [&str; 3] = ["core", "mem", "discriminant"]; pub const MEM_FORGET: [&str; 3] = ["core", "mem", "forget"]; pub const MEM_MANUALLY_DROP: [&str; 4] = ["core", "mem", "manually_drop", "ManuallyDrop"]; pub const MEM_MAYBEUNINIT: [&str; 4] = ["core", "mem", "maybe_uninit", "MaybeUninit"]; pub const MEM_MAYBEUNINIT_UNINIT: [&str; 5] = ["core", "mem", "maybe_uninit", "MaybeUninit", "uninit"]; pub const MEM_REPLACE: [&str; 3] = ["core", "mem", "replace"]; pub const MEM_SIZE_OF: [&str; 3] = ["core", "mem", "size_of"]; pub const MEM_SIZE_OF_VAL: [&str; 3] = ["core", "mem", "size_of_val"]; pub const MUTEX_GUARD: [&str; 4] = ["std", "sync", "mutex", "MutexGuard"]; pub const OPEN_OPTIONS: [&str; 3] = ["std", "fs", "OpenOptions"]; pub const OPS_MODULE: [&str; 2] = ["core", "ops"]; /// Preferably use the diagnostic item `sym::option_type` where possible pub const OPTION: [&str; 3] = ["core", "option", "Option"]; pub const OPTION_NONE: [&str; 4] = ["core", "option", "Option", "None"]; pub const OPTION_SOME: [&str; 4] = ["core", "option", "Option", "Some"]; pub const ORD: [&str; 3] = ["core", "cmp", "Ord"]; pub const OS_STRING_AS_OS_STR: [&str; 5] = ["std", "ffi", "os_str", "OsString", "as_os_str"]; pub const OS_STR_TO_OS_STRING: [&str; 5] = ["std", "ffi", "os_str", "OsStr", "to_os_string"]; pub(super) const PANICKING_PANIC: [&str; 3] = ["core", "panicking", "panic"]; pub(super) const PANICKING_PANIC_FMT: [&str; 3] = ["core", "panicking", "panic_fmt"]; pub(super) const PANICKING_PANIC_STR: [&str; 3] = ["core", "panicking", "panic_str"]; pub(super) const PANIC_ANY: [&str; 3] = ["std", "panic", "panic_any"]; pub const PARKING_LOT_MUTEX_GUARD: [&str; 2] = ["parking_lot", "MutexGuard"]; pub const PARKING_LOT_RWLOCK_READ_GUARD: [&str; 2] = ["parking_lot", "RwLockReadGuard"]; pub const PARKING_LOT_RWLOCK_WRITE_GUARD: [&str; 2] = ["parking_lot", "RwLockWriteGuard"]; pub const PATH_BUF_AS_PATH: [&str; 4] = ["std", "path", "PathBuf", "as_path"]; pub const PATH_TO_PATH_BUF: [&str; 4] = ["std", "path", "Path", "to_path_buf"]; pub const PERMISSIONS: [&str; 3] = ["std", "fs", "Permissions"]; pub const PERMISSIONS_FROM_MODE: [&str; 6] = ["std", "os", "unix", "fs", "PermissionsExt", "from_mode"]; pub const POLL: [&str; 4] = ["core", "task", "poll", "Poll"]; pub const POLL_PENDING: [&str; 5] = ["core", "task", "poll", "Poll", "Pending"]; pub const POLL_READY: [&str; 5] = ["core", "task", "poll", "Poll", "Ready"]; pub const PTR_COPY: [&str; 3] = ["core", "intrinsics", "copy"]; pub const PTR_COPY_NONOVERLAPPING: [&str; 3] = ["core", "intrinsics", "copy_nonoverlapping"]; pub const PTR_EQ: [&str; 3] = ["core", "ptr", "eq"]; pub const PTR_SLICE_FROM_RAW_PARTS: [&str; 3] = ["core", "ptr", "slice_from_raw_parts"]; pub const PTR_SLICE_FROM_RAW_PARTS_MUT: [&str; 3] = ["core", "ptr", "slice_from_raw_parts_mut"]; pub const PTR_SWAP_NONOVERLAPPING: [&str; 3] = ["core", "ptr", "swap_nonoverlapping"]; pub const PTR_READ: [&str; 3] = ["core", "ptr", "read"]; pub const PTR_READ_UNALIGNED: [&str; 3] = ["core", "ptr", "read_unaligned"]; pub const PTR_READ_VOLATILE: [&str; 3] = ["core", "ptr", "read_volatile"]; pub const PTR_REPLACE: [&str; 3] = ["core", "ptr", "replace"]; pub const PTR_SWAP: [&str; 3] = ["core", "ptr", "swap"]; pub const PTR_WRITE: [&str; 3] = ["core", "ptr", "write"]; pub const PTR_WRITE_BYTES: [&str; 3] = ["core", "intrinsics", "write_bytes"]; pub const PTR_WRITE_UNALIGNED: [&str; 3] = ["core", "ptr", "write_unaligned"]; pub const PTR_WRITE_VOLATILE: [&str; 3] = ["core", "ptr", "write_volatile"]; pub const PUSH_STR: [&str; 4] = ["alloc", "string", "String", "push_str"]; pub const RANGE_ARGUMENT_TRAIT: [&str; 3] = ["core", "ops", "RangeBounds"]; pub const RC_PTR_EQ: [&str; 4] = ["alloc", "rc", "Rc", "ptr_eq"]; pub const REFCELL_REF: [&str; 3] = ["core", "cell", "Ref"]; pub const REFCELL_REFMUT: [&str; 3] = ["core", "cell", "RefMut"]; pub const REGEX_BUILDER_NEW: [&str; 5] = ["regex", "re_builder", "unicode", "RegexBuilder", "new"]; pub const REGEX_BYTES_BUILDER_NEW: [&str; 5] = ["regex", "re_builder", "bytes", "RegexBuilder", "new"]; pub const REGEX_BYTES_NEW: [&str; 4] = ["regex", "re_bytes", "Regex", "new"]; pub const REGEX_BYTES_SET_NEW: [&str; 5] = ["regex", "re_set", "bytes", "RegexSet", "new"]; pub const REGEX_NEW: [&str; 4] = ["regex", "re_unicode", "Regex", "new"]; pub const REGEX_SET_NEW: [&str; 5] = ["regex", "re_set", "unicode", "RegexSet", "new"]; /// Preferably use the diagnostic item `sym::result_type` where possible pub const RESULT: [&str; 3] = ["core", "result", "Result"]; pub const RESULT_ERR: [&str; 4] = ["core", "result", "Result", "Err"]; pub const RESULT_OK: [&str; 4] = ["core", "result", "Result", "Ok"]; pub const RWLOCK_READ_GUARD: [&str; 4] = ["std", "sync", "rwlock", "RwLockReadGuard"]; pub const RWLOCK_WRITE_GUARD: [&str; 4] = ["std", "sync", "rwlock", "RwLockWriteGuard"]; pub const SERDE_DESERIALIZE: [&str; 3] = ["serde", "de", "Deserialize"]; pub const SERDE_DE_VISITOR: [&str; 3] = ["serde", "de", "Visitor"]; pub const SLICE_FROM_RAW_PARTS: [&str; 4] = ["core", "slice", "raw", "from_raw_parts"]; pub const SLICE_FROM_RAW_PARTS_MUT: [&str; 4] = ["core", "slice", "raw", "from_raw_parts_mut"]; pub const SLICE_INTO_VEC: [&str; 4] = ["alloc", "slice", "<impl [T]>", "into_vec"]; pub const SLICE_ITER: [&str; 4] = ["core", "slice", "iter", "Iter"]; pub const STDERR: [&str; 4] = ["std", "io", "stdio", "stderr"]; pub const STDOUT: [&str; 4] = ["std", "io", "stdio", "stdout"]; pub const CONVERT_IDENTITY: [&str; 3] = ["core", "convert", "identity"]; pub const STD_FS_CREATE_DIR: [&str; 3] = ["std", "fs", "create_dir"]; pub const STRING_AS_MUT_STR: [&str; 4] = ["alloc", "string", "String", "as_mut_str"]; pub const STRING_AS_STR: [&str; 4] = ["alloc", "string", "String", "as_str"]; pub const STR_ENDS_WITH: [&str; 4] = ["core", "str", "<impl str>", "ends_with"]; pub const STR_FROM_UTF8: [&str; 4] = ["core", "str", "converts", "from_utf8"]; pub const STR_LEN: [&str; 4] = ["core", "str", "<impl str>", "len"]; pub const STR_STARTS_WITH: [&str; 4] = ["core", "str", "<impl str>", "starts_with"]; #[cfg(feature = "internal-lints")] pub const SYMBOL: [&str; 3] = ["rustc_span", "symbol", "Symbol"]; #[cfg(feature = "internal-lints")] pub const SYMBOL_AS_STR: [&str; 4] = ["rustc_span", "symbol", "Symbol", "as_str"]; #[cfg(feature = "internal-lints")] pub const SYMBOL_INTERN: [&str; 4] = ["rustc_span", "symbol", "Symbol", "intern"]; #[cfg(feature = "internal-lints")] pub const SYMBOL_TO_IDENT_STRING: [&str; 4] = ["rustc_span", "symbol", "Symbol", "to_ident_string"]; #[cfg(feature = "internal-lints")] pub const SYM_MODULE: [&str; 3] = ["rustc_span", "symbol", "sym"]; #[cfg(feature = "internal-lints")] pub const SYNTAX_CONTEXT: [&str; 3] = ["rustc_span", "hygiene", "SyntaxContext"]; pub const TO_OWNED_METHOD: [&str; 4] = ["alloc", "borrow", "ToOwned", "to_owned"]; pub const TO_STRING_METHOD: [&str; 4] = ["alloc", "string", "ToString", "to_string"]; pub const TRY_FROM: [&str; 4] = ["core", "convert", "TryFrom", "try_from"]; pub const VEC_AS_MUT_SLICE: [&str; 4] = ["alloc", "vec", "Vec", "as_mut_slice"]; pub const VEC_AS_SLICE: [&str; 4] = ["alloc", "vec", "Vec", "as_slice"]; pub const VEC_FROM_ELEM: [&str; 3] = ["alloc", "vec", "from_elem"]; pub const VEC_NEW: [&str; 4] = ["alloc", "vec", "Vec", "new"]; pub const VEC_RESIZE: [&str; 4] = ["alloc", "vec", "Vec", "resize"]; pub const WEAK_ARC: [&str; 3] = ["alloc", "sync", "Weak"]; pub const WEAK_RC: [&str; 3] = ["alloc", "rc", "Weak"];
70.307692
114
0.631057
33fe36f148d7b9d1f887b41cede427b4e18ac051
5,965
//! Digital IO Implementations //! //! For a detailed explanation, refer to the [general Digital IO documentation][1]. //! //! [1]: ../../avr_hal_generic/port/index.html pub use avr_hal::port::mode; pub trait PortExt { type Parts; fn split(self) -> Self::Parts; } avr_hal::impl_generic_pin! { pub enum Pin { A(crate::atmega1280::PORTA, porta, pina, ddra), B(crate::atmega1280::PORTB, portb, pinb, ddrb), C(crate::atmega1280::PORTC, portc, pinc, ddrc), D(crate::atmega1280::PORTD, portd, pind, ddrd), E(crate::atmega1280::PORTE, porte, pine, ddre), F(crate::atmega1280::PORTF, portf, pinf, ddrf), G(crate::atmega1280::PORTG, portg, ping, ddrg), H(crate::atmega1280::PORTH, porth, pinh, ddrh), J(crate::atmega1280::PORTJ, portj, pinj, ddrj), K(crate::atmega1280::PORTK, portk, pink, ddrk), L(crate::atmega1280::PORTL, portl, pinl, ddrl), } } avr_hal::impl_port! { pub mod porta { #[port_ext] use super::PortExt; #[generic_pin] use Pin::A; impl PortExt for crate::atmega1280::PORTA { regs: (pina, ddra, porta), pa0: (PA0, 0), pa1: (PA1, 1), pa2: (PA2, 2), pa3: (PA3, 3), pa4: (PA4, 4), pa5: (PA5, 5), pa6: (PA6, 6), pa7: (PA7, 7), } } } avr_hal::impl_port! { pub mod portb { #[port_ext] use super::PortExt; #[generic_pin] use Pin::B; impl PortExt for crate::atmega1280::PORTB { regs: (pinb, ddrb, portb), pb0: (PB0, 0), pb1: (PB1, 1), pb2: (PB2, 2), pb3: (PB3, 3), pb4: (PB4, 4), pb5: (PB5, 5), pb6: (PB6, 6), pb7: (PB7, 7), } } } avr_hal::impl_port! { pub mod portc { #[port_ext] use super::PortExt; #[generic_pin] use Pin::C; impl PortExt for crate::atmega1280::PORTC { regs: (pinc, ddrc, portc), pc0: (PC0, 0), pc1: (PC1, 1), pc2: (PC2, 2), pc3: (PC3, 3), pc4: (PC4, 4), pc5: (PC5, 5), pc6: (PC6, 6), pc7: (PC7, 7), } } } avr_hal::impl_port! { pub mod portd { #[port_ext] use super::PortExt; #[generic_pin] use Pin::D; impl PortExt for crate::atmega1280::PORTD { regs: (pind, ddrd, portd), pd0: (PD0, 0), pd1: (PD1, 1), pd2: (PD2, 2), pd3: (PD3, 3), pd4: (PD4, 4), pd5: (PD5, 5), pd6: (PD6, 6), pd7: (PD7, 7), } } } avr_hal::impl_port! { pub mod porte { #[port_ext] use super::PortExt; #[generic_pin] use Pin::E; impl PortExt for crate::atmega1280::PORTE { regs: (pine, ddre, porte), pe0: (PE0, 0), pe1: (PE1, 1), pe2: (PE2, 2), pe3: (PE3, 3), pe4: (PE4, 4), pe5: (PE5, 5), pe6: (PE6, 6), pe7: (PE7, 7), } } } avr_hal::impl_port! { pub mod portf { #[port_ext] use super::PortExt; #[generic_pin] use Pin::F; impl PortExt for crate::atmega1280::PORTF { regs: (pinf, ddrf, portf), pf0: (PF0, 0), pf1: (PF1, 1), pf2: (PF2, 2), pf3: (PF3, 3), pf4: (PF4, 4), pf5: (PF5, 5), pf6: (PF6, 6), pf7: (PF7, 7), } } } avr_hal::impl_port! { pub mod portg { #[port_ext] use super::PortExt; #[generic_pin] use Pin::G; impl PortExt for crate::atmega1280::PORTG { regs: (ping, ddrg, portg), pg0: (PG0, 0), pg1: (PG1, 1), pg2: (PG2, 2), pg3: (PG3, 3), pg4: (PG4, 4), pg5: (PG5, 5), } } } avr_hal::impl_port! { pub mod porth { #[port_ext] use super::PortExt; #[generic_pin] use Pin::H; impl PortExt for crate::atmega1280::PORTH { regs: (pinh, ddrh, porth), ph0: (PH0, 0), ph1: (PH1, 1), ph2: (PH2, 2), ph3: (PH3, 3), ph4: (PH4, 4), ph5: (PH5, 5), ph6: (PH6, 6), ph7: (PH7, 7), } } } avr_hal::impl_port! { pub mod portj { #[port_ext] use super::PortExt; #[generic_pin] use Pin::J; impl PortExt for crate::atmega1280::PORTJ { regs: (pinj, ddrj, portj), pj0: (PJ0, 0), pj1: (PJ1, 1), pj2: (PJ2, 2), pj3: (PJ3, 3), pj4: (PJ4, 4), pj5: (PJ5, 5), pj6: (PJ6, 6), pj7: (PJ7, 7), } } } avr_hal::impl_port! { pub mod portk { #[port_ext] use super::PortExt; #[generic_pin] use Pin::K; impl PortExt for crate::atmega1280::PORTK { regs: (pink, ddrk, portk), pk0: (PK0, 0), pk1: (PK1, 1), pk2: (PK2, 2), pk3: (PK3, 3), pk4: (PK4, 4), pk5: (PK5, 5), pk6: (PK6, 6), pk7: (PK7, 7), } } } avr_hal::impl_port! { pub mod portl { #[port_ext] use super::PortExt; #[generic_pin] use Pin::L; impl PortExt for crate::atmega1280::PORTL { regs: (pinl, ddrl, portl), pl0: (PL0, 0), pl1: (PL1, 1), pl2: (PL2, 2), pl3: (PL3, 3), pl4: (PL4, 4), pl5: (PL5, 5), pl6: (PL6, 6), pl7: (PL7, 7), } } }
22.092593
83
0.418944
ed3dafbe237a23766a410ff8e367d8f67910884b
9,764
use crate::r#ref::AnyRef; use crate::{Func, Store, ValType}; use anyhow::{bail, Result}; use std::ptr; use wasmtime_environ::ir; /// Possible runtime values that a WebAssembly module can either consume or /// produce. #[derive(Debug, Clone)] pub enum Val { /// A 32-bit integer I32(i32), /// A 64-bit integer I64(i64), /// A 32-bit float. /// /// Note that the raw bits of the float are stored here, and you can use /// `f32::from_bits` to create an `f32` value. F32(u32), /// A 64-bit float. /// /// Note that the raw bits of the float are stored here, and you can use /// `f64::from_bits` to create an `f64` value. F64(u64), /// An `anyref` value which can hold opaque data to the wasm instance itself. /// /// Note that this is a nullable value as well. AnyRef(AnyRef), /// A first-class reference to a WebAssembly function. FuncRef(Func), /// A 128-bit number V128(u128), /// A signed 8-bit integer, part of the WebAssembly Interface Types proposal S8(i8), /// A signed 16-bit integer, part of the WebAssembly Interface Types proposal S16(i16), /// A signed 32-bit integer, part of the WebAssembly Interface Types proposal /// /// Note that this is distinct from `I32` which does not have a signedness /// representation. This type is not the same as the `I32` type. S32(i32), /// A signed 64-bit integer, part of the WebAssembly Interface Types proposal /// /// Note that this is distinct from `I64` which does not have a signedness /// representation. This type is not the same as the `I64` type. S64(i64), /// An unsigned 8-bit integer, part of the WebAssembly Interface Types proposal U8(u8), /// An unsigned 16-bit integer, part of the WebAssembly Interface Types proposal U16(u16), /// An unsigned 32-bit integer, part of the WebAssembly Interface Types proposal U32(u32), /// An unsigned 64-bit integer, part of the WebAssembly Interface Types proposal U64(u64), /// A utf-8 string, part of the WebAssembly Interface Types proposal String(String), } macro_rules! accessors { ($bind:ident $(($variant:ident($ty:ty) $get:ident $unwrap:ident $cvt:expr))*) => ($( /// Attempt to access the underlying value of this `Val`, returning /// `None` if it is not the correct type. pub fn $get(&self) -> Option<$ty> { if let Val::$variant($bind) = self { Some($cvt) } else { None } } /// Returns the underlying value of this `Val`, panicking if it's the /// wrong type. /// /// # Panics /// /// Panics if `self` is not of the right type. pub fn $unwrap(&self) -> $ty { self.$get().expect(concat!("expected ", stringify!($ty))) } )*) } impl Val { /// Returns a null `anyref` value. pub fn null() -> Val { Val::AnyRef(AnyRef::null()) } /// Returns the corresponding [`ValType`] for this `Val`. pub fn ty(&self) -> ValType { match self { Val::I32(_) => ValType::I32, Val::I64(_) => ValType::I64, Val::F32(_) => ValType::F32, Val::F64(_) => ValType::F64, Val::AnyRef(_) => ValType::AnyRef, Val::FuncRef(_) => ValType::FuncRef, Val::V128(_) => ValType::V128, Val::S8(_) => ValType::S8, Val::S16(_) => ValType::S16, Val::S32(_) => ValType::S32, Val::S64(_) => ValType::S64, Val::U8(_) => ValType::U8, Val::U16(_) => ValType::U16, Val::U32(_) => ValType::U32, Val::U64(_) => ValType::U64, Val::String(_) => ValType::String, } } pub(crate) unsafe fn write_value_to(&self, p: *mut i128) { match self { Val::I32(i) => ptr::write(p as *mut i32, *i), Val::I64(i) => ptr::write(p as *mut i64, *i), Val::F32(u) => ptr::write(p as *mut u32, *u), Val::F64(u) => ptr::write(p as *mut u64, *u), Val::V128(b) => ptr::write(p as *mut u128, *b), _ => unimplemented!("Val::write_value_to"), } } pub(crate) unsafe fn read_value_from(p: *const i128, ty: ir::Type) -> Val { match ty { ir::types::I32 => Val::I32(ptr::read(p as *const i32)), ir::types::I64 => Val::I64(ptr::read(p as *const i64)), ir::types::F32 => Val::F32(ptr::read(p as *const u32)), ir::types::F64 => Val::F64(ptr::read(p as *const u64)), ir::types::I8X16 => Val::V128(ptr::read(p as *const u128)), _ => unimplemented!("Val::read_value_from"), } } accessors! { e (I32(i32) i32 unwrap_i32 *e) (I64(i64) i64 unwrap_i64 *e) (F32(f32) f32 unwrap_f32 f32::from_bits(*e)) (F64(f64) f64 unwrap_f64 f64::from_bits(*e)) (FuncRef(&Func) funcref unwrap_funcref e) (V128(u128) v128 unwrap_v128 *e) (S8(i8) s8 unwrap_s8 *e) (S16(i16) s16 unwrap_s16 *e) (S32(i32) s32 unwrap_s32 *e) (S64(i64) s64 unwrap_s64 *e) (U8(u8) u8 unwrap_u8 *e) (U16(u16) u16 unwrap_u16 *e) (U32(u32) u32 unwrap_u32 *e) (U64(u64) u64 unwrap_u64 *e) (String(&str) string unwrap_string e) } /// Attempt to access the underlying value of this `Val`, returning /// `None` if it is not the correct type. /// /// This will return `Some` for both the `AnyRef` and `FuncRef` types. pub fn anyref(&self) -> Option<AnyRef> { match self { Val::AnyRef(e) => Some(e.clone()), _ => None, } } /// Returns the underlying value of this `Val`, panicking if it's the /// wrong type. /// /// # Panics /// /// Panics if `self` is not of the right type. pub fn unwrap_anyref(&self) -> AnyRef { self.anyref().expect("expected anyref") } pub(crate) fn comes_from_same_store(&self, store: &Store) -> bool { match self { Val::FuncRef(f) => Store::same(store, f.store()), // TODO: need to implement this once we actually finalize what // `anyref` will look like and it's actually implemented to pass it // to compiled wasm as well. Val::AnyRef(AnyRef::Ref(_)) | Val::AnyRef(AnyRef::Other(_)) => false, Val::AnyRef(AnyRef::Null) => true, // Integers have no association with any particular store, so // they're always considered as "yes I came from that store", Val::I32(_) | Val::I64(_) | Val::F32(_) | Val::F64(_) | Val::V128(_) | Val::S8(_) | Val::S16(_) | Val::S32(_) | Val::S64(_) | Val::U8(_) | Val::U16(_) | Val::U32(_) | Val::U64(_) | Val::String(_) => true, } } } impl From<i8> for Val { fn from(val: i8) -> Val { Val::S8(val) } } impl From<i16> for Val { fn from(val: i16) -> Val { Val::S16(val) } } impl From<i32> for Val { fn from(val: i32) -> Val { Val::I32(val) } } impl From<i64> for Val { fn from(val: i64) -> Val { Val::I64(val) } } impl From<u8> for Val { fn from(val: u8) -> Val { Val::U8(val) } } impl From<u16> for Val { fn from(val: u16) -> Val { Val::U16(val) } } impl From<u32> for Val { fn from(val: u32) -> Val { Val::U32(val) } } impl From<u64> for Val { fn from(val: u64) -> Val { Val::U64(val) } } impl From<f32> for Val { fn from(val: f32) -> Val { Val::F32(val.to_bits()) } } impl From<f64> for Val { fn from(val: f64) -> Val { Val::F64(val.to_bits()) } } impl From<String> for Val { fn from(val: String) -> Val { Val::String(val) } } impl From<&str> for Val { fn from(val: &str) -> Val { Val::String(String::from(val)) } } impl From<AnyRef> for Val { fn from(val: AnyRef) -> Val { Val::AnyRef(val) } } impl From<Func> for Val { fn from(val: Func) -> Val { Val::FuncRef(val) } } pub(crate) fn into_checked_anyfunc( val: Val, store: &Store, ) -> Result<wasmtime_runtime::VMCallerCheckedAnyfunc> { if !val.comes_from_same_store(store) { bail!("cross-`Store` values are not supported"); } Ok(match val { Val::AnyRef(AnyRef::Null) => wasmtime_runtime::VMCallerCheckedAnyfunc { func_ptr: ptr::null(), type_index: wasmtime_runtime::VMSharedSignatureIndex::default(), vmctx: ptr::null_mut(), }, Val::FuncRef(f) => { let f = f.wasmtime_function(); wasmtime_runtime::VMCallerCheckedAnyfunc { func_ptr: f.address, type_index: f.signature, vmctx: f.vmctx, } } _ => bail!("val is not funcref"), }) } pub(crate) fn from_checked_anyfunc( item: wasmtime_runtime::VMCallerCheckedAnyfunc, store: &Store, ) -> Val { if item.type_index == wasmtime_runtime::VMSharedSignatureIndex::default() { Val::AnyRef(AnyRef::Null); } let instance_handle = unsafe { wasmtime_runtime::InstanceHandle::from_vmctx(item.vmctx) }; let export = wasmtime_runtime::ExportFunction { address: item.func_ptr, signature: item.type_index, vmctx: item.vmctx, }; let f = Func::from_wasmtime_function(export, store, instance_handle); Val::FuncRef(f) }
28.80236
94
0.542708
7ab918c159e1f7fb31c04e266e0e171917be4827
2,345
//! Miscellaneous type-system utilities that are too small to deserve their own modules. use crate::infer::TyCtxtInferExt; use crate::traits::{self, ObligationCause}; use rustc::ty::{self, Ty, TyCtxt, TypeFoldable}; use rustc_hir as hir; #[derive(Clone)] pub enum CopyImplementationError<'tcx> { InfrigingFields(Vec<&'tcx ty::FieldDef>), NotAnAdt, HasDestructor, } pub fn can_type_implement_copy( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, self_type: Ty<'tcx>, ) -> Result<(), CopyImplementationError<'tcx>> { // FIXME: (@jroesch) float this code up tcx.infer_ctxt().enter(|infcx| { let (adt, substs) = match self_type.kind { // These types used to have a builtin impl. // Now libcore provides that impl. ty::Uint(_) | ty::Int(_) | ty::Bool | ty::Float(_) | ty::Char | ty::RawPtr(..) | ty::Never | ty::Ref(_, _, hir::Mutability::Not) => return Ok(()), ty::Adt(adt, substs) => (adt, substs), _ => return Err(CopyImplementationError::NotAnAdt), }; let mut infringing = Vec::new(); for variant in &adt.variants { for field in &variant.fields { let ty = field.ty(tcx, substs); if ty.references_error() { continue; } let span = tcx.def_span(field.did); let cause = ObligationCause { span, ..ObligationCause::dummy() }; let ctx = traits::FulfillmentContext::new(); match traits::fully_normalize(&infcx, ctx, cause, param_env, &ty) { Ok(ty) => { if !infcx.type_is_copy_modulo_regions(param_env, ty, span) { infringing.push(field); } } Err(errors) => { infcx.report_fulfillment_errors(&errors, None, false); } }; } } if !infringing.is_empty() { return Err(CopyImplementationError::InfrigingFields(infringing)); } if adt.has_dtor(tcx) { return Err(CopyImplementationError::HasDestructor); } Ok(()) }) }
32.569444
88
0.514286
9bb35e36331dfe3bac2123ef9f4212ec05561efb
12,373
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! ICMPv6 use core::convert::TryFrom; use core::fmt; use net_types::ip::{Ipv6, Ipv6Addr}; use packet::{BufferView, ParsablePacket, ParseMetadata}; use zerocopy::{AsBytes, ByteSlice, FromBytes, Unaligned}; use crate::error::{ParseError, ParseResult}; use crate::U32; use super::common::{IcmpDestUnreachable, IcmpEchoReply, IcmpEchoRequest, IcmpTimeExceeded}; use super::{ mld, ndp, peek_message_type, IcmpIpExt, IcmpMessageType, IcmpPacket, IcmpParseArgs, IcmpUnusedCode, OriginalPacket, }; /// An ICMPv6 packet with a dynamic message type. /// /// Unlike `IcmpPacket`, `Packet` only supports ICMPv6, and does not /// require a static message type. Each enum variant contains an `IcmpPacket` of /// the appropriate static type, making it easier to call `parse` without /// knowing the message type ahead of time while still getting the benefits of a /// statically-typed packet struct after parsing is complete. #[allow(missing_docs)] pub enum Icmpv6Packet<B: ByteSlice> { DestUnreachable(IcmpPacket<Ipv6, B, IcmpDestUnreachable>), PacketTooBig(IcmpPacket<Ipv6, B, Icmpv6PacketTooBig>), TimeExceeded(IcmpPacket<Ipv6, B, IcmpTimeExceeded>), ParameterProblem(IcmpPacket<Ipv6, B, Icmpv6ParameterProblem>), EchoRequest(IcmpPacket<Ipv6, B, IcmpEchoRequest>), EchoReply(IcmpPacket<Ipv6, B, IcmpEchoReply>), Ndp(ndp::NdpPacket<B>), Mld(mld::MldPacket<B>), } impl<B: ByteSlice + fmt::Debug> fmt::Debug for Icmpv6Packet<B> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::Icmpv6Packet::*; use mld::MldPacket::*; use ndp::NdpPacket::*; match self { DestUnreachable(ref p) => f.debug_tuple("DestUnreachable").field(p).finish(), PacketTooBig(ref p) => f.debug_tuple("PacketTooBig").field(p).finish(), TimeExceeded(ref p) => f.debug_tuple("TimeExceeded").field(p).finish(), ParameterProblem(ref p) => f.debug_tuple("ParameterProblem").field(p).finish(), EchoRequest(ref p) => f.debug_tuple("EchoRequest").field(p).finish(), EchoReply(ref p) => f.debug_tuple("EchoReply").field(p).finish(), Ndp(RouterSolicitation(ref p)) => f.debug_tuple("RouterSolicitation").field(p).finish(), Ndp(RouterAdvertisement(ref p)) => { f.debug_tuple("RouterAdvertisement").field(p).finish() } Ndp(NeighborSolicitation(ref p)) => { f.debug_tuple("NeighborSolicitation").field(p).finish() } Ndp(NeighborAdvertisement(ref p)) => { f.debug_tuple("NeighborAdvertisement").field(p).finish() } Ndp(Redirect(ref p)) => f.debug_tuple("Redirect").field(p).finish(), Mld(MulticastListenerQuery(ref p)) => { f.debug_tuple("MulticastListenerQuery").field(p).finish() } Mld(MulticastListenerReport(ref p)) => { f.debug_tuple("MulticastListenerReport").field(p).finish() } Mld(MulticastListenerDone(ref p)) => { f.debug_tuple("MulticastListenerDone").field(p).finish() } } } } impl<B: ByteSlice> ParsablePacket<B, IcmpParseArgs<Ipv6Addr>> for Icmpv6Packet<B> { type Error = ParseError; fn parse_metadata(&self) -> ParseMetadata { use self::Icmpv6Packet::*; use mld::MldPacket::*; use ndp::NdpPacket::*; match self { DestUnreachable(p) => p.parse_metadata(), PacketTooBig(p) => p.parse_metadata(), TimeExceeded(p) => p.parse_metadata(), ParameterProblem(p) => p.parse_metadata(), EchoRequest(p) => p.parse_metadata(), EchoReply(p) => p.parse_metadata(), Ndp(RouterSolicitation(p)) => p.parse_metadata(), Ndp(RouterAdvertisement(p)) => p.parse_metadata(), Ndp(NeighborSolicitation(p)) => p.parse_metadata(), Ndp(NeighborAdvertisement(p)) => p.parse_metadata(), Ndp(Redirect(p)) => p.parse_metadata(), Mld(MulticastListenerQuery(p)) => p.parse_metadata(), Mld(MulticastListenerReport(p)) => p.parse_metadata(), Mld(MulticastListenerDone(p)) => p.parse_metadata(), } } fn parse<BV: BufferView<B>>(buffer: BV, args: IcmpParseArgs<Ipv6Addr>) -> ParseResult<Self> { use self::Icmpv6Packet::*; use mld::MldPacket::*; use ndp::NdpPacket::*; macro_rules! mtch { ($buffer:expr, $args:expr, $pkt_name:ident, $($msg_variant:ident => $pkt_variant:expr => $type:ty,)*) => { match peek_message_type($buffer.as_ref())? { $(Icmpv6MessageType::$msg_variant => { let $pkt_name = <IcmpPacket<Ipv6, B, $type> as ParsablePacket<_, _>>::parse($buffer, $args)?; $pkt_variant })* } } } Ok(mtch!( buffer, args, packet, DestUnreachable => DestUnreachable(packet) => IcmpDestUnreachable, PacketTooBig => PacketTooBig(packet) => Icmpv6PacketTooBig, TimeExceeded => TimeExceeded(packet) => IcmpTimeExceeded, ParameterProblem => ParameterProblem(packet) => Icmpv6ParameterProblem, EchoRequest => EchoRequest(packet) => IcmpEchoRequest, EchoReply => EchoReply(packet) => IcmpEchoReply, RouterSolicitation => Ndp(RouterSolicitation(packet)) => ndp::RouterSolicitation, RouterAdvertisement => Ndp(RouterAdvertisement(packet)) => ndp::RouterAdvertisement, NeighborSolicitation => Ndp(NeighborSolicitation(packet)) => ndp::NeighborSolicitation, NeighborAdvertisement => Ndp(NeighborAdvertisement(packet)) => ndp::NeighborAdvertisement, Redirect => Ndp(Redirect(packet)) => ndp::Redirect, MulticastListenerQuery => Mld(MulticastListenerQuery(packet)) => mld::MulticastListenerQuery, MulticastListenerReport => Mld(MulticastListenerReport(packet)) => mld::MulticastListenerReport, MulticastListenerDone => Mld(MulticastListenerDone(packet)) => mld::MulticastListenerDone, )) } } create_protocol_enum!( #[allow(missing_docs)] #[derive(Copy, Clone, PartialEq, Eq)] pub enum Icmpv6MessageType: u8 { DestUnreachable, 1, "Destination Unreachable"; PacketTooBig, 2, "Packet Too Big"; TimeExceeded, 3, "Time Exceeded"; ParameterProblem, 4, "Parameter Problem"; EchoRequest, 128, "Echo Request"; EchoReply, 129, "Echo Reply"; // NDP messages RouterSolicitation, 133, "Router Solicitation"; RouterAdvertisement, 134, "Router Advertisement"; NeighborSolicitation, 135, "Neighbor Solicitation"; NeighborAdvertisement, 136, "Neighbor Advertisement"; Redirect, 137, "Redirect"; // MLDv1 messages MulticastListenerQuery, 130, "Multicast Listener Query"; MulticastListenerReport, 131, "Multicast Listener Report"; MulticastListenerDone, 132, "Multicast Listener Done"; } ); impl IcmpMessageType for Icmpv6MessageType { fn is_err(self) -> bool { use Icmpv6MessageType::*; [DestUnreachable, PacketTooBig, TimeExceeded, ParameterProblem].contains(&self) } } impl_icmp_message!(Ipv6, IcmpEchoRequest, EchoRequest, IcmpUnusedCode, OriginalPacket<B>); impl_icmp_message!(Ipv6, IcmpEchoReply, EchoReply, IcmpUnusedCode, OriginalPacket<B>); create_protocol_enum!( #[allow(missing_docs)] #[derive(Copy, Clone, PartialEq, Eq)] pub enum Icmpv6DestUnreachableCode: u8 { NoRoute, 0, "No Route"; CommAdministrativelyProhibited, 1, "Comm Administratively Prohibited"; BeyondScope, 2, "Beyond Scope"; AddrUnreachable, 3, "Address Unreachable"; PortUnreachable, 4, "Port Unreachable"; SrcAddrFailedPolicy, 5, "Source Address Failed Policy"; RejectRoute, 6, "Reject Route"; } ); impl_icmp_message!( Ipv6, IcmpDestUnreachable, DestUnreachable, Icmpv6DestUnreachableCode, OriginalPacket<B> ); /// An ICMPv6 Packet Too Big message. #[derive(Copy, Clone, Debug, FromBytes, AsBytes, Unaligned, PartialEq)] #[repr(C)] pub struct Icmpv6PacketTooBig { mtu: U32, } impl Icmpv6PacketTooBig { /// Returns a new `Icmpv6PacketTooBig` with the given MTU value. pub fn new(mtu: u32) -> Icmpv6PacketTooBig { Icmpv6PacketTooBig { mtu: U32::new(mtu) } } /// Get the mtu value. pub fn mtu(&self) -> u32 { self.mtu.get() } } impl_icmp_message!(Ipv6, Icmpv6PacketTooBig, PacketTooBig, IcmpUnusedCode, OriginalPacket<B>); create_protocol_enum!( #[allow(missing_docs)] #[derive(Copy, Clone, PartialEq, Eq)] pub enum Icmpv6TimeExceededCode: u8 { HopLimitExceeded, 0, "Hop Limit Exceeded"; FragmentReassemblyTimeExceeded, 1, "Fragment Reassembly Time Exceeded"; } ); impl_icmp_message!(Ipv6, IcmpTimeExceeded, TimeExceeded, Icmpv6TimeExceededCode, OriginalPacket<B>); create_protocol_enum!( #[allow(missing_docs)] #[derive(Copy, Clone, PartialEq, Eq)] pub enum Icmpv6ParameterProblemCode: u8 { ErroneousHeaderField, 0, "Erroneous Header Field"; UnrecognizedNextHeaderType, 1, "Unrecognized Next Header Type"; UnrecognizedIpv6Option, 2, "Unrecognized IPv6 Option"; } ); /// An ICMPv6 Parameter Problem message. #[derive(Copy, Clone, Debug, Eq, PartialEq, FromBytes, AsBytes, Unaligned)] #[repr(C)] pub struct Icmpv6ParameterProblem { pointer: U32, } impl Icmpv6ParameterProblem { /// Returns a new `Icmpv6ParameterProblem` with the given pointer. pub fn new(pointer: u32) -> Icmpv6ParameterProblem { Icmpv6ParameterProblem { pointer: U32::new(pointer) } } /// Gets the pointer of the ICMPv6 Parameter Problem message. pub fn pointer(self) -> u32 { self.pointer.get() } } impl_icmp_message!( Ipv6, Icmpv6ParameterProblem, ParameterProblem, Icmpv6ParameterProblemCode, OriginalPacket<B> ); #[cfg(test)] mod tests { use packet::{InnerPacketBuilder, ParseBuffer, Serializer}; use std::fmt::Debug; use super::*; use crate::icmp::{IcmpMessage, IcmpPacket, MessageBody}; use crate::ipv6::{Ipv6Packet, Ipv6PacketBuilder}; fn serialize_to_bytes<B: ByteSlice + Debug, M: IcmpMessage<Ipv6, B> + Debug>( src_ip: Ipv6Addr, dst_ip: Ipv6Addr, icmp: &IcmpPacket<Ipv6, B, M>, builder: Ipv6PacketBuilder, ) -> Vec<u8> { icmp.message_body .bytes() .into_serializer() .encapsulate(icmp.builder(src_ip, dst_ip)) .encapsulate(builder) .serialize_vec_outer() .unwrap() .as_ref() .to_vec() } fn test_parse_and_serialize< M: for<'a> IcmpMessage<Ipv6, &'a [u8]> + Debug, F: for<'a> FnOnce(&IcmpPacket<Ipv6, &'a [u8], M>), >( mut req: &[u8], check: F, ) { let orig_req = &req[..]; let ip = req.parse::<Ipv6Packet<_>>().unwrap(); let mut body = ip.body(); let icmp = body .parse_with::<_, IcmpPacket<_, _, M>>(IcmpParseArgs::new(ip.src_ip(), ip.dst_ip())) .unwrap(); check(&icmp); let data = serialize_to_bytes(ip.src_ip(), ip.dst_ip(), &icmp, ip.builder()); assert_eq!(&data[..], orig_req); } #[test] fn test_parse_and_serialize_echo_request() { use crate::testdata::icmp_echo_v6::*; test_parse_and_serialize::<IcmpEchoRequest, _>(REQUEST_IP_PACKET_BYTES, |icmp| { assert_eq!(icmp.message_body.bytes(), ECHO_DATA); assert_eq!(icmp.message().id_seq.id.get(), IDENTIFIER); assert_eq!(icmp.message().id_seq.seq.get(), SEQUENCE_NUM); }); } }
38.188272
118
0.62305
db8efe19dc1df973e3f37968c5ca138c47c46d9f
23,269
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Selection over an array of receivers //! //! This module contains the implementation machinery necessary for selecting //! over a number of receivers. One large goal of this module is to provide an //! efficient interface to selecting over any receiver of any type. //! //! This is achieved through an architecture of a "receiver set" in which //! receivers are added to a set and then the entire set is waited on at once. //! The set can be waited on multiple times to prevent re-adding each receiver //! to the set. //! //! Usage of this module is currently encouraged to go through the use of the //! `select!` macro. This macro allows naturally binding of variables to the //! received values of receivers in a much more natural syntax then usage of the //! `Select` structure directly. //! //! # Example //! //! ```rust //! use std::sync::mpsc::channel; //! //! let (tx1, rx1) = channel(); //! let (tx2, rx2) = channel(); //! //! tx1.send(1).unwrap(); //! tx2.send(2).unwrap(); //! //! select! { //! val = rx1.recv() => { //! assert_eq!(val.unwrap(), 1); //! }, //! val = rx2.recv() => { //! assert_eq!(val.unwrap(), 2); //! } //! } //! ``` #![allow(dead_code)] #![unstable(feature = "std_misc", reason = "This implementation, while likely sufficient, is unsafe and \ likely to be error prone. At some point in the future this \ module will likely be replaced, and it is currently \ unknown how much API breakage that will cause. The ability \ to select over a number of channels will remain forever, \ but no guarantees beyond this are being made")] use core::prelude::*; use core::cell::Cell; use core::marker; use core::mem; use core::ptr; use core::usize; use sync::mpsc::{Receiver, RecvError}; use sync::mpsc::blocking::{self, SignalToken}; /// The "receiver set" of the select interface. This structure is used to manage /// a set of receivers which are being selected over. pub struct Select { head: *mut Handle<'static, ()>, tail: *mut Handle<'static, ()>, next_id: Cell<uint>, } impl !marker::Send for Select {} /// A handle to a receiver which is currently a member of a `Select` set of /// receivers. This handle is used to keep the receiver in the set as well as /// interact with the underlying receiver. pub struct Handle<'rx, T:'rx> { /// The ID of this handle, used to compare against the return value of /// `Select::wait()` id: uint, selector: &'rx Select, next: *mut Handle<'static, ()>, prev: *mut Handle<'static, ()>, added: bool, packet: &'rx (Packet+'rx), // due to our fun transmutes, we be sure to place this at the end. (nothing // previous relies on T) rx: &'rx Receiver<T>, } struct Packets { cur: *mut Handle<'static, ()> } #[doc(hidden)] #[derive(PartialEq)] pub enum StartResult { Installed, Abort, } #[doc(hidden)] pub trait Packet { fn can_recv(&self) -> bool; fn start_selection(&self, token: SignalToken) -> StartResult; fn abort_selection(&self) -> bool; } impl Select { /// Creates a new selection structure. This set is initially empty. /// /// Usage of this struct directly can sometimes be burdensome, and usage is much easier through /// the `select!` macro. /// /// # Examples /// /// ``` /// use std::sync::mpsc::Select; /// /// let select = Select::new(); /// ``` pub fn new() -> Select { Select { head: ptr::null_mut(), tail: ptr::null_mut(), next_id: Cell::new(1), } } /// Creates a new handle into this receiver set for a new receiver. Note /// that this does *not* add the receiver to the receiver set, for that you /// must call the `add` method on the handle itself. pub fn handle<'a, T: Send>(&'a self, rx: &'a Receiver<T>) -> Handle<'a, T> { let id = self.next_id.get(); self.next_id.set(id + 1); Handle { id: id, selector: self, next: ptr::null_mut(), prev: ptr::null_mut(), added: false, rx: rx, packet: rx, } } /// Waits for an event on this receiver set. The returned value is *not* an /// index, but rather an id. This id can be queried against any active /// `Handle` structures (each one has an `id` method). The handle with /// the matching `id` will have some sort of event available on it. The /// event could either be that data is available or the corresponding /// channel has been closed. pub fn wait(&self) -> uint { self.wait2(true) } /// Helper method for skipping the preflight checks during testing fn wait2(&self, do_preflight_checks: bool) -> uint { // Note that this is currently an inefficient implementation. We in // theory have knowledge about all receivers in the set ahead of time, // so this method shouldn't really have to iterate over all of them yet // again. The idea with this "receiver set" interface is to get the // interface right this time around, and later this implementation can // be optimized. // // This implementation can be summarized by: // // fn select(receivers) { // if any receiver ready { return ready index } // deschedule { // block on all receivers // } // unblock on all receivers // return ready index // } // // Most notably, the iterations over all of the receivers shouldn't be // necessary. unsafe { // Stage 1: preflight checks. Look for any packets ready to receive if do_preflight_checks { for handle in self.iter() { if (*handle).packet.can_recv() { return (*handle).id(); } } } // Stage 2: begin the blocking process // // Create a number of signal tokens, and install each one // sequentially until one fails. If one fails, then abort the // selection on the already-installed tokens. let (wait_token, signal_token) = blocking::tokens(); for (i, handle) in self.iter().enumerate() { match (*handle).packet.start_selection(signal_token.clone()) { StartResult::Installed => {} StartResult::Abort => { // Go back and abort the already-begun selections for handle in self.iter().take(i) { (*handle).packet.abort_selection(); } return (*handle).id; } } } // Stage 3: no messages available, actually block wait_token.wait(); // Stage 4: there *must* be message available; find it. // // Abort the selection process on each receiver. If the abort // process returns `true`, then that means that the receiver is // ready to receive some data. Note that this also means that the // receiver may have yet to have fully read the `to_wake` field and // woken us up (although the wakeup is guaranteed to fail). // // This situation happens in the window of where a sender invokes // increment(), sees -1, and then decides to wake up the task. After // all this is done, the sending thread will set `selecting` to // `false`. Until this is done, we cannot return. If we were to // return, then a sender could wake up a receiver which has gone // back to sleep after this call to `select`. // // Note that it is a "fairly small window" in which an increment() // views that it should wake a thread up until the `selecting` bit // is set to false. For now, the implementation currently just spins // in a yield loop. This is very distasteful, but this // implementation is already nowhere near what it should ideally be. // A rewrite should focus on avoiding a yield loop, and for now this // implementation is tying us over to a more efficient "don't // iterate over everything every time" implementation. let mut ready_id = usize::MAX; for handle in self.iter() { if (*handle).packet.abort_selection() { ready_id = (*handle).id; } } // We must have found a ready receiver assert!(ready_id != usize::MAX); return ready_id; } } fn iter(&self) -> Packets { Packets { cur: self.head } } } impl<'rx, T: Send> Handle<'rx, T> { /// Retrieve the id of this handle. #[inline] pub fn id(&self) -> uint { self.id } /// Block to receive a value on the underlying receiver, returning `Some` on /// success or `None` if the channel disconnects. This function has the same /// semantics as `Receiver.recv` pub fn recv(&mut self) -> Result<T, RecvError> { self.rx.recv() } /// Adds this handle to the receiver set that the handle was created from. This /// method can be called multiple times, but it has no effect if `add` was /// called previously. /// /// This method is unsafe because it requires that the `Handle` is not moved /// while it is added to the `Select` set. pub unsafe fn add(&mut self) { if self.added { return } let selector: &mut Select = mem::transmute(&*self.selector); let me: *mut Handle<'static, ()> = mem::transmute(&*self); if selector.head.is_null() { selector.head = me; selector.tail = me; } else { (*me).prev = selector.tail; assert!((*me).next.is_null()); (*selector.tail).next = me; selector.tail = me; } self.added = true; } /// Removes this handle from the `Select` set. This method is unsafe because /// it has no guarantee that the `Handle` was not moved since `add` was /// called. pub unsafe fn remove(&mut self) { if !self.added { return } let selector: &mut Select = mem::transmute(&*self.selector); let me: *mut Handle<'static, ()> = mem::transmute(&*self); if self.prev.is_null() { assert_eq!(selector.head, me); selector.head = self.next; } else { (*self.prev).next = self.next; } if self.next.is_null() { assert_eq!(selector.tail, me); selector.tail = self.prev; } else { (*self.next).prev = self.prev; } self.next = ptr::null_mut(); self.prev = ptr::null_mut(); self.added = false; } } #[unsafe_destructor] impl Drop for Select { fn drop(&mut self) { assert!(self.head.is_null()); assert!(self.tail.is_null()); } } #[unsafe_destructor] impl<'rx, T: Send> Drop for Handle<'rx, T> { fn drop(&mut self) { unsafe { self.remove() } } } impl Iterator for Packets { type Item = *mut Handle<'static, ()>; fn next(&mut self) -> Option<*mut Handle<'static, ()>> { if self.cur.is_null() { None } else { let ret = Some(self.cur); unsafe { self.cur = (*self.cur).next; } ret } } } #[cfg(test)] #[allow(unused_imports)] mod test { use prelude::v1::*; use thread; use sync::mpsc::*; // Don't use the libstd version so we can pull in the right Select structure // (std::comm points at the wrong one) macro_rules! select { ( $($name:pat = $rx:ident.$meth:ident() => $code:expr),+ ) => ({ let sel = Select::new(); $( let mut $rx = sel.handle(&$rx); )+ unsafe { $( $rx.add(); )+ } let ret = sel.wait(); $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+ { unreachable!() } }) } #[test] fn smoke() { let (tx1, rx1) = channel::<int>(); let (tx2, rx2) = channel::<int>(); tx1.send(1).unwrap(); select! { foo = rx1.recv() => { assert_eq!(foo.unwrap(), 1); }, _bar = rx2.recv() => { panic!() } } tx2.send(2).unwrap(); select! { _foo = rx1.recv() => { panic!() }, bar = rx2.recv() => { assert_eq!(bar.unwrap(), 2) } } drop(tx1); select! { foo = rx1.recv() => { assert!(foo.is_err()); }, _bar = rx2.recv() => { panic!() } } drop(tx2); select! { bar = rx2.recv() => { assert!(bar.is_err()); } } } #[test] fn smoke2() { let (_tx1, rx1) = channel::<int>(); let (_tx2, rx2) = channel::<int>(); let (_tx3, rx3) = channel::<int>(); let (_tx4, rx4) = channel::<int>(); let (tx5, rx5) = channel::<int>(); tx5.send(4).unwrap(); select! { _foo = rx1.recv() => { panic!("1") }, _foo = rx2.recv() => { panic!("2") }, _foo = rx3.recv() => { panic!("3") }, _foo = rx4.recv() => { panic!("4") }, foo = rx5.recv() => { assert_eq!(foo.unwrap(), 4); } } } #[test] fn closed() { let (_tx1, rx1) = channel::<int>(); let (tx2, rx2) = channel::<int>(); drop(tx2); select! { _a1 = rx1.recv() => { panic!() }, a2 = rx2.recv() => { assert!(a2.is_err()); } } } #[test] fn unblocks() { let (tx1, rx1) = channel::<int>(); let (_tx2, rx2) = channel::<int>(); let (tx3, rx3) = channel::<int>(); let _t = thread::spawn(move|| { for _ in 0..20 { thread::yield_now(); } tx1.send(1).unwrap(); rx3.recv().unwrap(); for _ in 0..20 { thread::yield_now(); } }); select! { a = rx1.recv() => { assert_eq!(a.unwrap(), 1); }, _b = rx2.recv() => { panic!() } } tx3.send(1).unwrap(); select! { a = rx1.recv() => { assert!(a.is_err()) }, _b = rx2.recv() => { panic!() } } } #[test] fn both_ready() { let (tx1, rx1) = channel::<int>(); let (tx2, rx2) = channel::<int>(); let (tx3, rx3) = channel::<()>(); let _t = thread::spawn(move|| { for _ in 0..20 { thread::yield_now(); } tx1.send(1).unwrap(); tx2.send(2).unwrap(); rx3.recv().unwrap(); }); select! { a = rx1.recv() => { assert_eq!(a.unwrap(), 1); }, a = rx2.recv() => { assert_eq!(a.unwrap(), 2); } } select! { a = rx1.recv() => { assert_eq!(a.unwrap(), 1); }, a = rx2.recv() => { assert_eq!(a.unwrap(), 2); } } assert_eq!(rx1.try_recv(), Err(TryRecvError::Empty)); assert_eq!(rx2.try_recv(), Err(TryRecvError::Empty)); tx3.send(()).unwrap(); } #[test] fn stress() { static AMT: int = 10000; let (tx1, rx1) = channel::<int>(); let (tx2, rx2) = channel::<int>(); let (tx3, rx3) = channel::<()>(); let _t = thread::spawn(move|| { for i in 0..AMT { if i % 2 == 0 { tx1.send(i).unwrap(); } else { tx2.send(i).unwrap(); } rx3.recv().unwrap(); } }); for i in 0..AMT { select! { i1 = rx1.recv() => { assert!(i % 2 == 0 && i == i1.unwrap()); }, i2 = rx2.recv() => { assert!(i % 2 == 1 && i == i2.unwrap()); } } tx3.send(()).unwrap(); } } #[test] fn cloning() { let (tx1, rx1) = channel::<int>(); let (_tx2, rx2) = channel::<int>(); let (tx3, rx3) = channel::<()>(); let _t = thread::spawn(move|| { rx3.recv().unwrap(); tx1.clone(); assert_eq!(rx3.try_recv(), Err(TryRecvError::Empty)); tx1.send(2).unwrap(); rx3.recv().unwrap(); }); tx3.send(()).unwrap(); select! { _i1 = rx1.recv() => {}, _i2 = rx2.recv() => panic!() } tx3.send(()).unwrap(); } #[test] fn cloning2() { let (tx1, rx1) = channel::<int>(); let (_tx2, rx2) = channel::<int>(); let (tx3, rx3) = channel::<()>(); let _t = thread::spawn(move|| { rx3.recv().unwrap(); tx1.clone(); assert_eq!(rx3.try_recv(), Err(TryRecvError::Empty)); tx1.send(2).unwrap(); rx3.recv().unwrap(); }); tx3.send(()).unwrap(); select! { _i1 = rx1.recv() => {}, _i2 = rx2.recv() => panic!() } tx3.send(()).unwrap(); } #[test] fn cloning3() { let (tx1, rx1) = channel::<()>(); let (tx2, rx2) = channel::<()>(); let (tx3, rx3) = channel::<()>(); let _t = thread::spawn(move|| { let s = Select::new(); let mut h1 = s.handle(&rx1); let mut h2 = s.handle(&rx2); unsafe { h2.add(); } unsafe { h1.add(); } assert_eq!(s.wait(), h2.id); tx3.send(()).unwrap(); }); for _ in 0..1000 { thread::yield_now(); } drop(tx1.clone()); tx2.send(()).unwrap(); rx3.recv().unwrap(); } #[test] fn preflight1() { let (tx, rx) = channel(); tx.send(()).unwrap(); select! { _n = rx.recv() => {} } } #[test] fn preflight2() { let (tx, rx) = channel(); tx.send(()).unwrap(); tx.send(()).unwrap(); select! { _n = rx.recv() => {} } } #[test] fn preflight3() { let (tx, rx) = channel(); drop(tx.clone()); tx.send(()).unwrap(); select! { _n = rx.recv() => {} } } #[test] fn preflight4() { let (tx, rx) = channel(); tx.send(()).unwrap(); let s = Select::new(); let mut h = s.handle(&rx); unsafe { h.add(); } assert_eq!(s.wait2(false), h.id); } #[test] fn preflight5() { let (tx, rx) = channel(); tx.send(()).unwrap(); tx.send(()).unwrap(); let s = Select::new(); let mut h = s.handle(&rx); unsafe { h.add(); } assert_eq!(s.wait2(false), h.id); } #[test] fn preflight6() { let (tx, rx) = channel(); drop(tx.clone()); tx.send(()).unwrap(); let s = Select::new(); let mut h = s.handle(&rx); unsafe { h.add(); } assert_eq!(s.wait2(false), h.id); } #[test] fn preflight7() { let (tx, rx) = channel::<()>(); drop(tx); let s = Select::new(); let mut h = s.handle(&rx); unsafe { h.add(); } assert_eq!(s.wait2(false), h.id); } #[test] fn preflight8() { let (tx, rx) = channel(); tx.send(()).unwrap(); drop(tx); rx.recv().unwrap(); let s = Select::new(); let mut h = s.handle(&rx); unsafe { h.add(); } assert_eq!(s.wait2(false), h.id); } #[test] fn preflight9() { let (tx, rx) = channel(); drop(tx.clone()); tx.send(()).unwrap(); drop(tx); rx.recv().unwrap(); let s = Select::new(); let mut h = s.handle(&rx); unsafe { h.add(); } assert_eq!(s.wait2(false), h.id); } #[test] fn oneshot_data_waiting() { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); let _t = thread::spawn(move|| { select! { _n = rx1.recv() => {} } tx2.send(()).unwrap(); }); for _ in 0..100 { thread::yield_now() } tx1.send(()).unwrap(); rx2.recv().unwrap(); } #[test] fn stream_data_waiting() { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); tx1.send(()).unwrap(); tx1.send(()).unwrap(); rx1.recv().unwrap(); rx1.recv().unwrap(); let _t = thread::spawn(move|| { select! { _n = rx1.recv() => {} } tx2.send(()).unwrap(); }); for _ in 0..100 { thread::yield_now() } tx1.send(()).unwrap(); rx2.recv().unwrap(); } #[test] fn shared_data_waiting() { let (tx1, rx1) = channel(); let (tx2, rx2) = channel(); drop(tx1.clone()); tx1.send(()).unwrap(); rx1.recv().unwrap(); let _t = thread::spawn(move|| { select! { _n = rx1.recv() => {} } tx2.send(()).unwrap(); }); for _ in 0..100 { thread::yield_now() } tx1.send(()).unwrap(); rx2.recv().unwrap(); } #[test] fn sync1() { let (tx, rx) = sync_channel::<int>(1); tx.send(1).unwrap(); select! { n = rx.recv() => { assert_eq!(n.unwrap(), 1); } } } #[test] fn sync2() { let (tx, rx) = sync_channel::<int>(0); let _t = thread::spawn(move|| { for _ in 0..100 { thread::yield_now() } tx.send(1).unwrap(); }); select! { n = rx.recv() => { assert_eq!(n.unwrap(), 1); } } } #[test] fn sync3() { let (tx1, rx1) = sync_channel::<int>(0); let (tx2, rx2): (Sender<int>, Receiver<int>) = channel(); let _t = thread::spawn(move|| { tx1.send(1).unwrap(); }); let _t = thread::spawn(move|| { tx2.send(2).unwrap(); }); select! { n = rx1.recv() => { let n = n.unwrap(); assert_eq!(n, 1); assert_eq!(rx2.recv().unwrap(), 2); }, n = rx2.recv() => { let n = n.unwrap(); assert_eq!(n, 2); assert_eq!(rx1.recv().unwrap(), 1); } } } }
30.697889
99
0.489793
d730891f4a0fd1c97b12ca923cbdb6e4b1beb181
6,671
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use super::{Error, Result}; use hypervisor::kvm::kvm_bindings::{kvm_device_attr, KVM_DEV_ARM_VGIC_GRP_REDIST_REGS}; use hypervisor::CpuState; use std::sync::Arc; // Relevant redistributor registers that we want to save/restore. const GICR_CTLR: u32 = 0x0000; const GICR_STATUSR: u32 = 0x0010; const GICR_WAKER: u32 = 0x0014; const GICR_PROPBASER: u32 = 0x0070; const GICR_PENDBASER: u32 = 0x0078; /* SGI and PPI Redistributor registers, offsets from RD_base */ /* * Redistributor frame offsets from RD_base which is actually SZ_ */ const GICR_SGI_OFFSET: u32 = 0x0001_0000; const GICR_IGROUPR0: u32 = GICR_SGI_OFFSET + 0x0080; const GICR_ICENABLER0: u32 = GICR_SGI_OFFSET + 0x0180; const GICR_ISENABLER0: u32 = GICR_SGI_OFFSET + 0x0100; const GICR_ISPENDR0: u32 = GICR_SGI_OFFSET + 0x0200; const GICR_ICPENDR0: u32 = GICR_SGI_OFFSET + 0x0280; const GICR_ISACTIVER0: u32 = GICR_SGI_OFFSET + 0x0300; const GICR_ICACTIVER0: u32 = GICR_SGI_OFFSET + 0x0380; const GICR_IPRIORITYR0: u32 = GICR_SGI_OFFSET + 0x0400; const GICR_ICFGR0: u32 = GICR_SGI_OFFSET + 0x0C00; const KVM_DEV_ARM_VGIC_V3_MPIDR_SHIFT: u32 = 32; const KVM_DEV_ARM_VGIC_V3_MPIDR_MASK: u64 = 0xffffffff << KVM_DEV_ARM_VGIC_V3_MPIDR_SHIFT as u64; /// This is how we represent the registers of a distributor. /// It is relrvant their offset from the base address of the /// distributor. /// Each register has a different number /// of bits_per_irq and is therefore variable length. /// First 32 interrupts (0-32) are private to each CPU (SGIs and PPIs). /// and so we save the first irq to identify between the type of the interrupt /// that the respective register deals with. struct RdistReg { /// Offset from distributor address. base: u32, /// Length of the register. length: u8, } // All or at least the registers we are interested in are 32 bit, so // we use a constant for size(u32). const REG_SIZE: u8 = 4; // Creates a vgic redistributor register. macro_rules! VGIC_RDIST_REG { ($base:expr, $len:expr) => { RdistReg { base: $base, length: $len, } }; } // List with relevant distributor registers that we will be restoring. static VGIC_RDIST_REGS: &'static [RdistReg] = &[ VGIC_RDIST_REG!(GICR_CTLR, 4), VGIC_RDIST_REG!(GICR_STATUSR, 4), VGIC_RDIST_REG!(GICR_WAKER, 4), VGIC_RDIST_REG!(GICR_PROPBASER, 8), VGIC_RDIST_REG!(GICR_PENDBASER, 8), ]; // List with relevant distributor registers that we will be restoring. static VGIC_SGI_REGS: &'static [RdistReg] = &[ VGIC_RDIST_REG!(GICR_IGROUPR0, 4), VGIC_RDIST_REG!(GICR_ICENABLER0, 4), VGIC_RDIST_REG!(GICR_ISENABLER0, 4), VGIC_RDIST_REG!(GICR_ICFGR0, 8), VGIC_RDIST_REG!(GICR_ICPENDR0, 4), VGIC_RDIST_REG!(GICR_ISPENDR0, 4), VGIC_RDIST_REG!(GICR_ICACTIVER0, 4), VGIC_RDIST_REG!(GICR_ISACTIVER0, 4), VGIC_RDIST_REG!(GICR_IPRIORITYR0, 32), ]; fn redist_attr_access( gic: &Arc<dyn hypervisor::Device>, offset: u32, typer: u64, val: &u32, set: bool, ) -> Result<()> { let mut gic_dist_attr = kvm_device_attr { group: KVM_DEV_ARM_VGIC_GRP_REDIST_REGS, attr: (typer & KVM_DEV_ARM_VGIC_V3_MPIDR_MASK) | (offset as u64), // this needs the mpidr addr: val as *const u32 as u64, flags: 0, }; if set { #[allow(clippy::unnecessary_mut_passed)] gic.set_device_attr(&mut gic_dist_attr) .map_err(Error::SetDeviceAttribute)?; } else { gic.get_device_attr(&mut gic_dist_attr) .map_err(Error::GetDeviceAttribute)?; } Ok(()) } fn access_redists_aux( gic: &Arc<dyn hypervisor::Device>, gicr_typer: &[u64], state: &mut Vec<u32>, reg_list: &'static [RdistReg], idx: &mut usize, set: bool, ) -> Result<()> { for i in gicr_typer { for rdreg in reg_list { let mut base = rdreg.base; let end = base + rdreg.length as u32; while base < end { let mut val = 0; if set { val = state[*idx]; redist_attr_access(gic, base, *i, &val, true)?; *idx += 1; } else { redist_attr_access(gic, base, *i, &val, false)?; state.push(val); } base += REG_SIZE as u32; } } } Ok(()) } /// Get redistributor registers. pub fn get_redist_regs(gic: &Arc<dyn hypervisor::Device>, gicr_typer: &[u64]) -> Result<Vec<u32>> { let mut state = Vec::new(); let mut idx: usize = 0; access_redists_aux( gic, gicr_typer, &mut state, VGIC_RDIST_REGS, &mut idx, false, )?; access_redists_aux(gic, gicr_typer, &mut state, VGIC_SGI_REGS, &mut idx, false)?; Ok(state) } /// Set redistributor registers. pub fn set_redist_regs( gic: &Arc<dyn hypervisor::Device>, gicr_typer: &[u64], state: &[u32], ) -> Result<()> { let mut idx: usize = 0; let mut mut_state = state.to_owned(); access_redists_aux( gic, gicr_typer, &mut mut_state, VGIC_RDIST_REGS, &mut idx, true, )?; access_redists_aux( gic, gicr_typer, &mut mut_state, VGIC_SGI_REGS, &mut idx, true, ) } pub fn construct_gicr_typers(vcpu_states: &[CpuState]) -> Vec<u64> { /* Pre-construct the GICR_TYPER: * For our implementation: * Top 32 bits are the affinity value of the associated CPU * CommonLPIAff == 01 (redistributors with same Aff3 share LPI table) * Processor_Number == CPU index starting from 0 * DPGS == 0 (GICR_CTLR.DPG* not supported) * Last == 1 if this is the last redistributor in a series of * contiguous redistributor pages * DirectLPI == 0 (direct injection of LPIs not supported) * VLPIS == 0 (virtual LPIs not supported) * PLPIS == 0 (physical LPIs not supported) */ let mut gicr_typers: Vec<u64> = Vec::new(); for (index, state) in vcpu_states.iter().enumerate() { let last = { if index == vcpu_states.len() - 1 { 1 } else { 0 } }; //calculate affinity let mut cpu_affid = state.mpidr & 1095233437695; cpu_affid = ((cpu_affid & 0xFF00000000) >> 8) | (cpu_affid & 0xFFFFFF); gicr_typers.push((cpu_affid << 32) | (1 << 24) | (index as u64) << 8 | (last << 4)); } gicr_typers }
31.466981
99
0.629741
f4a9f0466be59cd623fb6d234dfe29953f7d3b6c
3,661
use super::OurTree; use rust_htslib::bam; use rust_htslib::prelude::*; use std::collections::HashMap; use std::str; pub struct ChunkedGenome { trees: Option<HashMap<String, (OurTree, Vec<String>)>>, bam: bam::IndexedReader, chromosomes: Vec<String>, } impl ChunkedGenome { ///create a new chunked genome for iteration ///if you pass in a tree, it is guranteed that the splits happen ///between entries of the tree, not inside. pub fn new( trees: HashMap<String, (OurTree, Vec<String>)>, bam: bam::IndexedReader, ) -> ChunkedGenome { let chrs_in_tree_and_bam = trees .keys() .map(|x| x.clone()) .filter(|x| bam.header().tid(x.as_bytes()).is_some()) .collect(); ChunkedGenome { chromosomes: chrs_in_tree_and_bam, trees: Some(trees), bam, } } pub fn new_without_tree(bam: bam::IndexedReader) -> ChunkedGenome { ChunkedGenome { trees: None, chromosomes: bam .header() .target_names() .iter() .map(|x| str::from_utf8(x).unwrap().to_string()) .collect(), bam, } } pub fn iter(&self) -> ChunkedGenomeIterator { ChunkedGenomeIterator { cg: &self, it: self.chromosomes.iter(), last_start: 0, last_tid: 0, last_chr_length: 0, last_chr: "".to_string(), } } } pub struct ChunkedGenomeIterator<'a> { cg: &'a ChunkedGenome, it: std::slice::Iter<'a, String>, last_start: u32, last_chr: String, last_tid: u32, last_chr_length: u32, } #[derive(Debug)] pub struct Chunk { pub chr: String, pub tid: u32, pub start: u32, pub stop: u32, } impl<'a> Iterator for ChunkedGenomeIterator<'a> { type Item = Chunk; fn next(&mut self) -> Option<Chunk> { let chunk_size = 1_000_000; if self.last_start >= self.last_chr_length { let next_chr = match self.it.next() { Some(x) => x, None => return None, }; let tid = self.cg.bam.header().tid(next_chr.as_bytes()).unwrap(); let chr_length = self.cg.bam.header().target_len(tid).unwrap(); self.last_tid = tid; self.last_chr_length = chr_length; self.last_chr = next_chr.to_string(); self.last_start = 0; } let mut stop = self.last_start + chunk_size; if self.cg.trees.is_some() { let (next_tree, _next_gene_ids) = self.cg.trees.as_ref().unwrap().get(&self.last_chr).unwrap(); loop { ////this has been adjusted not to cut genes in half //cut gene in half? //option 0 for that is to pass in the gene intervals as well //just for constructing the chunks let overlapping = next_tree.find(stop..stop + 1).next(); match overlapping { None => break, Some(entry) => { let iv = entry.interval(); if iv.end + 1 < stop { panic!("WHAT?"); } stop = iv.end + 1; } } } } let c = Chunk { chr: self.last_chr.clone(), tid: self.last_tid, start: self.last_start, stop, }; self.last_start = stop; Some(c) } }
30.256198
77
0.503141
8f2322af1e3bf6a3c564e8bce5cd4d788bc6c623
596
use crate::Scalar; use ndarray::ArrayViewMut2; #[allow(clippy::cast_possible_wrap)] pub unsafe fn trsm<A>(a: *const A, row_stride: isize, col_stride: isize, mut b: ArrayViewMut2<A>) where A: Scalar, { for j in 0..b.ncols() { for k in 0..b.nrows() { if *b.uget((k, j)) == A::zero() { continue; } for i in k + 1..b.nrows() { let prod = *b.uget((k, j)) * *a.offset(row_stride * i as isize + col_stride * k as isize); *b.uget_mut((i, j)) -= prod; } } } }
27.090909
99
0.474832
5b034b9671182bff8b9e606e575df2c18ad9f2a1
1,916
#![warn(missing_docs)] //! This crate provides building blocks for developing Internet Computer Canister. //! //! You can check the [Internet Computer Specification]( //! https://smartcontracts.org/docs/interface-spec/index.html#system-api-imports) //! for a full list of the system API functions. pub mod api; mod futures; mod printer; pub mod storage; pub use api::call::call; pub use api::{caller, id, print, trap}; static mut DONE: bool = false; /// Re-exports crates those are necessary for using ic-cdk pub mod export { pub use candid; pub use candid::types::ic_types::Principal; pub use serde; } /// Setup the stdlib hooks. pub fn setup() { unsafe { if DONE { return; } DONE = true; } printer::hook() } /// Block on a promise in a WASM-friendly way (no multithreading!). pub fn block_on<F: 'static + std::future::Future<Output = ()>>(future: F) { futures::block_on(future); } /// Format and then print the formatted message #[cfg(target_arch = "wasm32")] #[macro_export] macro_rules! println { ($fmt:expr) => (ic_cdk::print(format!($fmt))); ($fmt:expr, $($arg:tt)*) => (ic_cdk::print(format!($fmt, $($arg)*))); } /// Format and then print the formatted message #[cfg(not(target_arch = "wasm32"))] #[macro_export] macro_rules! println { ($fmt:expr) => (std::println!($fmt)); ($fmt:expr, $($arg:tt)*) => (std::println!($fmt, $($arg)*)); } /// Format and then print the formatted message #[cfg(target_arch = "wasm32")] #[macro_export] macro_rules! eprintln { ($fmt:expr) => (ic_cdk::print(format!($fmt))); ($fmt:expr, $($arg:tt)*) => (ic_cdk::print(format!($fmt, $($arg)*))); } /// Format and then print the formatted message #[cfg(not(target_arch = "wasm32"))] #[macro_export] macro_rules! eprintln { ($fmt:expr) => (std::eprintln!($fmt)); ($fmt:expr, $($arg:tt)*) => (std::eprintln!($fmt, $($arg)*)); }
26.246575
82
0.631002
76dff376d813313f611f9ecc1876fc005d037e49
11,184
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]> // // 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. /*! Pin configuration. Some pins that could be configured here may be missing from actual MCU depending on the package. */ use core::intrinsics::abort; use core::option::Option; use self::Port::*; #[path="../../util/ioreg.rs"] #[macro_use] mod ioreg; #[path="../../util/wait_for.rs"] #[macro_use] mod wait_for; /// Available port names. #[allow(missing_docs)] #[derive(Clone, Copy)] pub enum Port { Port0, Port1, Port2, Port3, Port4, } /// Pin functions (GPIO or up to three additional functions). #[derive(PartialEq, Clone, Copy)] #[allow(missing_docs)] pub enum Function { Gpio = 0, AltFunction1 = 1, AltFunction2 = 2, AltFunction3 = 3, } /// Pin modes #[derive(PartialEq, Clone, Copy)] #[allow(missing_docs)] pub enum Mode { PullUp = 0, Repeater = 1, Floating = 2, PullDown = 3, } /// Structure to describe the location of a pin #[derive(Clone, Copy)] pub struct Pin { /// Port the pin is attached to port: Port, /// Pin number in the port pin: u8 } impl Pin { /// Create and setup a Pin pub fn new(port: Port, pin_index: u8, function: Function, gpiodir: Option<::hal::pin::GpioDirection>) -> Pin { let pin = Pin { port: port, pin: pin_index, }; pin.setup_regs(function, gpiodir); pin } fn setup_regs(&self, function: Function, gpiodir: Option<::hal::pin::GpioDirection>) { let (offset, reg) = self.get_pinsel_reg_and_offset(); let fun_bits: u32 = (function as u32) << ((offset as usize) * 2); let mask_bits: u32 = !(3u32 << ((offset as usize) * 2)); let val: u32 = reg.value(); let new_val = (val & mask_bits) | fun_bits; reg.set_value(new_val); match function { Function::Gpio => (self as &::hal::pin::Gpio).set_direction(gpiodir.unwrap()), Function::AltFunction1 => match self.adc_channel() { Some(_) => self.setup_adc(), _ => {}, }, _ => {}, } } fn set_mode(&self, mode: Mode) { let (offset, reg) = self.get_pimode_reg_and_offset(); let value = reg.value() | (mode as u32) << offset; reg.set_value(value) } fn gpioreg(&self) -> &reg::Gpio { match self.port { Port0 => &reg::GPIO_0, Port1 => &reg::GPIO_1, Port2 => &reg::GPIO_2, Port3 => &reg::GPIO_3, Port4 => &reg::GPIO_4, } } fn get_pinsel_reg_and_offset(&self) -> (u8, &reg::PINSEL) { match self.port { Port0 => match self.pin { 0...15 => (self.pin, &reg::PINSEL0), 16...30 => (self.pin-16, &reg::PINSEL1), _ => unsafe { abort() }, }, Port1 => match self.pin { 0...15 => (self.pin, &reg::PINSEL2), 16...31 => (self.pin-16, &reg::PINSEL3), _ => unsafe { abort() }, }, Port2 => match self.pin { 0...13 => (self.pin, &reg::PINSEL4), _ => unsafe { abort() }, }, Port3 => match self.pin { 25|26 => (self.pin-16, &reg::PINSEL7), _ => unsafe { abort() }, }, Port4 => match self.pin { 28|29 => (self.pin-16, &reg::PINSEL9), _ => unsafe { abort() }, }, } } fn get_pimode_reg_and_offset(&self) -> (u8, &reg::PINMODE) { match self.port { Port0 => match self.pin { 0...11 => (self.pin*2, &reg::PINMODE0), 15 => (self.pin*2, &reg::PINMODE0), 16...26 => ((self.pin-16)*2, &reg::PINMODE1), _ => unsafe { abort() }, }, Port1 => match self.pin { 0...1 => (self.pin*2, &reg::PINMODE2), 4 => (self.pin*2, &reg::PINMODE2), 8...10 => (self.pin*2, &reg::PINMODE2), 14...15 => (self.pin*2, &reg::PINMODE2), 16...31 => ((self.pin-16)*2, &reg::PINMODE3), _ => unsafe { abort() }, }, Port2 => match self.pin { 0...13 => (self.pin*2, &reg::PINMODE4), _ => unsafe { abort() }, }, Port3 => match self.pin { 25 => (18, &reg::PINMODE7), 26 => (20, &reg::PINMODE7), _ => unsafe { abort() }, }, Port4 => match self.pin { 28 => (24, &reg::PINMODE9), 29 => (26, &reg::PINMODE9), _ => unsafe { abort() }, }, } } /// Get adc channel number fn adc_channel(&self) -> Option<u8> { match self.port { Port0 => match self.pin { 2 => Some(7), 3 => Some(6), 23...26 => Some(self.pin - 23), _ => None, }, Port1 => match self.pin { 30...31 => Some(self.pin - 26), _ => None, }, Port2 => None, Port3 => None, Port4 => None, } } fn setup_adc(&self) { // ensure power is turned on let pconp = &reg::PCONP; let pconp_value = pconp.value(); pconp.set_value(pconp_value | (1 << 12)); // set PCLK of ADC to /1 let pclksel0 = &reg::PCLKSEL0; let mut pclksel0_val: u32 = pclksel0.value(); pclksel0_val &= !(0x3 << 24); pclksel0_val |= 0x1 << 24; pclksel0.set_value(pclksel0_val); fn div_round_up(x: u32, y: u32) -> u32 { (x + (y - 1)) / y } let pclk = ::hal::lpc17xx::system_clock::system_clock(); let max_adc_clk = 13000000; let clkdiv = div_round_up(pclk, max_adc_clk); let cr = (0 << 0) // SEL: 0 = no channels selected | (clkdiv << 8) // CLKDIV: PCLK max ~= 25MHz, /25 to give safe 1MHz at fastest | (0 << 16) // BURST: 0 = software control | (0 << 17) // CLKS: not applicable | (1 << 21) // PDN: 1 = operational | (0 << 24) // START: 0 = no start | (0 << 27); // EDGE: not applicable &reg::ADC.set_CR(cr); self.set_mode(Mode::Floating); } } impl ::hal::pin::Gpio for Pin { /// Sets output GPIO value to high. fn set_high(&self) { self.gpioreg().set_FIOSET(1 << (self.pin as usize)); } /// Sets output GPIO value to low. fn set_low(&self) { self.gpioreg().set_FIOCLR(1 << (self.pin as usize)); } /// Returns input GPIO level. fn level(&self) -> ::hal::pin::GpioLevel { let bit: u32 = 1 << (self.pin as usize); let reg = self.gpioreg(); match reg.FIOPIN() & bit { 0 => ::hal::pin::Low, _ => ::hal::pin::High, } } /// Sets output GPIO direction. fn set_direction(&self, new_mode: ::hal::pin::GpioDirection) { let bit: u32 = 1 << (self.pin as usize); let mask: u32 = !bit; let reg = self.gpioreg(); let val: u32 = reg.FIODIR(); let new_val: u32 = match new_mode { ::hal::pin::In => val & mask, ::hal::pin::Out => (val & mask) | bit, }; reg.set_FIODIR(new_val); } } impl ::hal::pin::Adc for Pin { /// Read analog input value of pin fn read(&self) -> u32 { let adc = &reg::ADC; let channel = self.adc_channel().unwrap(); let mut cr = adc.CR(); cr &= !(0xFF as u32); cr |= 1 << channel; cr |= (1 << 24) as u32; adc.set_CR(cr); wait_for!((adc.STAT() & (1 << channel)) != 0); let data = match channel { 0 => adc.DR0(), 1 => adc.DR1(), 2 => adc.DR2(), 3 => adc.DR3(), 4 => adc.DR4(), 5 => adc.DR5(), 6 => adc.DR6(), 7 => adc.DR7(), _ => unsafe { abort() }, }; adc.set_CR((adc.CR() as u32) & !(1 << 24)); (data >> 4) & 0xFFF // 12 bit range } } /// Sets the state of trace port interface. pub fn set_trace_port_interface_enabled(enabled: bool) { let value: u32 = if enabled { 0b1000 } else { 0 }; reg::PINSEL10.set_value(value); } mod reg { use volatile_cell::VolatileCell; ioreg_old!(PINSEL: u32, value); reg_rw!(PINSEL, u32, value, set_value, value); extern { #[link_name="lpc17xx_iomem_PINSEL0"] pub static PINSEL0: PINSEL; #[link_name="lpc17xx_iomem_PINSEL1"] pub static PINSEL1: PINSEL; #[link_name="lpc17xx_iomem_PINSEL2"] pub static PINSEL2: PINSEL; #[link_name="lpc17xx_iomem_PINSEL3"] pub static PINSEL3: PINSEL; #[link_name="lpc17xx_iomem_PINSEL4"] pub static PINSEL4: PINSEL; #[link_name="lpc17xx_iomem_PINSEL7"] pub static PINSEL7: PINSEL; #[link_name="lpc17xx_iomem_PINSEL9"] pub static PINSEL9: PINSEL; #[link_name="lpc17xx_iomem_PINSEL10"] pub static PINSEL10: PINSEL; } ioreg_old!(PINMODE: u32, value); reg_rw!(PINMODE, u32, value, set_value, value); extern { #[link_name="lpc17xx_iomem_PINMODE0"] pub static PINMODE0: PINMODE; #[link_name="lpc17xx_iomem_PINMODE1"] pub static PINMODE1: PINMODE; #[link_name="lpc17xx_iomem_PINMODE2"] pub static PINMODE2: PINMODE; #[link_name="lpc17xx_iomem_PINMODE3"] pub static PINMODE3: PINMODE; #[link_name="lpc17xx_iomem_PINMODE4"] pub static PINMODE4: PINMODE; #[link_name="lpc17xx_iomem_PINMODE7"] pub static PINMODE7: PINMODE; #[link_name="lpc17xx_iomem_PINMODE9"] pub static PINMODE9: PINMODE; } ioreg_old!(Gpio: u32, FIODIR, _r0, _r1, _r2, FIOMASK, FIOPIN, FIOSET, FIOCLR); reg_rw!(Gpio, u32, FIODIR, set_FIODIR, FIODIR); reg_rw!(Gpio, u32, FIOMASK, set_FIOMASK, FIOMASK); reg_rw!(Gpio, u32, FIOPIN, set_FIOPIN, FIOPIN); reg_rw!(Gpio, u32, FIOSET, set_FIOSET, FIOSET); reg_rw!(Gpio, u32, FIOCLR, set_FIOCLR, FIOCLR); extern { #[link_name="lpc17xx_iomem_GPIO0"] pub static GPIO_0: Gpio; #[link_name="lpc17xx_iomem_GPIO1"] pub static GPIO_1: Gpio; #[link_name="lpc17xx_iomem_GPIO2"] pub static GPIO_2: Gpio; #[link_name="lpc17xx_iomem_GPIO3"] pub static GPIO_3: Gpio; #[link_name="lpc17xx_iomem_GPIO4"] pub static GPIO_4: Gpio; } ioreg_old!(PCONP: u32, value); ioreg_old!(PCLKSEL0: u32, value); reg_rw!(PCONP, u32, value, set_value, value); reg_rw!(PCLKSEL0, u32, value, set_value, value); extern { #[link_name="lpc17xx_iomem_PCONP"] pub static PCONP: PCONP; #[link_name="lpc17xx_iomem_PCLKSEL0"] pub static PCLKSEL0: PCLKSEL0; } ioreg_old!(ADC: u32, CR, GDR, pad_0, INTEN, DR0, DR1, DR2, DR3, DR4, DR5, DR6, DR7, STAT, TRM); reg_rw!(ADC, u32, CR, set_CR, CR); reg_r!(ADC, u32, GDR, GDR); reg_rw!(ADC, u32, INTEN, set_INTEN, INTEN); reg_rw!(ADC, u32, DR0, set_DR0, DR0); reg_rw!(ADC, u32, DR1, set_DR1, DR1); reg_rw!(ADC, u32, DR2, set_DR2, DR2); reg_rw!(ADC, u32, DR3, set_DR3, DR3); reg_rw!(ADC, u32, DR4, set_DR4, DR4); reg_rw!(ADC, u32, DR5, set_DR5, DR5); reg_rw!(ADC, u32, DR6, set_DR6, DR6); reg_rw!(ADC, u32, DR7, set_DR7, DR7); reg_rw!(ADC, u32, STAT, set_STAT, STAT); extern { #[link_name="lpc17xx_iomem_ADC"] pub static ADC: ADC; } }
29.277487
97
0.581724
f7b64a1ccd98155af4628fdc1a9f95745dadb89b
19,256
use std::collections::HashMap; #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] #[serde(default)] #[serde(rename_all = "kebab-case")] pub struct Config { pub files: Walk, pub default: EngineConfig, #[serde(rename = "type")] pub type_: TypeEngineConfig, #[serde(skip)] pub overrides: EngineConfig, } impl Config { pub fn from_dir(cwd: &std::path::Path) -> Result<Option<Self>, anyhow::Error> { let config = if let Some(path) = find_project_file(cwd, &["typos.toml", "_typos.toml", ".typos.toml"]) { log::debug!("Loading {}", path.display()); Some(Self::from_file(&path)?) } else { None }; Ok(config) } pub fn from_file(path: &std::path::Path) -> Result<Self, anyhow::Error> { let s = std::fs::read_to_string(path)?; Self::from_toml(&s) } pub fn from_toml(data: &str) -> Result<Self, anyhow::Error> { let content = toml_edit::easy::from_str(data)?; Ok(content) } pub fn from_defaults() -> Self { Self { files: Walk::from_defaults(), default: EngineConfig::from_defaults(), type_: TypeEngineConfig::from_defaults(), overrides: EngineConfig::default(), } } pub fn update(&mut self, source: &Config) { self.files.update(&source.files); self.default.update(&source.default); self.type_.update(&source.type_); self.overrides.update(&source.overrides); } } #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] #[serde(default)] #[serde(rename_all = "kebab-case")] pub struct Walk { pub extend_exclude: Vec<String>, /// Skip hidden files and directories. pub ignore_hidden: Option<bool>, /// Respect ignore files. pub ignore_files: Option<bool>, /// Respect .ignore files. pub ignore_dot: Option<bool>, /// Respect ignore files in vcs directories. pub ignore_vcs: Option<bool>, /// Respect global ignore files. pub ignore_global: Option<bool>, /// Respect ignore files in parent directories. pub ignore_parent: Option<bool>, } impl Walk { pub fn from_defaults() -> Self { let empty = Self::default(); Self { extend_exclude: empty.extend_exclude.clone(), ignore_hidden: Some(empty.ignore_hidden()), ignore_files: Some(true), ignore_dot: Some(empty.ignore_dot()), ignore_vcs: Some(empty.ignore_vcs()), ignore_global: Some(empty.ignore_global()), ignore_parent: Some(empty.ignore_parent()), } } pub fn update(&mut self, source: &Walk) { self.extend_exclude .extend(source.extend_exclude.iter().cloned()); if let Some(source) = source.ignore_hidden { self.ignore_hidden = Some(source); } if let Some(source) = source.ignore_files { self.ignore_files = Some(source); self.ignore_dot = None; self.ignore_vcs = None; self.ignore_global = None; self.ignore_parent = None; } if let Some(source) = source.ignore_dot { self.ignore_dot = Some(source); } if let Some(source) = source.ignore_vcs { self.ignore_vcs = Some(source); self.ignore_global = None; } if let Some(source) = source.ignore_global { self.ignore_global = Some(source); } if let Some(source) = source.ignore_parent { self.ignore_parent = Some(source); } } pub fn extend_exclude(&self) -> &[String] { &self.extend_exclude } pub fn ignore_hidden(&self) -> bool { self.ignore_hidden.unwrap_or(true) } pub fn ignore_dot(&self) -> bool { self.ignore_dot.or(self.ignore_files).unwrap_or(true) } pub fn ignore_vcs(&self) -> bool { self.ignore_vcs.or(self.ignore_files).unwrap_or(true) } pub fn ignore_global(&self) -> bool { self.ignore_global .or(self.ignore_vcs) .or(self.ignore_files) .unwrap_or(true) } pub fn ignore_parent(&self) -> bool { self.ignore_parent.or(self.ignore_files).unwrap_or(true) } } #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] #[serde(default)] #[serde(transparent)] pub struct TypeEngineConfig { pub patterns: std::collections::HashMap<kstring::KString, GlobEngineConfig>, } impl TypeEngineConfig { pub fn from_defaults() -> Self { let empty = Self::default(); Self { patterns: empty.patterns().collect(), } } pub fn update(&mut self, source: &Self) { for (type_name, engine) in source.patterns.iter() { self.patterns .entry(type_name.to_owned()) .or_insert_with(GlobEngineConfig::default) .update(engine); } } pub fn patterns(&self) -> impl Iterator<Item = (kstring::KString, GlobEngineConfig)> { let mut patterns = self.patterns.clone(); patterns .entry("lock".into()) .or_insert_with(|| GlobEngineConfig { extend_glob: Vec::new(), engine: EngineConfig { check_file: Some(false), ..Default::default() }, }); patterns .entry("rust".into()) .or_insert_with(|| GlobEngineConfig { // From a spell-check perspective, these are more closely related to Rust than Toml extend_glob: vec!["Cargo.toml".into()], engine: EngineConfig { dict: Some(DictConfig { extend_words: maplit::hashmap! { "flate".into() => "flate".into(), "ser".into() => "ser".into(), }, ..Default::default() }), ..Default::default() }, }); patterns .entry("python".into()) .or_insert_with(|| GlobEngineConfig { // From a spell-check perspective, these are more closely related to Python than Toml extend_glob: vec!["pyproject.toml".into()], engine: EngineConfig { ..Default::default() }, }); patterns.entry("cert".into()).or_insert_with(|| { GlobEngineConfig { extend_glob: vec![ // Certificate files: "*.crt".into(), "*.cer".into(), "*.ca-bundle".into(), "*.p7b".into(), "*.p7c".into(), "*.p7s".into(), "*.pem".into(), // Keystore Files: "*.key".into(), "*.keystore".into(), "*.jks".into(), // Combined certificate and key files: "*.p12".into(), "*.pfx".into(), "*.pem".into(), ], engine: EngineConfig { check_file: Some(false), ..Default::default() }, } }); patterns.into_iter() } } #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] //#[serde(deny_unknown_fields)] // Doesn't work with `flatten` #[serde(default)] #[serde(rename_all = "kebab-case")] pub struct GlobEngineConfig { pub extend_glob: Vec<kstring::KString>, #[serde(flatten)] pub engine: EngineConfig, } impl GlobEngineConfig { pub fn update(&mut self, source: &GlobEngineConfig) { self.extend_glob.extend(source.extend_glob.iter().cloned()); self.engine.update(&source.engine); } } #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] //#[serde(deny_unknown_fields)] // Doesn't work with `flatten` #[serde(default)] #[serde(rename_all = "kebab-case")] pub struct EngineConfig { /// Check binary files. pub binary: Option<bool>, /// Verifying spelling in file names. pub check_filename: Option<bool>, /// Verifying spelling in files. pub check_file: Option<bool>, #[serde(flatten)] pub tokenizer: Option<TokenizerConfig>, #[serde(flatten)] pub dict: Option<DictConfig>, } impl EngineConfig { pub fn from_defaults() -> Self { let empty = Self::default(); EngineConfig { binary: Some(empty.binary()), check_filename: Some(empty.check_filename()), check_file: Some(empty.check_file()), tokenizer: Some( empty .tokenizer .unwrap_or_else(TokenizerConfig::from_defaults), ), dict: Some(empty.dict.unwrap_or_else(DictConfig::from_defaults)), } } pub fn update(&mut self, source: &EngineConfig) { if let Some(source) = source.binary { self.binary = Some(source); } if let Some(source) = source.check_filename { self.check_filename = Some(source); } if let Some(source) = source.check_file { self.check_file = Some(source); } if let Some(source) = source.tokenizer.as_ref() { let mut tokenizer = None; std::mem::swap(&mut tokenizer, &mut self.tokenizer); let mut tokenizer = tokenizer.unwrap_or_default(); tokenizer.update(source); let mut tokenizer = Some(tokenizer); std::mem::swap(&mut tokenizer, &mut self.tokenizer); } if let Some(source) = source.dict.as_ref() { let mut dict = None; std::mem::swap(&mut dict, &mut self.dict); let mut dict = dict.unwrap_or_default(); dict.update(source); let mut dict = Some(dict); std::mem::swap(&mut dict, &mut self.dict); } } pub fn binary(&self) -> bool { self.binary.unwrap_or(false) } pub fn check_filename(&self) -> bool { self.check_filename.unwrap_or(true) } pub fn check_file(&self) -> bool { self.check_file.unwrap_or(true) } } #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] #[serde(default)] #[serde(rename_all = "kebab-case")] pub struct TokenizerConfig { /// Allow unicode characters in identifiers (and not just ASCII) pub unicode: Option<bool>, /// Do not check identifiers that appear to be hexadecimal values. pub ignore_hex: Option<bool>, /// Allow identifiers to start with digits, in addition to letters. pub identifier_leading_digits: Option<bool>, } impl TokenizerConfig { pub fn from_defaults() -> Self { let empty = Self::default(); Self { unicode: Some(empty.unicode()), ignore_hex: Some(empty.ignore_hex()), identifier_leading_digits: Some(empty.identifier_leading_digits()), } } pub fn update(&mut self, source: &TokenizerConfig) { if let Some(source) = source.unicode { self.unicode = Some(source); } if let Some(source) = source.ignore_hex { self.ignore_hex = Some(source); } if let Some(source) = source.identifier_leading_digits { self.identifier_leading_digits = Some(source); } } pub fn unicode(&self) -> bool { self.unicode.unwrap_or(true) } pub fn ignore_hex(&self) -> bool { self.ignore_hex.unwrap_or(true) } pub fn identifier_leading_digits(&self) -> bool { self.identifier_leading_digits.unwrap_or(false) } } #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] #[serde(default)] #[serde(rename_all = "kebab-case")] pub struct DictConfig { pub locale: Option<Locale>, pub extend_identifiers: HashMap<kstring::KString, kstring::KString>, pub extend_words: HashMap<kstring::KString, kstring::KString>, } impl DictConfig { pub fn from_defaults() -> Self { let empty = Self::default(); Self { locale: Some(empty.locale()), extend_identifiers: Default::default(), extend_words: Default::default(), } } pub fn update(&mut self, source: &DictConfig) { if let Some(source) = source.locale { self.locale = Some(source); } self.extend_identifiers.extend( source .extend_identifiers .iter() .map(|(key, value)| (key.clone(), value.clone())), ); self.extend_words.extend( source .extend_words .iter() .map(|(key, value)| (key.clone(), value.clone())), ); } pub fn locale(&self) -> Locale { self.locale.unwrap_or_default() } pub fn extend_identifiers(&self) -> Box<dyn Iterator<Item = (&str, &str)> + '_> { Box::new( self.extend_identifiers .iter() .map(|(k, v)| (k.as_str(), v.as_str())), ) } pub fn extend_words(&self) -> Box<dyn Iterator<Item = (&str, &str)> + '_> { Box::new( self.extend_words .iter() .map(|(k, v)| (k.as_str(), v.as_str())), ) } } fn find_project_file(dir: &std::path::Path, names: &[&str]) -> Option<std::path::PathBuf> { let mut file_path = dir.join("placeholder"); for name in names { file_path.set_file_name(name); if file_path.exists() { return Some(file_path); } } None } #[derive(Debug, Copy, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "kebab-case")] pub enum Locale { En, EnUs, EnGb, EnCa, EnAu, } impl Locale { pub const fn category(self) -> Option<varcon_core::Category> { match self { Locale::En => None, Locale::EnUs => Some(varcon_core::Category::American), Locale::EnGb => Some(varcon_core::Category::BritishIse), Locale::EnCa => Some(varcon_core::Category::Canadian), Locale::EnAu => Some(varcon_core::Category::Australian), } } pub const fn variants() -> [&'static str; 5] { ["en", "en-us", "en-gb", "en-ca", "en-au"] } } impl Default for Locale { fn default() -> Self { Locale::En } } impl std::str::FromStr for Locale { type Err = String; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { match s { "en" => Ok(Locale::En), "en-us" => Ok(Locale::EnUs), "en-gb" => Ok(Locale::EnGb), "en-ca" => Ok(Locale::EnCa), "en-au" => Ok(Locale::EnAu), _ => Err("valid values: en, en-us, en-gb, en-ca, en-au".to_owned()), } } } impl std::fmt::Display for Locale { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match *self { Locale::En => write!(f, "en"), Locale::EnUs => write!(f, "en-us"), Locale::EnGb => write!(f, "en-gb"), Locale::EnCa => write!(f, "en-ca"), Locale::EnAu => write!(f, "en-au"), } } } #[cfg(test)] mod test { use super::*; #[test] fn test_from_defaults() { let null = Config::default(); let defaulted = Config::from_defaults(); assert_ne!(defaulted, null); assert_ne!(defaulted.files, null.files); assert_ne!(defaulted.default, null.default); assert_ne!(defaulted.default.tokenizer, null.default.tokenizer); assert_ne!(defaulted.default.dict, null.default.dict); } #[test] fn test_update_from_nothing() { let null = Config::default(); let defaulted = Config::from_defaults(); let mut actual = defaulted.clone(); actual.update(&null); assert_eq!(actual, defaulted); } #[test] fn test_update_from_defaults() { let null = Config::default(); let defaulted = Config::from_defaults(); let mut actual = null; actual.update(&defaulted); assert_eq!(actual, defaulted); } #[test] fn test_extend_glob_updates() { let null = GlobEngineConfig::default(); let extended = GlobEngineConfig { extend_glob: vec!["*.foo".into()], ..Default::default() }; let mut actual = null; actual.update(&extended); assert_eq!(actual, extended); } #[test] fn test_extend_glob_extends() { let base = GlobEngineConfig { extend_glob: vec!["*.foo".into()], ..Default::default() }; let extended = GlobEngineConfig { extend_glob: vec!["*.bar".into()], ..Default::default() }; let mut actual = base; actual.update(&extended); let expected: Vec<kstring::KString> = vec!["*.foo".into(), "*.bar".into()]; assert_eq!(actual.extend_glob, expected); } #[test] fn parse_extend_globs() { let input = r#"[type.po] extend-glob = ["*.po"] check-file = true "#; let mut expected = Config::default(); expected.type_.patterns.insert( "po".into(), GlobEngineConfig { extend_glob: vec!["*.po".into()], engine: EngineConfig { tokenizer: Some(TokenizerConfig::default()), dict: Some(DictConfig::default()), check_file: Some(true), ..Default::default() }, }, ); let actual = Config::from_toml(input).unwrap(); assert_eq!(actual, expected); } #[test] fn parse_extend_words() { let input = r#"[type.shaders] extend-glob = [ '*.shader', '*.cginc', ] [type.shaders.extend-words] inout = "inout" "#; let mut expected = Config::default(); expected.type_.patterns.insert( "shaders".into(), GlobEngineConfig { extend_glob: vec!["*.shader".into(), "*.cginc".into()], engine: EngineConfig { tokenizer: Some(TokenizerConfig::default()), dict: Some(DictConfig { extend_words: maplit::hashmap! { "inout".into() => "inout".into(), }, ..Default::default() }), ..Default::default() }, }, ); let actual = Config::from_toml(input).unwrap(); assert_eq!(actual, expected); } }
30.613672
101
0.539572
385e4dfd91fc53ecf5de5ca92ac8828fa7ab4eb4
69
//! Awesome module //! Does stuff! <caret> fn undocumented_fn() {}
9.857143
23
0.637681
283db16f7384cd74ac290a0671531e2df13c52ed
39,044
/* * Copyright (c) 2015-2021, SALT. * This file is part of HashtagBlessedII and is distributed under the 3-clause BSD license. * See LICENSE.md for terms of use. */ use crate::util::*; use crate::arm::threading::*; use crate::arm::cache::*; use crate::vm::vmmu::*; use crate::logger::*; use alloc::collections::BTreeMap; use crate::hos::smc::*; use crate::util::*; use core::sync::atomic::{AtomicBool, Ordering}; pub const AHB_BASE: u32 = 0x6000C000; pub const AHB_ARBITRATION_DISABLE: u32 = (AHB_BASE + 0x004); pub const MC_BASE: u64 = (0x70019000); pub const MC_END: u64 = (0x7001A000); pub const MC_ERR_STATUS: u64 = (MC_BASE + 0x8); pub const MC_ERR_ADR: u64 = (MC_BASE + 0xC); pub const MC_SMMU_CONFIG: u64 = (MC_BASE + 0x10); pub const MC_SMMU_TLB_CONFIG: u64 = (MC_BASE + 0x14); pub const MC_SMMU_PTC_CONFIG: u64 = (MC_BASE + 0x18); pub const MC_SMMU_PTB_ASID: u64 = (MC_BASE + 0x1C); pub const MC_SMMU_PTB_DATA: u64 = (MC_BASE + 0x20); pub const MC_SMMU_TLB_FLUSH: u64 = (MC_BASE + 0x30); pub const MC_SMMU_PTC_FLUSH: u64 = (MC_BASE + 0x34); pub const MC_EMEM_CFG: u64 = (MC_BASE + 0x50); pub const MC_EMEM_ADR_CFG: u64 = (MC_BASE + 0x54); pub const MC_SMMU_PPCS1_ASID: u64 = (MC_BASE + 0x298); pub const MC_SMMU_DC_ASID: u64 = (MC_BASE + 0x240); // Display0A/0B/0C pub const MC_SMMU_DCB_ASID: u64 = (MC_BASE + 0x244); pub const MC_SMMU_NVENC_ASID: u64 = (MC_BASE + 0x264); pub const MC_SMMU_NV_ASID: u64 = (MC_BASE + 0x268); pub const MC_SMMU_NV2_ASID: u64 = (MC_BASE + 0x26C); pub const MC_SMMU_VI_ASID: u64 = (MC_BASE + 0x280); pub const MC_SMMU_TSEC_ASID: u64 = (MC_BASE + 0x294); pub const MC_SMMU_PTC_FLUSH_1: u64 = (MC_BASE + 0x9B8); pub const MC_SMMU_SDMMC1A_ASID: u64 = (MC_BASE + 0xA94); pub const MC_SMMU_SDMMC2A_ASID: u64 = (MC_BASE + 0xA98); pub const MC_SMMU_SDMMC3A_ASID: u64 = (MC_BASE + 0xA9C); pub const MC_SMMU_SDMMC4A_ASID: u64 = (MC_BASE + 0xAA0); pub const MC_SMMU_GPU_ASID: u64 = (MC_BASE + 0xAA8); pub const MC_SMMU_GPUB_ASID: u64 = (MC_BASE + 0xAAC); pub const SMMU_NUM_PAGES: usize = 0x400; static mut PTB_SET: bool = false; static mut TLB_FLUSH_SET: bool = false; static mut PTC_FLUSH_SET: bool = false; static mut LAST_MC_SMMU_TLB_FLUSH: u32 = 0; static mut LAST_MC_SMMU_PTC_FLUSH: u32 = 0; static mut LAST_MC_SMMU_PTC_FLUSH_HI: u32 = 0; static mut SE_BUFFER: u64 = 0; static mut SE_BUFFER_ADJ: u32 = 0; static mut SDMMC_ASID: u8 = 6; static mut SDMMC_BUFFER: u64 = 0; static mut SDMMC_BUFFER_ADJ: u32 = 0; static mut DC_ASID: u8 = 7; static mut DC_BUFFER: u64 = 0; static mut DC_BUFFER_ADJ: u32 = 0; static mut GPU_ASID_LO: u8 = 0; static mut GPU_ASID_HI: u8 = 0; static mut SMMU_CURRENT_ASID: u8 = 0; static mut SMMU_PAGE_MAPPINGS: BTreeMap<u64, u64> = BTreeMap::new(); static mut SMMU_PAGE_MAPPING_VADDR: BTreeMap<u64, u32> = BTreeMap::new(); static mut SMMU_PAGE_MAPPING_ASID: BTreeMap<u64, u8> = BTreeMap::new(); static mut PTB_HOS_ASIDS: [u64; 0x80] = [0; 0x80]; static mut PTB_HTB_ASIDS: [u64; 0x80] = [0; 0x80]; static mut ASID_BUFFERS: [u64; 0x80] = [0; 0x80]; static mut ASID_BASES: [u32; 0x80] = [0; 0x80]; static mut SMMU_PAGE_ALLOCBITMAP: [u8; SMMU_NUM_PAGES/8] = [0; SMMU_NUM_PAGES/8]; static mut SMMU_LAST_FREED: u64 = 0; static mut SMMU_MIGHT_NEED_RETRANSLATE: bool = false; #[repr(align(0x1000))] struct SMMUPages([u32; 1024 * SMMU_NUM_PAGES]); static mut SMMU_PAGES: SMMUPages = SMMUPages([0; 1024 * SMMU_NUM_PAGES]); static mut SMMU_ACTIVE: AtomicBool = AtomicBool::new(false); static mut OLD_AHB_ARB: u32 = 0; pub fn smmu_init() { let ahb_arb_disable: MMIOReg = MMIOReg::new(AHB_ARBITRATION_DISABLE); unsafe { OLD_AHB_ARB = ahb_arb_disable.r32() | (bit!(1) | bit!(4) | bit!(6) | bit!(7) | bit!(18)); } /*unsafe { SMMU_PAGES = SMMUPages([0; 1024 * SMMU_NUM_PAGES]); SMMU_PAGE_ALLOCBITMAP = [0; SMMU_NUM_PAGES/8]; SMMU_CURRENT_ASID = 0; PTB_HOS_ASIDS = [0; 0x80]; PTB_HTB_ASIDS = [0; 0x80]; ASID_BASES = [0; 0x80]; ASID_BUFFERS = [0; 0x80]; SMMU_PAGE_MAPPINGS = BTreeMap::new(); }*/ // TODO actual init // Allow usbd regs to be arbitrated // (SMMU will still be locked out but there's a workaround) ahb_arb_disable.w32(0); let old_conf = smmu_readreg(MC_SMMU_PTC_CONFIG); smmu_writereg(MC_SMMU_PTC_CONFIG, old_conf & !bit!(29)); let old_conf2 = smmu_readreg(MC_SMMU_TLB_CONFIG); smmu_writereg(MC_SMMU_TLB_CONFIG, old_conf & !0x1F); } pub fn smmu_sleep() { let ahb_arb_disable: MMIOReg = MMIOReg::new(AHB_ARBITRATION_DISABLE); unsafe { ahb_arb_disable.w32(0x40062);} } pub fn smmu_active() -> bool { unsafe { SMMU_ACTIVE.load(Ordering::Relaxed) } } pub fn smmu_print_err() { let status = smmu_readreg(MC_ERR_STATUS); let addr = smmu_readreg(MC_ERR_ADR); smmu_writereg(MC_BASE, smmu_readreg(MC_BASE)); smmu_writereg(MC_BASE, 0); smmu_writereg(MC_BASE+4, 0); let err_id = status & 0xFF; let err_adr1 = (status >> 12) & 7; let err_rw = (status & bit!(16)) != 0; let err_security = (status & bit!(17)) != 0; let err_swap = (status & bit!(18)) != 0; let err_adr_hi = (status >> 20) & 3; let err_invalid_smmu_page_nonsecure = (status & bit!(25)) != 0; let err_invalid_smmu_page_writable = (status & bit!(26)) != 0; let err_invalid_smmu_page_readable = (status & bit!(27)) != 0; let err_type = (status >> 28) & 7; if err_type == 7 { return; } println!("({:08x}, {:08x}) ERR_ID {:x} ERR_ADR1 {:x} ERR_RW {} ERR_SECURITY {} ERR_SWAP {}", status, addr, err_id, err_adr1, err_rw, err_security, err_swap); println!("ERR_ADR_HI {:x} INVALID_SEC {} INVALID_WRITE {} INVALID_READ {} ERR_TYPE {:x}", err_adr_hi, err_invalid_smmu_page_nonsecure, err_invalid_smmu_page_writable, err_invalid_smmu_page_readable, err_type); } pub fn smmu_test() { /*let emem_cfg = smmu_readreg(MC_EMEM_CFG); let page_addr = 0xd0000000 as u64; let ptb_data_val = (((page_addr & 0x3FFFFFFFF)>>12) | bit!(29) | bit!(30) | bit!(31)) as u32; //smmu_writereg(MC_EMEM_CFG, emem_cfg & !bit!(31)); smmu_writereg(MC_SMMU_PTB_ASID, 0x06); smmu_writereg(MC_SMMU_PTB_DATA, ptb_data_val); smmu_writereg(MC_SMMU_PTC_FLUSH, 0x00); smmu_readreg(MC_SMMU_TLB_CONFIG); // flush smmu_writereg(MC_SMMU_TLB_FLUSH, 0x00); smmu_readreg(MC_SMMU_TLB_CONFIG); // flush //smmu_writereg(MC_EMEM_CFG, emem_cfg); smmu_print_err();*/ } pub fn smmu_get_se_buffer() -> u64 { unsafe { return SE_BUFFER; } } pub fn smmu_get_se_buffer_adj() -> u32 { unsafe { return SE_BUFFER_ADJ; } } pub fn smmu_get_sdmmc_buffer() -> u64 { unsafe { return SDMMC_BUFFER; }//ASID_BUFFERS[SDMMC_ASID]; } pub fn smmu_get_sdmmc_buffer_adj() -> u32 { unsafe { return SDMMC_BUFFER_ADJ; }//ASID_BASES[SDMMC_ASID]; } pub fn smmu_map_pages(hos: u64, hyp: u64, virt: u32, asid: u8) { unsafe { SMMU_PAGE_MAPPINGS.insert(hos, hyp); SMMU_PAGE_MAPPING_VADDR.insert(hos, virt); SMMU_PAGE_MAPPING_ASID.insert(hos, asid); } } pub fn smmu_unmap_page(hyp: u64) { let mut hos: u64 = 0; unsafe { for (key, val) in &SMMU_PAGE_MAPPINGS { if *val == hyp { hos = *key; break; } } if hos != 0 { SMMU_PAGE_MAPPINGS.remove(&hos); let vaddr = smmu_find_page_vaddr(hos); let asid = smmu_get_asid(hos); SMMU_PAGE_MAPPING_VADDR.remove(&hos); SMMU_PAGE_MAPPING_ASID.remove(&hos); } } } pub fn smmu_find_hyp_mapping_from_hos(hos: u64) -> u64 { unsafe { if let Some(hyp) = SMMU_PAGE_MAPPINGS.get(&hos) { return *hyp; } } return 0; } pub fn smmu_find_page_vaddr(hos: u64) -> u32 { unsafe { if let Some(val) = SMMU_PAGE_MAPPING_VADDR.get(&hos) { return *val; } } return 0; } pub fn smmu_get_asid(hos: u64) -> u8 { unsafe { if let Some(val) = SMMU_PAGE_MAPPING_ASID.get(&hos) { return *val; } } return 0; } pub fn smmu_find_hos_mapping_from_hyp(hyp: u64) -> u64 { let mut hos: u64 = 0; unsafe { for (key, val) in &SMMU_PAGE_MAPPINGS { if *val == hyp { hos = *key; break; } } return hos; } return 0; } pub fn smmu_freetable(smmu_tlb: u64, baseaddr: u32, level: i32) { for i in 0..(0x1000/4) { let curaddr = smmu_tlb + (i*4) as u64; let deviceaddr = baseaddr + (i * (if level == 0 { 0x400000 } else { 0x1000 })) as u32; let tblval = peek32(curaddr); if (tblval == 0) { continue; } //printf("freeing @ lv{} (asid {:02x}): {:016x}: {:08x}\n\r", level, SMMU_CURRENT_ASID, curaddr, tblval); let smmu_pa = ((tblval & 0x3fffff) as u64) << 12; poke32(curaddr, 0); dcache_flush(curaddr,0x4); //smmu_writereg(MC_SMMU_PTC_FLUSH_1, (curaddr >> 32) as u32); //smmu_writereg(MC_SMMU_PTC_FLUSH, ((curaddr & 0xFFFFFFF0) | 1) as u32); //smmu_readreg(0x70019010); if ((tblval & 0x10000000) != 0) // page table { //printf("freeing @ lv{} (asid {:02x}): lv{} page table {:016x}\n\r", level, SMMU_CURRENT_ASID, level+1, smmu_pa); smmu_freetable(smmu_pa, deviceaddr, level + 1); smmu_freepage(smmu_pa); smmu_unmap_page(smmu_pa); //unsafe { println_core!("smmu: ASID {:x} freed page for device vaddr {:x}", SMMU_CURRENT_ASID, deviceaddr); } } } } pub fn smmu_printtlb(smmu_tlb: u64, baseaddr: u32, level: i32, asid: u8, len: u64, is_kern: bool) -> (bool,u64) { unsafe { let mut str_indent = ""; if level == 1 { str_indent = " "; } else if level == 1 { str_indent = " "; } let level_inc = if level == 0 { 0x400000 } else { 0x1000 }; let mut scan_range = false; let mut last_pa = 0; let mut last_da = 0; let mut range_len = 0; let mut is_contiguous = true; let mut first_addr = 0; for i in 0..(len/4) { let atom_idx = (smmu_tlb & 0xFF0) / 4; let idx = (i+atom_idx); let is_last = (i == (len/4)-1); let curaddr = smmu_tlb + i*4; let deviceaddr = baseaddr + ((i+atom_idx) * level_inc) as u32; let tblval = peek32(curaddr); let mut smmu_pa = ((tblval & 0x3fffff) as u64) << 12; if is_kern { smmu_pa = ipaddr_to_paddr(smmu_pa); } let is_tbl = ((tblval & 0x10000000) != 0 && level <= 1); let is_unalloc = (tblval == 0); if scan_range && ((last_pa + level_inc) != smmu_pa || is_tbl || is_last || is_unalloc) && range_len != 1 { if range_len >= 2 { println_core!("{}...", str_indent); } println_core!("{}page: dev vaddr {:08x} -> {:09x} b {} {}", str_indent, last_da, last_pa, range_len, i); scan_range = false; is_contiguous = false; } last_pa = smmu_pa; last_da = deviceaddr; range_len += 1; if is_unalloc { is_contiguous = false; continue; } if scan_range { continue; } if is_tbl // page table { let res = smmu_printtlb(smmu_pa, deviceaddr, level + 1, asid, 0x1000, is_kern); if res.0 { println_core!("{}tbl: dev vaddr {:08x} -> {:09x} cont", str_indent, deviceaddr, res.1); } else { is_contiguous = false; println_core!("{}tbl: dev vaddr {:08x} -> {:09x}", str_indent, deviceaddr, smmu_pa); } } else { if is_contiguous && first_addr == 0 { first_addr = smmu_pa; } println_core!("{}page: dev vaddr {:08x} -> {:09x} a", str_indent, deviceaddr, smmu_pa); scan_range = true; range_len = 1; } } return (is_contiguous, first_addr); } } pub fn smmu_translatetlb(smmu_tlb: u64, kern_tlb: u64, baseaddr: u32, level: i32, va_match: u8, va: u32, asid: u8, len: u64) { unsafe { let mut changed = false; for i in 0..(len/4) { let atom_idx = (smmu_tlb & 0xFF0) / 4; let curaddr = smmu_tlb + i*4; let curaddr_kern = kern_tlb + i*4; let deviceaddr = baseaddr + ((i+atom_idx) * (if level == 0 { 0x400000 } else { 0x1000 })) as u32; let deviceaddr_next = baseaddr + ((i+atom_idx+1) * (if level == 0 { 0x400000 } else { 0x1000 })) as u32; let tblval_kern = peek32(curaddr_kern); let tblval = peek32(curaddr); if tblval_kern == 0 && tblval == 0 { poke32(curaddr, 0); //dcache_flush(curaddr,0x4); //smmu_readreg(0x70019010); //smmu_writereg(MC_SMMU_PTC_FLUSH_1, (curaddr >> 32) as u32); //smmu_writereg(MC_SMMU_PTC_FLUSH, ((curaddr & 0xFFFFFFF0) | 1) as u32); //smmu_readreg(0x70019010); changed = false; continue; } if level == 0 && va_match == 2 && deviceaddr == va { continue; } let smmu_ipa = ((tblval_kern & 0x3fffff) as u64) << 12; let smmu_pa = ipaddr_to_paddr(smmu_ipa); let smmu_htb_pa = ((tblval & 0x3fffff) as u64) << 12; if tblval_kern == 0 && (tblval & 0x10000000) != 0 { poke32(curaddr, 0); // write 0 first, in case SMMU is in use dcache_flush(curaddr,0x4); smmu_writereg(MC_SMMU_PTC_FLUSH_1, (curaddr >> 32) as u32); smmu_writereg(MC_SMMU_PTC_FLUSH, ((curaddr & 0xFFFFFFF0) | 1) as u32); //smmu_writereg(MC_SMMU_TLB_FLUSH, bit!(31) | ((asid as u32) << 24) as u32 | ((baseaddr >> 14) << 2) as u32 | 2); //smmu_writereg(MC_SMMU_TLB_FLUSH, bit!(31) | ((asid as u32) << 24) as u32 | ((deviceaddr >> 14) << 2) as u32 | 2); //smmu_freetable(smmu_htb_pa, deviceaddr, level + 1); if smmu_htb_pa != 0 { //smmu_freepage(smmu_htb_pa); //smmu_unmap_page(smmu_htb_pa); } changed = false; //println_core!("smmu: ASID {:x} freed page table for device vaddr {:x}", asid, deviceaddr); continue; } else if tblval_kern == 0 && (tblval & 0x10000000) == 0 { poke32(curaddr, 0); // write 0 first, in case SMMU is in use dcache_flush(curaddr,0x4); smmu_writereg(MC_SMMU_PTC_FLUSH_1, (curaddr >> 32) as u32); smmu_writereg(MC_SMMU_PTC_FLUSH, ((curaddr & 0xFFFFFFF0) | 3) as u32); changed = false; if smmu_htb_pa == 0 && (asid == GPU_ASID_LO || asid == GPU_ASID_HI) && (deviceaddr & 0xFFFF) == 0 { //println_core!("smmu: ASID {:x} freed page for device vaddr {:x}", asid, deviceaddr); } continue; } /*if smmu_pa >= 0xd0000000 && smmu_ipa < (0xd0000000+TOTAL_HTB_SIZE) { println_core!("smmu: overlap with hyp, ipa {:x} asid {:x}", smmu_ipa, SMMU_CURRENT_ASID); } if smmu_ipa != smmu_pa { println_core!("smmu: ASID {:x}, IPA {:x} doesn't match PA {:x}", SMMU_CURRENT_ASID, smmu_ipa, smmu_pa); }*/ if smmu_pa == 0 && smmu_ipa != 0 { println_core!("!! SMMU is mapping unavailable page {:x} !!", smmu_ipa); continue; } if (tblval_kern & !0x3fffff) != (tblval & !0x3fffff){ changed = true } if ((tblval_kern & 0x10000000) != 0 && level <= 1) // page table { let mut newpage = smmu_htb_pa; if newpage == 0 { //println_core!("smmu: ASID {:x} added page table for device vaddr {:x}", asid, deviceaddr); let check_exist = smmu_find_hyp_mapping_from_hos(smmu_pa); if check_exist != 0 { /*poke32(curaddr, 0); // write 0 first, in case SMMU is in use dcache_flush(curaddr,0x4); smmu_writereg(MC_SMMU_PTC_FLUSH_1, (curaddr >> 32) as u32); smmu_writereg(MC_SMMU_PTC_FLUSH, ((curaddr & 0xFFFFFFF0) | 1) as u32); //smmu_writereg(MC_SMMU_TLB_FLUSH, bit!(31) | ((asid as u32) << 24) as u32 | ((deviceaddr >> 14) << 2) as u32 | 2); smmu_readreg(0x70019010); //smmu_freetable(smmu_htb_pa, deviceaddr, level + 1); smmu_freepage(check_exist); smmu_unmap_page(check_exist); changed = true; println_core!("smmu: ASID {:x} freed page table for device vaddr {:x}", asid, deviceaddr);*/ //println_core!("smmu: ASID {:x} reused page table for device vaddr {:x}", asid, deviceaddr); smmu_unmap_page(check_exist); newpage = check_exist; dcache_flush(newpage,0x1000); changed = true; } else { newpage = smmu_allocpage(); if (newpage == 0) { panic!("COULDN'T ALLOC SMMU PAGE!"); } changed = true; } smmu_map_pages(smmu_pa, newpage, deviceaddr, asid); } if va_match != 4 { smmu_translatetlb(newpage, smmu_pa, deviceaddr, level + 1, 0, 0, asid, 0x1000); } if newpage != smmu_htb_pa || (tblval_kern & !0x3fffff) != (tblval & !0x3fffff) { poke32(curaddr, (tblval_kern & !0x3fffff) | (newpage >> 12) as u32); dcache_flush(curaddr,0x4); changed = true; if va_match != 4 { smmu_writereg(MC_SMMU_TLB_FLUSH, bit!(31) | ((asid as u32) << 24) as u32 | ((deviceaddr >> 14) << 2) as u32 | 2); } smmu_writereg(MC_SMMU_TLB_FLUSH, bit!(31) | ((asid as u32) << 24) as u32 | ((baseaddr >> 14) << 2) as u32 | 2); } } else { if (SMMU_CURRENT_ASID == 5) { if (SE_BUFFER == 0) { println!("(core {}) SE buffer: IPADDR {:016x} -> PADDR {:016x}, SMMU addr {:08x}", get_core(), smmu_ipa, smmu_pa, deviceaddr); SE_BUFFER = smmu_pa; SE_BUFFER_ADJ = deviceaddr; } } else if (SMMU_CURRENT_ASID == 6) { if (SDMMC_BUFFER == 0) { println!("(core {}) SDMMC buffer: IPADDR {:016x} -> PADDR {:016x}, SMMU addr {:08x}", get_core(), smmu_ipa, smmu_pa, deviceaddr); SDMMC_BUFFER = smmu_pa; SDMMC_BUFFER_ADJ = deviceaddr; } } else if (SMMU_CURRENT_ASID == DC_ASID) { if (DC_BUFFER == 0) { println!("(core {}) DC buffer: IPADDR {:016x} -> PADDR {:016x}, SMMU addr {:08x}", get_core(), smmu_ipa, smmu_pa, deviceaddr); DC_BUFFER = smmu_pa; DC_BUFFER_ADJ = deviceaddr; } } else { if (ASID_BUFFERS[SMMU_CURRENT_ASID as usize] == 0) { println!("(core {}) ASID {} buffer: IPADDR {:016x} -> PADDR {:016x}, SMMU addr {:08x}", get_core(), SMMU_CURRENT_ASID, smmu_ipa, smmu_pa, deviceaddr); ASID_BUFFERS[SMMU_CURRENT_ASID as usize] = 1;//ASID_BUFFERS; ASID_BASES[SMMU_CURRENT_ASID as usize] = deviceaddr; } } if smmu_htb_pa == 0 && (asid == GPU_ASID_LO || asid == GPU_ASID_HI) && (deviceaddr & 0xFFFF) == 0 { //println_core!("smmu: ASID {:x} added page for device vaddr {:x}", asid, deviceaddr); } if smmu_pa != smmu_htb_pa || (tblval_kern & !0x3fffff) != (tblval & !0x3fffff) { poke32(curaddr, (tblval_kern & !0x3fffff) | (smmu_pa >> 12) as u32); dcache_flush(curaddr,0x4); changed = true; } } if changed { //smmu_readreg(0x70019010); smmu_writereg(MC_SMMU_PTC_FLUSH_1, (curaddr >> 32) as u32); smmu_writereg(MC_SMMU_PTC_FLUSH, ((curaddr & 0xFFFFFFF0) | 0) as u32); /*if level == 0 { smmu_writereg(MC_SMMU_TLB_FLUSH, bit!(31) | ((asid as u32) << 24) as u32 | ((deviceaddr >> 14) << 2) as u32 | 1); smmu_writereg(MC_SMMU_TLB_FLUSH, bit!(31) | ((asid as u32) << 24) as u32 | ((baseaddr >> 14) << 2) as u32 | 1); }*/ //smmu_readreg(0x70019010); changed = false; } } } } pub fn smmu_match_asid(addr: u64) -> i32 { unsafe { for i in 0..0x80 { if (PTB_HOS_ASIDS[i] == addr) { return i as i32; } } return -1; } } pub fn smmu_retranslate_asid(asid: u8, va_match: u8, va: u32) { unsafe { let smmu_hos = PTB_HOS_ASIDS[asid as usize]; let smmu_hyp = PTB_HTB_ASIDS[asid as usize]; let level = 0; if smmu_hos == 0 || smmu_hyp == 0 { return; } //smmu_freetable(smmu_hyp, 0); //memcpy32(smmu_hyp, smmu_hos, 0x1000); //printf("(core {}) retranslate ASID {:x} ({:016x}, {:016x} {:08x})\n\r", get_core(), flushing_asid, flushing_addr, smmu_hyp, val); smmu_translatetlb(smmu_hyp, smmu_hos, 0, level, va_match, va, asid, 0x1000); // TODO invalidate only what's needed for PTC? /*smmu_writereg(MC_SMMU_PTC_FLUSH_1, 0); smmu_writereg(MC_SMMU_PTC_FLUSH, 0); smmu_writereg(MC_SMMU_TLB_FLUSH, bit!(31) | ((asid as u32) << 24) as u32 | 0); smmu_readreg(0x70019010);*/ } } pub fn smmu_flush_asid(asid: u8) { unsafe { let smmu_hos = PTB_HOS_ASIDS[asid as usize]; let smmu_hyp = PTB_HTB_ASIDS[asid as usize]; let level = 0; if smmu_hos == 0 || smmu_hyp == 0 { return; } /*smmu_writereg(MC_SMMU_PTC_FLUSH_1, 0); smmu_writereg(MC_SMMU_PTC_FLUSH, 0); smmu_writereg(MC_SMMU_TLB_FLUSH, 0); smmu_readreg(0x70019010);*/ } } pub fn smmu_retranslate_and_flush_all() { unsafe { for i in 0..128 { smmu_retranslate_asid(i, 0, 0); smmu_flush_asid(i); } /*smmu_writereg(MC_SMMU_PTC_FLUSH_1, 0); smmu_writereg(MC_SMMU_PTC_FLUSH, 0); smmu_writereg(MC_SMMU_TLB_FLUSH, 0); smmu_readreg(0x70019010);*/ } } pub fn smmu_retranslate_all() { unsafe { for i in 0..128 { smmu_retranslate_asid(i, 0, 0); } /*smmu_writereg(MC_SMMU_PTC_FLUSH_1, 0); smmu_writereg(MC_SMMU_PTC_FLUSH, 0); smmu_writereg(MC_SMMU_TLB_FLUSH, 0); smmu_readreg(0x70019010);*/ } } pub fn smmu_handle_ptc_flush() { unsafe { let mut val = LAST_MC_SMMU_PTC_FLUSH; let mut flushing_addr = ((LAST_MC_SMMU_PTC_FLUSH_HI as u64) << 32) | (val & 0xFFFFF000) as u64; let flush_type = val & bit!(0); // 0 = ALL, 1 = ADR let atom = (val & 0xFF0) as u64; SMMU_MIGHT_NEED_RETRANSLATE = true; flushing_addr = ipaddr_to_paddr(flushing_addr); if (smmu_get_asid(flushing_addr) == GPU_ASID_LO || smmu_get_asid(flushing_addr) == GPU_ASID_HI) && (flush_type == 0 || atom == 0) { //println_core!("smmu: ASID {:x} PTC flush IPA {:08x}, type = {}", smmu_get_asid(flushing_addr), val, flush_type); } if flush_type == 0 { smmu_retranslate_all(); val = (flushing_addr & 0xFFFFF000) as u32 | (val & 0xFFF); smmu_writereg(MC_SMMU_PTC_FLUSH_1, LAST_MC_SMMU_PTC_FLUSH_HI); smmu_writereg(MC_SMMU_PTC_FLUSH, val); return; } //TODO: check for UAF? let mut matched_page = smmu_find_hyp_mapping_from_hos(flushing_addr); if (matched_page == 0) { println_core!("FAILED TO MATCH SMMU PAGE {:x}!", flushing_addr); return; //smmu_retranslate_all(); //matched_page = smmu_find_hyp_mapping_from_hos(flushing_addr); } let mut flushing_asid = smmu_match_asid(flushing_addr); let mut level = 0; if (flushing_asid == -1) { //println!("(core {}) FAILED TO IDENTIFY SMMU ASID! FALLBACK... {:x}", get_core(), flushing_addr); //flushing_asid = SMMU_CURRENT_ASID as i32; level = 1; } let smmu_hos = flushing_addr; let mut smmu_hyp = matched_page; // TODO? //println_core!("----- kern printout -----"); //smmu_printtlb(smmu_hos, smmu_find_page_vaddr(smmu_hos), level, SMMU_CURRENT_ASID, 0x1000, true); //println_core!("-------------------------"); smmu_translatetlb(smmu_hyp | atom, smmu_hos | atom, smmu_find_page_vaddr(smmu_hos), level, 4, 0, smmu_get_asid(flushing_addr), 0x10); //smmu_translatetlb(smmu_hyp, smmu_hos, smmu_find_page_vaddr(smmu_hos), level, 4, 0, smmu_get_asid(flushing_addr), 0x1000); //println_core!("----- htb2 printout -----"); //smmu_printtlb(smmu_hyp, smmu_find_page_vaddr(smmu_hos), level, SMMU_CURRENT_ASID, 0x1000, false); //println_core!("-------------------------"); smmu_hyp = smmu_find_hyp_mapping_from_hos(flushing_addr); val = (smmu_hyp & 0xFFFFF000) as u32 | (val & 0xFFF); //val = (flushing_addr & 0xFFFFF000) | (val & 0xFFF); smmu_writereg(MC_SMMU_PTC_FLUSH_1, LAST_MC_SMMU_PTC_FLUSH_HI); smmu_writereg(MC_SMMU_PTC_FLUSH, val); } } pub fn smmu_handle_tlb_flush() { unsafe { let mut val = LAST_MC_SMMU_TLB_FLUSH; let va = ((val >> 2) & 0x3FFFF) << 14; let asid_flush = ((val >> 24) & 0x7F) as u8; let should_asid_match = (val & bit!(31)) != 0; let va_match = (val & 3) as u8; // 0 = ALL, 2 = SECTION, 3 = GROUP if va_match == 0 { if !should_asid_match { smmu_retranslate_all(); } else { smmu_retranslate_asid(asid_flush, 0, 0); } } else if va_match == 2 //&& !SMMU_MIGHT_NEED_RETRANSLATE { // TODO can this be done simpler? if !should_asid_match { smmu_retranslate_all(); } else { smmu_retranslate_asid(asid_flush, va_match, va); } SMMU_MIGHT_NEED_RETRANSLATE = false; } else if va_match == 3 || va_match == 1 //&& !SMMU_MIGHT_NEED_RETRANSLATE { // TODO can this be done simpler? if !should_asid_match { smmu_retranslate_all(); } else { smmu_retranslate_asid(asid_flush, va_match, va); } SMMU_MIGHT_NEED_RETRANSLATE = false; } let mut flushing_tlb = PTB_HTB_ASIDS[SMMU_CURRENT_ASID as usize]; if (asid_flush == GPU_ASID_LO || asid_flush == GPU_ASID_HI) || !should_asid_match || ((asid_flush == GPU_ASID_LO || asid_flush == GPU_ASID_HI) && va_match == 0) { //println_core!("smmu: buffer flush VA {:08x} for ASID {:02x}, match = {}, match ASID = {}", va, asid_flush, va_match, should_asid_match); } smmu_writereg(MC_SMMU_TLB_FLUSH, val); } } pub fn smmu_handle_rwreg(ctx: &mut [u64]) -> bool { unsafe{ let reg = (ctx[1] & 0xFFFFFFFF) as u64; let is_write = (ctx[2] == 0xFFFFFFFF); let mut val = (ctx[3] & 0xFFFFFFFF) as u32; SMMU_ACTIVE.store(true, Ordering::Relaxed); if reg != 0x70019054 && reg != 0x700199b8 && reg != 0x70019034 { //println_core!("smmu: rwreg {:08x} {} {:08x}", reg, if (is_write) { "<-" } else { "->" }, val); } if (!is_write) { if (reg == MC_SMMU_PTB_DATA) { val = smmu_readreg(reg); let smmu_hyp = ((val & 0x3fffff) << 12) as u64; let smmu_pa = smmu_find_hos_mapping_from_hyp(smmu_hyp); let smmu_ipa = paddr_to_ipaddr(smmu_pa); val = (val & !0x3fffff) | (smmu_ipa >> 12) as u32; ctx[0] = 0; ctx[1] = val as u64; SMMU_ACTIVE.store(false, Ordering::Relaxed); return true; } else if (reg == MC_SMMU_CONFIG) { if PTB_SET { let hos = PTB_HOS_ASIDS[SMMU_CURRENT_ASID as usize]; let hyp = PTB_HTB_ASIDS[SMMU_CURRENT_ASID as usize]; //println_core!("----- kern printout -----"); //smmu_printtlb(hos, 0, 0, SMMU_CURRENT_ASID, 0x1000, true); //println_core!("-------------------------"); smmu_translatetlb(hyp, hos, 0, 0, 0, 0, SMMU_CURRENT_ASID, 0x1000); //println_core!("----- htb2 printout -----"); //smmu_printtlb(hyp, 0, 0, SMMU_CURRENT_ASID, 0x1000, false); //println_core!("-------------------------"); PTB_SET = false; } if TLB_FLUSH_SET { //println_core!("tlb flush"); smmu_handle_tlb_flush(); TLB_FLUSH_SET = false; } if PTC_FLUSH_SET { //println_core!("ptc flush"); smmu_handle_ptc_flush(); PTC_FLUSH_SET = false; } /*if GPU_ASID_LO != 0 && PTB_HOS_ASIDS[GPU_ASID_LO as usize] != 0 { smmu_retranslate_asid(GPU_ASID_LO, 0, 0); smmu_retranslate_asid(GPU_ASID_HI, 0, 0); smmu_readreg(0x70019010); smmu_writereg(MC_SMMU_PTC_FLUSH_1, 0); smmu_writereg(MC_SMMU_PTC_FLUSH, 0); smmu_writereg(MC_SMMU_TLB_FLUSH, 0); smmu_readreg(0x70019010); }*/ } SMMU_ACTIVE.store(false, Ordering::Relaxed); return false; } //return false; if (reg == MC_SMMU_PTB_DATA) { let smmu_ipa = ((val & 0x3fffff) << 12) as u64; let smmu_pa = ipaddr_to_paddr(smmu_ipa); PTB_HOS_ASIDS[SMMU_CURRENT_ASID as usize] = smmu_pa; let mut matched_page = smmu_find_hyp_mapping_from_hos(smmu_pa); /*if matched_page != 0 && PTB_HTB_ASIDS[SMMU_CURRENT_ASID as usize] != 0 { let old_page = PTB_HTB_ASIDS[SMMU_CURRENT_ASID as usize]; smmu_freepage(old_page); smmu_unmap_page(old_page); matched_page = 0; }*/ if (matched_page == 0) { PTB_HTB_ASIDS[SMMU_CURRENT_ASID as usize] = smmu_allocpage(); smmu_map_pages(smmu_pa, PTB_HTB_ASIDS[SMMU_CURRENT_ASID as usize], 0, SMMU_CURRENT_ASID); matched_page = PTB_HTB_ASIDS[SMMU_CURRENT_ASID as usize]; } PTB_SET = true; println_core!("smmu: PTB_DATA changed for ASID {:x}! -> {:x}", SMMU_CURRENT_ASID, smmu_pa); val = (val & !0x3fffff) | (matched_page >> 12) as u32; //printf("core {}: translating IPA {:016x} -> PA {:016x}\n\r", get_core(), smmu_ipa, smmu_pa); } else if (reg == MC_SMMU_PTC_FLUSH && (val|LAST_MC_SMMU_PTC_FLUSH_HI) != 0) // PTC_FLUSH { if PTC_FLUSH_SET { //println_core!("ptc flush"); smmu_handle_ptc_flush(); PTC_FLUSH_SET = false; } LAST_MC_SMMU_PTC_FLUSH = val; PTC_FLUSH_SET = true; //println_core!("ptc flush {:x}", val); ctx[0] = 0; ctx[1] = 0; SMMU_ACTIVE.store(false, Ordering::Relaxed); return true; } else if (reg == MC_SMMU_TLB_FLUSH) // lookaside buffer flush { if TLB_FLUSH_SET { //println_core!("tlb flush"); smmu_handle_tlb_flush(); TLB_FLUSH_SET = false; } LAST_MC_SMMU_TLB_FLUSH = val; TLB_FLUSH_SET = true; ctx[0] = 0; ctx[1] = 0; SMMU_ACTIVE.store(false, Ordering::Relaxed); return true; } else if (reg == MC_SMMU_PTB_ASID) { SMMU_CURRENT_ASID = (val & 0x7F) as u8; //println!("(core {}) set ASID {:x}", get_core(), SMMU_CURRENT_ASID); } else if (reg == MC_SMMU_PTC_FLUSH_1) { //PTC_FLUSH_SET = true; LAST_MC_SMMU_PTC_FLUSH_HI = val; //println_core!("ptc flush hi {:x}", val); ctx[0] = 0; ctx[1] = 0; SMMU_ACTIVE.store(false, Ordering::Relaxed); return true; //println!("(core {}) ASID {:x} ptbl cache flush addr upper", get_core(), SMMU_CURRENT_ASID); } else if (reg == MC_SMMU_CONFIG) { //smmu_flush_tlb(PTB_HTB_ASIDS[SMMU_CURRENT_ASID], 0, 0, SMMU_CURRENT_ASID); } else if (reg == MC_SMMU_TLB_CONFIG) { val &= !0x1F; } else if (reg == MC_SMMU_PTC_CONFIG) { val &= !bit!(29); } else if (reg == MC_SMMU_DC_ASID) { println!("DC ASID: {:08x}", val); DC_ASID = (val & 0x7F) as u8; //smmu_print_err(); } else if (reg == MC_SMMU_SDMMC1A_ASID) { println!("SDMMC1A ASID: {:08x}", val); //smmu_print_err(); } else if (reg == MC_SMMU_SDMMC2A_ASID) { println!("SDMMC2A ASID: {:08x}", val); SDMMC_ASID = (val & 0x7F) as u8; //smmu_print_err(); } else if (reg == MC_SMMU_SDMMC3A_ASID) { println!("SDMMC3A ASID: {:08x}", val); //smmu_print_err(); } else if (reg == MC_SMMU_SDMMC4A_ASID) { println!("SDMMC4A ASID: {:08x}", val); //smmu_print_err(); } else if (reg == MC_SMMU_NVENC_ASID) { println!("NVENC ASID: {:08x}", val); } else if (reg == MC_SMMU_NV_ASID) { println!("NV ASID: {:08x}", val); } else if (reg == MC_SMMU_NV2_ASID) { println!("NV2 ASID: {:08x}", val); } else if (reg == MC_SMMU_VI_ASID) { println!("VI ASID: {:08x}", val); } else if (reg == MC_SMMU_TSEC_ASID) { println!("TSEC ASID: {:08x}", val); } else if (reg == MC_SMMU_GPU_ASID) { println!("GPU ASID: {:08x}", val); } else if (reg == MC_SMMU_GPUB_ASID) { println!("GPUB ASID: {:08x}", val); GPU_ASID_LO = (val & 0xFF) as u8; GPU_ASID_HI = ((val >> 8) & 0xFF) as u8; } ctx[0] = smmu_writereg(reg, (val & 0xFFFFFFFF) as u32) as u64; ctx[1] = 0; SMMU_ACTIVE.store(false, Ordering::Relaxed); return true; } } pub fn smmu_freepage(page: u64) { unsafe { let pages_ptr = to_u64ptr!(SMMU_PAGES.0.as_mut_ptr()); let idx = ((page - pages_ptr) / 0x1000) as usize; let bit = (idx & 0x7) as u8; SMMU_PAGE_ALLOCBITMAP[idx>>3] &= !bit!(bit); smmu_unmap_page(page); SMMU_LAST_FREED = 0;//page; /*for i in 0..(0x1000/4) { let curaddr = page + (i*4); poke32(curaddr, 0); dcache_flush(curaddr,0x4); smmu_writereg(MC_SMMU_PTC_FLUSH_1, (curaddr >> 32) as u32); smmu_writereg(MC_SMMU_PTC_FLUSH, ((curaddr & 0xFFFFFFF0) | 1) as u32); smmu_readreg(0x70019010); }*/ } } pub fn smmu_allocpage() -> u64 { unsafe { if SMMU_LAST_FREED != 0 { let page = SMMU_LAST_FREED; SMMU_LAST_FREED = 0; return page; } let pages_ptr = to_u64ptr!(SMMU_PAGES.0.as_mut_ptr()); for i in 0..(SMMU_NUM_PAGES/8) { let bits = SMMU_PAGE_ALLOCBITMAP[i]; if (bits == 0xFF) { continue; } let mut bit = 0xFF; for j in 0..8 { if ((bits & bit!(j)) != 0) { continue; } bit = j; break; } if (bit == 0xFF) { continue; } SMMU_PAGE_ALLOCBITMAP[i] |= bit!(bit); let offs = ((i*8)+bit)*0x1000; let page = (pages_ptr + offs as u64); memset32(page, 0, 0x1000); dcache_flush(page,0x1000); return page; } println_core!("!! Exhausted SMMU pages !!"); return 0; } }
33.658621
213
0.521463
22c31dae756f8b0820cadd6f6a28afc40c3ede7c
2,352
// Copyright 2020-2021 The Datafuse Authors. // // SPDX-License-Identifier: Apache-2.0. use std::collections::hash_map::DefaultHasher; use std::hash::Hash; use std::hash::Hasher; use crate::meta_service::Node; use crate::meta_service::NodeId; use crate::meta_service::Slot; /// IPlacement defines the behavior of an algo to assign file to nodes. /// An placement algo considers the replication config, such as number of copies, /// and workload balancing etc. /// /// A placement algo is a two-level mapping: /// The first is about how to assign files(identified by keys) to a virtual bucket(AKA slot), /// and the second is about how to assign a slot to nodes. /// /// Data migration should be impl on only the second level, in which way only a small piece of metadata /// will be modified when repairing a damaged server or when extending the cluster. /// /// A default consistent-hash like impl is provided for most cases. /// With this algo user only need to impl two methods: get_slots() and get_node(). pub trait Placement { /// Returns the Node-s that are responsible to store a copy of a file. fn nodes_to_store_key(&self, key: &str) -> Vec<Node> { let slot_idx = self.slot_index_for_key(key); let slot = self.get_slot(slot_idx); slot.node_ids .iter() .map(|nid| self.get_node(nid).unwrap()) .collect() } /// Returns the slot index to store a file. fn slot_index_for_key(&self, key: &str) -> u64 { // TODO use consistent hash if need to extend cluster. let mut hasher = DefaultHasher::new(); key.hash(&mut hasher); let hsh = hasher.finish(); hsh % self.get_slots().len() as u64 } fn get_slot(&self, slot_idx: u64) -> &Slot { &self.get_slots()[slot_idx as usize] } fn get_slots(&self) -> &[Slot]; fn get_node(&self, node_id: &NodeId) -> Option<Node>; } /// Evenly chooses `n` elements from `m` elements pub fn rand_n_from_m(m: usize, n: usize) -> anyhow::Result<Vec<usize>> { if m < n { return Err(anyhow::anyhow!("m={} must >= n={}", m, n)); } let mut chosen = Vec::with_capacity(n); let mut need = n; for i in 0..m { if rand::random::<usize>() % (m - i) < need { chosen.push(i); need -= 1; } } Ok(chosen) }
31.783784
103
0.632228
fe03693c5d03c99f28ca33be959d09511a2679cb
4,295
#![allow(non_snake_case, non_upper_case_globals)] #![allow(non_camel_case_types)] //! Window watchdog //! //! Used by: stm32l100, stm32l151, stm32l162 use crate::RWRegister; #[cfg(not(feature = "nosync"))] use core::marker::PhantomData; /// Control register pub mod CR { /// Activation bit pub mod WDGA { /// Offset (7 bits) pub const offset: u32 = 7; /// Mask (1 bit: 1 << 7) pub const mask: u32 = 1 << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values pub mod RW { /// 0b0: Watchdog disabled pub const Disabled: u32 = 0b0; /// 0b1: Watchdog enabled pub const Enabled: u32 = 0b1; } } /// 7-bit counter (MSB to LSB) pub mod T { /// Offset (0 bits) pub const offset: u32 = 0; /// Mask (7 bits: 0x7f << 0) pub const mask: u32 = 0x7f << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values (empty) pub mod RW {} } } /// Configuration register pub mod CFR { /// Early wakeup interrupt pub mod EWI { /// Offset (9 bits) pub const offset: u32 = 9; /// Mask (1 bit: 1 << 9) pub const mask: u32 = 1 << offset; /// Read-only values (empty) pub mod R {} /// Write-only values pub mod W { /// 0b1: interrupt occurs whenever the counter reaches the value 0x40 pub const Enable: u32 = 0b1; } /// Read-write values (empty) pub mod RW {} } /// 7-bit window value pub mod W { /// Offset (0 bits) pub const offset: u32 = 0; /// Mask (7 bits: 0x7f << 0) pub const mask: u32 = 0x7f << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values (empty) pub mod RW {} } /// Timer base pub mod WDGTB { /// Offset (7 bits) pub const offset: u32 = 7; /// Mask (2 bits: 0b11 << 7) pub const mask: u32 = 0b11 << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values pub mod RW { /// 0b00: Counter clock (PCLK1 div 4096) div 1 pub const Div1: u32 = 0b00; /// 0b01: Counter clock (PCLK1 div 4096) div 2 pub const Div2: u32 = 0b01; /// 0b10: Counter clock (PCLK1 div 4096) div 4 pub const Div4: u32 = 0b10; /// 0b11: Counter clock (PCLK1 div 4096) div 8 pub const Div8: u32 = 0b11; } } } /// SR pub mod SR { /// EWIF pub mod EWIF { /// Offset (0 bits) pub const offset: u32 = 0; /// Mask (1 bit: 1 << 0) pub const mask: u32 = 1 << offset; /// Read-only values pub mod R { /// 0b1: The EWI Interrupt Service Routine has been triggered pub const Pending: u32 = 0b1; /// 0b0: The EWI Interrupt Service Routine has been serviced pub const Finished: u32 = 0b0; } /// Write-only values pub mod W { /// 0b0: The EWI Interrupt Service Routine has been serviced pub const Finished: u32 = 0b0; } /// Read-write values (empty) pub mod RW {} } } #[repr(C)] pub struct RegisterBlock { /// Control register pub CR: RWRegister<u32>, /// Configuration register pub CFR: RWRegister<u32>, /// SR pub SR: RWRegister<u32>, } pub struct ResetValues { pub CR: u32, pub CFR: u32, pub SR: u32, } #[cfg(not(feature = "nosync"))] pub struct Instance { pub(crate) addr: u32, pub(crate) _marker: PhantomData<*const RegisterBlock>, } #[cfg(not(feature = "nosync"))] impl ::core::ops::Deref for Instance { type Target = RegisterBlock; #[inline(always)] fn deref(&self) -> &RegisterBlock { unsafe { &*(self.addr as *const _) } } } #[cfg(feature = "rtic")] unsafe impl Send for Instance {}
24.97093
81
0.514785
8f84021017bf0339a5e3522e9282f74f529d509d
454
#![no_std] use embedded_hal as hal; pub use nrf9160_pac as pac; pub use nrf52_hal_common::*; pub mod prelude { pub use crate::hal::prelude::*; pub use nrf52_hal_common::prelude::*; pub use crate::time::U32Ext; } pub use crate::clocks::Clocks; pub use crate::delay::Delay; pub use crate::rtc::Rtc; pub use crate::saadc::Saadc; pub use crate::spim::Spim; pub use crate::timer::Timer; pub use crate::twim::Twim; pub use crate::uarte::Uarte;
20.636364
41
0.696035
fb318800b3fc15bb271cdce8f4cf5e44f0737d08
9,844
#[doc = "Reader of register CS3"] pub type R = crate::R<u32, super::CS3>; #[doc = "Writer for register CS3"] pub type W = crate::W<u32, super::CS3>; #[doc = "Register CS3 `reset()`'s with value 0"] impl crate::ResetValue for super::CS3 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TIME_STAMP`"] pub type TIME_STAMP_R = crate::R<u16, u16>; #[doc = "Write proxy for field `TIME_STAMP`"] pub struct TIME_STAMP_W<'a> { w: &'a mut W, } impl<'a> TIME_STAMP_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } #[doc = "Reader of field `DLC`"] pub type DLC_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DLC`"] pub struct DLC_W<'a> { w: &'a mut W, } impl<'a> DLC_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16); self.w } } #[doc = "Reader of field `RTR`"] pub type RTR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RTR`"] pub struct RTR_W<'a> { w: &'a mut W, } impl<'a> RTR_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 `IDE`"] pub type IDE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `IDE`"] pub struct IDE_W<'a> { w: &'a mut W, } impl<'a> IDE_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 `SRR`"] pub type SRR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SRR`"] pub struct SRR_W<'a> { w: &'a mut W, } impl<'a> SRR_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 `CODE`"] pub type CODE_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CODE`"] pub struct CODE_W<'a> { w: &'a mut W, } impl<'a> CODE_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 24)) | (((value as u32) & 0x0f) << 24); self.w } } #[doc = "Reader of field `ESI`"] pub type ESI_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ESI`"] pub struct ESI_W<'a> { w: &'a mut W, } impl<'a> ESI_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 `BRS`"] pub type BRS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `BRS`"] pub struct BRS_W<'a> { w: &'a mut W, } impl<'a> BRS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `EDL`"] pub type EDL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `EDL`"] pub struct EDL_W<'a> { w: &'a mut W, } impl<'a> EDL_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 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bits 0:15 - Free-Running Counter Time stamp. This 16-bit field is a copy of the Free-Running Timer, captured for Tx and Rx frames at the time when the beginning of the Identifier field appears on the CAN bus."] #[inline(always)] pub fn time_stamp(&self) -> TIME_STAMP_R { TIME_STAMP_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:19 - Length of the data to be stored/transmitted."] #[inline(always)] pub fn dlc(&self) -> DLC_R { DLC_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bit 20 - Remote Transmission Request. One/zero for remote/data frame."] #[inline(always)] pub fn rtr(&self) -> RTR_R { RTR_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - ID Extended. One/zero for extended/standard format frame."] #[inline(always)] pub fn ide(&self) -> IDE_R { IDE_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 22 - Substitute Remote Request. Contains a fixed recessive bit."] #[inline(always)] pub fn srr(&self) -> SRR_R { SRR_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bits 24:27 - Message Buffer Code. This 4-bit field can be accessed (read or write) by the CPU and by the FlexCAN module itself, as part of the message buffer matching and arbitration process."] #[inline(always)] pub fn code(&self) -> CODE_R { CODE_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bit 29 - Error State Indicator. This bit indicates if the transmitting node is error active or error passive."] #[inline(always)] pub fn esi(&self) -> ESI_R { ESI_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - Bit Rate Switch. This bit defines whether the bit rate is switched inside a CAN FD format frame."] #[inline(always)] pub fn brs(&self) -> BRS_R { BRS_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - Extended Data Length. This bit distinguishes between CAN format and CAN FD format frames. The EDL bit must not be set for Message Buffers configured to RANSWER with code field 0b1010."] #[inline(always)] pub fn edl(&self) -> EDL_R { EDL_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bits 0:15 - Free-Running Counter Time stamp. This 16-bit field is a copy of the Free-Running Timer, captured for Tx and Rx frames at the time when the beginning of the Identifier field appears on the CAN bus."] #[inline(always)] pub fn time_stamp(&mut self) -> TIME_STAMP_W { TIME_STAMP_W { w: self } } #[doc = "Bits 16:19 - Length of the data to be stored/transmitted."] #[inline(always)] pub fn dlc(&mut self) -> DLC_W { DLC_W { w: self } } #[doc = "Bit 20 - Remote Transmission Request. One/zero for remote/data frame."] #[inline(always)] pub fn rtr(&mut self) -> RTR_W { RTR_W { w: self } } #[doc = "Bit 21 - ID Extended. One/zero for extended/standard format frame."] #[inline(always)] pub fn ide(&mut self) -> IDE_W { IDE_W { w: self } } #[doc = "Bit 22 - Substitute Remote Request. Contains a fixed recessive bit."] #[inline(always)] pub fn srr(&mut self) -> SRR_W { SRR_W { w: self } } #[doc = "Bits 24:27 - Message Buffer Code. This 4-bit field can be accessed (read or write) by the CPU and by the FlexCAN module itself, as part of the message buffer matching and arbitration process."] #[inline(always)] pub fn code(&mut self) -> CODE_W { CODE_W { w: self } } #[doc = "Bit 29 - Error State Indicator. This bit indicates if the transmitting node is error active or error passive."] #[inline(always)] pub fn esi(&mut self) -> ESI_W { ESI_W { w: self } } #[doc = "Bit 30 - Bit Rate Switch. This bit defines whether the bit rate is switched inside a CAN FD format frame."] #[inline(always)] pub fn brs(&mut self) -> BRS_W { BRS_W { w: self } } #[doc = "Bit 31 - Extended Data Length. This bit distinguishes between CAN format and CAN FD format frames. The EDL bit must not be set for Message Buffers configured to RANSWER with code field 0b1010."] #[inline(always)] pub fn edl(&mut self) -> EDL_W { EDL_W { w: self } } }
33.59727
223
0.567351
29f5be1d6cd1cf8ba2b027e05567f761a7183cd6
3,710
//! A collection of extension traits for types that //! implement TryInto<U, Error=FieldViolation> //! //! Allows associating field context with the generated errors //! as they propagate up the struct topology use generated_types::google::FieldViolation; use std::convert::TryInto; /// An extension trait that adds the method `scope` to any type /// implementing `TryInto<U, Error = FieldViolation>` pub(crate) trait FromField<T> { fn scope(self, field: impl Into<String>) -> Result<T, FieldViolation>; } impl<T, U> FromField<U> for T where T: TryInto<U, Error = FieldViolation>, { /// Try to convert type using TryInto calling `FieldViolation::scope` /// on any returned error fn scope(self, field: impl Into<String>) -> Result<U, FieldViolation> { self.try_into().map_err(|e| e.scope(field)) } } /// An extension trait that adds the methods `optional` and `required` to any /// Option containing a type implementing `TryInto<U, Error = FieldViolation>` pub trait FromFieldOpt<T> { /// Try to convert inner type, if any, using TryInto calling /// `FieldViolation::scope` on any error encountered /// /// Returns None if empty fn optional(self, field: impl Into<String>) -> Result<Option<T>, FieldViolation>; /// Try to convert inner type, using TryInto calling `FieldViolation::scope` /// on any error encountered /// /// Returns an error if empty fn required(self, field: impl Into<String>) -> Result<T, FieldViolation>; } impl<T, U> FromFieldOpt<U> for Option<T> where T: TryInto<U, Error = FieldViolation>, { fn optional(self, field: impl Into<String>) -> Result<Option<U>, FieldViolation> { self.map(|t| t.scope(field)).transpose() } fn required(self, field: impl Into<String>) -> Result<U, FieldViolation> { match self { None => Err(FieldViolation::required(field)), Some(t) => t.scope(field), } } } /// An extension trait that adds the methods `optional` and `required` to any /// String /// /// Prost will default string fields to empty, whereas IOx sometimes /// uses Option<String>, this helper aids mapping between them /// /// TODO: Review mixed use of Option<String> and String in IOX pub(crate) trait FromFieldString { /// Returns a Ok if the String is not empty fn required(self, field: impl Into<String>) -> Result<String, FieldViolation>; /// Wraps non-empty strings in Some(_), returns None for empty strings fn optional(self) -> Option<String>; } impl FromFieldString for String { fn required(self, field: impl Into<Self>) -> Result<String, FieldViolation> { if self.is_empty() { return Err(FieldViolation::required(field)); } Ok(self) } fn optional(self) -> Option<String> { if self.is_empty() { return None; } Some(self) } } /// An extension trait that adds the method `vec_field` to any Vec of a type /// implementing `TryInto<U, Error = FieldViolation>` pub(crate) trait FromFieldVec<T> { /// Converts to a `Vec<U>`, short-circuiting on the first error and /// returning a correctly scoped `FieldViolation` for where the error /// was encountered fn vec_field(self, field: impl Into<String>) -> Result<T, FieldViolation>; } impl<T, U> FromFieldVec<Vec<U>> for Vec<T> where T: TryInto<U, Error = FieldViolation>, { fn vec_field(self, field: impl Into<String>) -> Result<Vec<U>, FieldViolation> { let res: Result<_, _> = self .into_iter() .enumerate() .map(|(i, t)| t.scope(i.to_string())) .collect(); res.map_err(|e| e.scope(field)) } }
32.831858
86
0.650674
e2663c62c95d86233fbda388f52942339c546a9c
616
use anyhow::Result; use std::{fs::File, io::Read, path::Path}; use svd_parser::svd::{Device, Peripheral}; pub fn peripherals<R: Read>(svd: &mut R) -> Result<Vec<Peripheral>> { let xml = &mut String::new(); svd.read_to_string(xml).unwrap(); let device = parse_device(xml)?; Ok(device.peripherals) } fn parse_device(xml: &str) -> Result<Device> { svd_parser::parse(xml) } pub fn device(path: &Path) -> Result<Device> { let xml = &mut String::new(); let mut svd_file = File::open(path).expect("svd path is not correct"); svd_file.read_to_string(xml).unwrap(); parse_device(xml) }
28
74
0.654221
fffa3c4077480af65701506aa2025384adca8fb0
2,937
// Copyright 2018 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use rand::{Rng, XorShiftRng, SeedableRng}; use messages::{Message, RawTransaction}; use encoding::Error as MessageError; use crypto::{PublicKey, SecretKey, Hash, gen_keypair}; use storage::{Fork, Snapshot}; use blockchain::{Service, Transaction, TransactionSet, ExecutionResult}; pub const TIMESTAMPING_SERVICE: u16 = 129; transactions! { TimestampingTransactions { const SERVICE_ID = TIMESTAMPING_SERVICE; struct TimestampTx { pub_key: &PublicKey, data: &[u8], } } } impl Transaction for TimestampTx { fn verify(&self) -> bool { self.verify_signature(self.pub_key()) } fn execute(&self, _: &mut Fork) -> ExecutionResult { Ok(()) } } #[derive(Default)] pub struct TimestampingService {} pub struct TimestampingTxGenerator { rand: XorShiftRng, data_size: usize, public_key: PublicKey, secret_key: SecretKey, } impl TimestampingTxGenerator { pub fn new(data_size: usize) -> TimestampingTxGenerator { let keypair = gen_keypair(); TimestampingTxGenerator::with_keypair(data_size, keypair) } pub fn with_keypair( data_size: usize, keypair: (PublicKey, SecretKey), ) -> TimestampingTxGenerator { let rand = XorShiftRng::from_seed([192, 168, 56, 1]); TimestampingTxGenerator { rand, data_size, public_key: keypair.0, secret_key: keypair.1, } } } impl Iterator for TimestampingTxGenerator { type Item = TimestampTx; fn next(&mut self) -> Option<TimestampTx> { let mut data = vec![0; self.data_size]; self.rand.fill_bytes(&mut data); Some(TimestampTx::new(&self.public_key, &data, &self.secret_key)) } } impl TimestampingService { pub fn new() -> Self { Self::default() } } impl Service for TimestampingService { fn service_name(&self) -> &str { "sandbox_timestamping" } fn service_id(&self) -> u16 { TIMESTAMPING_SERVICE } fn state_hash(&self, _: &Snapshot) -> Vec<Hash> { vec![Hash::new([127; 32]), Hash::new([128; 32])] } fn tx_from_raw(&self, raw: RawTransaction) -> Result<Box<Transaction>, MessageError> { let tx = TimestampingTransactions::tx_from_raw(raw)?; Ok(tx.into()) } }
26.223214
90
0.651345
1edc2fba1f6aa7192cf108f552b91d34a51f359c
9,936
//! The module for delta table state. use chrono::Utc; use parquet::file::{ reader::{FileReader, SerializedFileReader}, serialized_reader::SliceableCursor, }; use serde_json::{Map, Value}; use std::collections::HashMap; use std::collections::HashSet; use std::convert::TryFrom; use std::io::{BufRead, BufReader, Cursor}; use super::{ ApplyLogError, CheckPoint, DeltaDataTypeLong, DeltaDataTypeVersion, DeltaTable, DeltaTableError, DeltaTableMetaData, }; use crate::action; use crate::delta_config; /// State snapshot currently held by the Delta Table instance. #[derive(Default, Debug, Clone)] pub struct DeltaTableState { // A remove action should remain in the state of the table as a tombstone until it has expired. // A tombstone expires when the creation timestamp of the delta file exceeds the expiration tombstones: HashSet<action::Remove>, files: Vec<action::Add>, commit_infos: Vec<Map<String, Value>>, app_transaction_version: HashMap<String, DeltaDataTypeVersion>, min_reader_version: i32, min_writer_version: i32, current_metadata: Option<DeltaTableMetaData>, tombstone_retention_millis: DeltaDataTypeLong, log_retention_millis: DeltaDataTypeLong, enable_expired_log_cleanup: bool, } impl DeltaTableState { /// Construct a delta table state object from commit version. pub async fn from_commit( table: &DeltaTable, version: DeltaDataTypeVersion, ) -> Result<Self, ApplyLogError> { let commit_uri = table.commit_uri_from_version(version); let commit_log_bytes = table.storage.get_obj(&commit_uri).await?; let reader = BufReader::new(Cursor::new(commit_log_bytes)); let mut new_state = DeltaTableState::default(); for line in reader.lines() { let action: action::Action = serde_json::from_str(line?.as_str())?; new_state.process_action(action, true)?; } Ok(new_state) } /// Construct a delta table state object from checkpoint. pub async fn from_checkpoint( table: &DeltaTable, check_point: &CheckPoint, require_tombstones: bool, ) -> Result<Self, DeltaTableError> { let checkpoint_data_paths = table.get_checkpoint_data_paths(check_point); // process actions from checkpoint let mut new_state = DeltaTableState::default(); for f in &checkpoint_data_paths { let obj = table.storage.get_obj(f).await?; let preader = SerializedFileReader::new(SliceableCursor::new(obj))?; let schema = preader.metadata().file_metadata().schema(); if !schema.is_group() { return Err(DeltaTableError::from(action::ActionError::Generic( "Action record in checkpoint should be a struct".to_string(), ))); } for record in preader.get_row_iter(None)? { new_state.process_action( action::Action::from_parquet_record(schema, &record)?, require_tombstones, )?; } } Ok(new_state) } /// List of commit info maps. pub fn commit_infos(&self) -> &Vec<Map<String, Value>> { &self.commit_infos } /// Retention of tombstone in milliseconds. pub fn tombstone_retention_millis(&self) -> DeltaDataTypeLong { self.tombstone_retention_millis } /// Retention of logs in milliseconds. pub fn log_retention_millis(&self) -> DeltaDataTypeLong { self.log_retention_millis } /// Whether to clean up expired checkpoints and delta logs. pub fn enable_expired_log_cleanup(&self) -> bool { self.enable_expired_log_cleanup } /// Full list of tombstones (remove actions) representing files removed from table state). pub fn all_tombstones(&self) -> &HashSet<action::Remove> { &self.tombstones } /// List of unexpired tombstones (remove actions) representing files removed from table state. /// The retention period is set by `deletedFileRetentionDuration` with default value of 1 week. pub fn unexpired_tombstones(&self) -> impl Iterator<Item = &action::Remove> { let retention_timestamp = Utc::now().timestamp_millis() - self.tombstone_retention_millis; self.tombstones .iter() .filter(move |t| t.deletion_timestamp.unwrap_or(0) > retention_timestamp) } /// Full list of add actions representing all parquet files that are part of the current /// delta table state. pub fn files(&self) -> &Vec<action::Add> { self.files.as_ref() } /// HashMap containing the last txn version stored for every app id writing txn /// actions. pub fn app_transaction_version(&self) -> &HashMap<String, DeltaDataTypeVersion> { &self.app_transaction_version } /// The min reader version required by the protocol. pub fn min_reader_version(&self) -> i32 { self.min_reader_version } /// The min writer version required by the protocol. pub fn min_writer_version(&self) -> i32 { self.min_writer_version } /// The most recent metadata of the table. pub fn current_metadata(&self) -> Option<&DeltaTableMetaData> { self.current_metadata.as_ref() } /// merges new state information into our state pub fn merge(&mut self, mut new_state: DeltaTableState, require_tombstones: bool) { if !new_state.tombstones.is_empty() { self.files .retain(|a| !new_state.tombstones.contains(a.path.as_str())); } if require_tombstones { new_state.tombstones.into_iter().for_each(|r| { self.tombstones.insert(r); }); if !new_state.files.is_empty() { new_state.files.iter().for_each(|s| { self.tombstones.remove(s.path.as_str()); }); } } self.files.append(&mut new_state.files); if new_state.min_reader_version > 0 { self.min_reader_version = new_state.min_reader_version; self.min_writer_version = new_state.min_writer_version; } if new_state.current_metadata.is_some() { self.tombstone_retention_millis = new_state.tombstone_retention_millis; self.log_retention_millis = new_state.log_retention_millis; self.enable_expired_log_cleanup = new_state.enable_expired_log_cleanup; self.current_metadata = new_state.current_metadata.take(); } new_state .app_transaction_version .drain() .for_each(|(app_id, version)| { *self .app_transaction_version .entry(app_id) .or_insert(version) = version }); if !new_state.commit_infos.is_empty() { self.commit_infos.append(&mut new_state.commit_infos); } } /// Process given action by updating current state. fn process_action( &mut self, action: action::Action, handle_tombstones: bool, ) -> Result<(), ApplyLogError> { match action { action::Action::add(v) => { self.files.push(v.path_decoded()?); } action::Action::remove(v) => { if handle_tombstones { let v = v.path_decoded()?; self.tombstones.insert(v); } } action::Action::protocol(v) => { self.min_reader_version = v.min_reader_version; self.min_writer_version = v.min_writer_version; } action::Action::metaData(v) => { let md = DeltaTableMetaData::try_from(v)?; self.tombstone_retention_millis = delta_config::TOMBSTONE_RETENTION .get_interval_from_metadata(&md)? .as_millis() as i64; self.log_retention_millis = delta_config::LOG_RETENTION .get_interval_from_metadata(&md)? .as_millis() as i64; self.enable_expired_log_cleanup = delta_config::ENABLE_EXPIRED_LOG_CLEANUP.get_boolean_from_metadata(&md)?; self.current_metadata = Some(md); } action::Action::txn(v) => { *self .app_transaction_version .entry(v.app_id) .or_insert(v.version) = v.version; } action::Action::commitInfo(v) => { self.commit_infos.push(v); } } Ok(()) } } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; use std::collections::HashMap; #[test] fn state_records_new_txn_version() { let mut app_transaction_version = HashMap::new(); app_transaction_version.insert("abc".to_string(), 1); app_transaction_version.insert("xyz".to_string(), 1); let mut state = DeltaTableState { files: vec![], commit_infos: vec![], tombstones: HashSet::new(), current_metadata: None, min_reader_version: 1, min_writer_version: 2, app_transaction_version, tombstone_retention_millis: 0, log_retention_millis: 0, enable_expired_log_cleanup: true, }; let txn_action = action::Action::txn(action::Txn { app_id: "abc".to_string(), version: 2, last_updated: Some(0), }); let _ = state.process_action(txn_action, false).unwrap(); assert_eq!(2, *state.app_transaction_version().get("abc").unwrap()); assert_eq!(1, *state.app_transaction_version().get("xyz").unwrap()); } }
35.485714
99
0.609501
b95ad12b857502fcc8d53f20346d1fdc9487be5f
5,650
use std::io::Cursor; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use log::debug; use serde_cbor::de::from_slice; use serde_cbor::ser::to_vec; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use crate::error::Error; use crate::network::message::*; // Reexport all stream/socket related stuff for convenience purposes pub use super::platform::socket::Stream; pub use super::platform::socket::*; /// Convenience wrapper around send_bytes. /// Deserialize a message and feed the bytes into send_bytes. pub async fn send_message(message: Message, stream: &mut GenericStream) -> Result<(), Error> { debug!("Sending message: {:?}", message); // Prepare command for transfer and determine message byte size let payload = to_vec(&message).map_err(|err| Error::MessageDeserialization(err.to_string()))?; send_bytes(&payload, stream).await } /// Send a Vec of bytes. Before the actual bytes are send, the size of the message /// is transmitted in an header of fixed size (u64). pub async fn send_bytes(payload: &[u8], stream: &mut GenericStream) -> Result<(), Error> { let message_size = payload.len() as u64; let mut header = vec![]; WriteBytesExt::write_u64::<BigEndian>(&mut header, message_size).unwrap(); // Send the request size header first. // Afterwards send the request. stream.write_all(&header).await?; // Split the payload into 1.4Kbyte chunks // 1.5Kbyte is the MUT for TCP, but some carrier have a little less, such as Wireguard. for chunk in payload.chunks(1400) { stream.write_all(chunk).await?; } Ok(()) } /// Receive a byte stream. \ /// This is the basic protocol beneath all pueue communication. \ /// /// 1. The client sends a u64, which specifies the length of the payload. /// 2. Receive chunks of 1400 bytes until we finished all expected bytes pub async fn receive_bytes(stream: &mut GenericStream) -> Result<Vec<u8>, Error> { // Receive the header with the overall message size let mut header = vec![0; 8]; stream.read_exact(&mut header).await?; let mut header = Cursor::new(header); let message_size = ReadBytesExt::read_u64::<BigEndian>(&mut header)? as usize; // Buffer for the whole payload let mut payload_bytes = Vec::with_capacity(message_size); // Create a static buffer with our packet size. let mut chunk_buffer: [u8; 1400] = [0; 1400]; // Receive chunks until we reached the expected message size while payload_bytes.len() < message_size { // Read data and get the amount of received bytes let received_bytes = stream.read(&mut chunk_buffer).await?; if received_bytes == 0 { return Err(Error::Connection( "Connection went away while receiving payload.".into(), )); } // Extend the total payload bytes by the part of the buffer that has been filled // during this iteration. payload_bytes.extend_from_slice(&chunk_buffer[0..received_bytes]); } Ok(payload_bytes) } /// Convenience wrapper that receives a message and converts it into a Message. pub async fn receive_message(stream: &mut GenericStream) -> Result<Message, Error> { let payload_bytes = receive_bytes(stream).await?; debug!("Received {} bytes", payload_bytes.len()); if payload_bytes.is_empty() { return Err(Error::EmptyPayload); } // Deserialize the message. let message: Message = from_slice(&payload_bytes).map_err(|err| Error::MessageDeserialization(err.to_string()))?; debug!("Received message: {:?}", message); Ok(message) } #[cfg(test)] mod test { use super::*; use async_trait::async_trait; use pretty_assertions::assert_eq; use tokio::net::{TcpListener, TcpStream}; use tokio::task; use crate::network::platform::socket::Stream as PueueStream; // Implement generic Listener/Stream traits, so we can test stuff on normal TCP #[async_trait] impl Listener for TcpListener { async fn accept<'a>(&'a self) -> Result<GenericStream, Error> { let (stream, _) = self.accept().await?; Ok(Box::new(stream)) } } impl PueueStream for TcpStream {} #[tokio::test] async fn test_single_huge_payload() -> Result<(), Error> { let listener = TcpListener::bind("127.0.0.1:0").await?; let addr = listener.local_addr()?; // The message that should be sent let payload = "a".repeat(100_000); let message = create_success_message(payload); let original_bytes = to_vec(&message).expect("Failed to serialize message."); let listener: GenericListener = Box::new(listener); // Spawn a sub thread that: // 1. Accepts a new connection // 2. Reads a message // 3. Sends the same message back task::spawn(async move { let mut stream = listener.accept().await.unwrap(); let message_bytes = receive_bytes(&mut stream).await.unwrap(); let message: Message = from_slice(&message_bytes).unwrap(); send_message(message, &mut stream).await.unwrap(); }); let mut client: GenericStream = Box::new(TcpStream::connect(&addr).await?); // Create a client that sends a message and instantly receives it send_message(message, &mut client).await?; let response_bytes = receive_bytes(&mut client).await?; let _message: Message = from_slice(&response_bytes) .map_err(|err| Error::MessageDeserialization(err.to_string()))?; assert_eq!(response_bytes, original_bytes); Ok(()) } }
35.534591
98
0.662301
1a654da17e5745fa56a30dde58e23a1019a4da3e
5,088
use crate::{GuestError, GuestPtr}; use std::mem; pub trait GuestErrorType<'a> { type Context; fn success() -> Self; fn from_error(e: GuestError, ctx: &Self::Context) -> Self; } /// A trait for types that are intended to be pointees in `GuestPtr<T>`. /// /// This trait abstracts how to read/write information from the guest memory, as /// well as how to offset elements in an array of guest memory. This layer of /// abstraction allows the guest representation of a type to be different from /// the host representation of a type, if necessary. It also allows for /// validation when reading/writing. pub trait GuestType<'a>: Sized { /// Returns the size, in bytes, of this type in the guest memory. fn guest_size() -> u32; /// Returns the required alignment of this type, in bytes, for both guest /// and host memory. fn guest_align() -> usize; /// Reads this value from the provided `ptr`. /// /// Must internally perform any safety checks necessary and is allowed to /// fail if the bytes pointed to are also invalid. /// /// Typically if you're implementing this by hand you'll want to delegate to /// other safe implementations of this trait (e.g. for primitive types like /// `u32`) rather than writing lots of raw code yourself. fn read(ptr: &GuestPtr<'a, Self>) -> Result<Self, GuestError>; /// Writes a value to `ptr` after verifying that `ptr` is indeed valid to /// store `val`. /// /// Similar to `read`, you'll probably want to implement this in terms of /// other primitives. fn write(ptr: &GuestPtr<'_, Self>, val: Self) -> Result<(), GuestError>; } /// A trait for `GuestType`s that have the same representation in guest memory /// as in Rust. These types can be used with the `GuestPtr::as_raw` method to /// view as a slice. /// /// Unsafe trait because a correct GuestTypeTransparent implemengation ensures that the /// GuestPtr::as_raw methods are safe. This trait should only ever be implemented /// by wiggle_generate-produced code. pub unsafe trait GuestTypeTransparent<'a>: GuestType<'a> { /// Checks that the memory at `ptr` is a valid representation of `Self`. /// /// Assumes that memory safety checks have already been performed: `ptr` /// has been checked to be aligned correctly and reside in memory using /// `GuestMemory::validate_size_align` fn validate(ptr: *mut Self) -> Result<(), GuestError>; } macro_rules! primitives { ($($i:ident)*) => ($( impl<'a> GuestType<'a> for $i { fn guest_size() -> u32 { mem::size_of::<Self>() as u32 } fn guest_align() -> usize { mem::align_of::<Self>() } #[inline] fn read(ptr: &GuestPtr<'a, Self>) -> Result<Self, GuestError> { // Any bit pattern for any primitive implemented with this // macro is safe, so our `validate_size_align` method will // guarantee that if we are given a pointer it's valid for the // size of our type as well as properly aligned. Consequently we // should be able to safely ready the pointer just after we // validated it, returning it along here. let host_ptr = ptr.mem().validate_size_align( ptr.offset(), Self::guest_align(), Self::guest_size(), )?; Ok(unsafe { *host_ptr.cast::<Self>() }) } #[inline] fn write(ptr: &GuestPtr<'_, Self>, val: Self) -> Result<(), GuestError> { let host_ptr = ptr.mem().validate_size_align( ptr.offset(), Self::guest_align(), Self::guest_size(), )?; // Similar to above `as_raw` will do a lot of validation, and // then afterwards we can safely write our value into the // memory location. unsafe { *host_ptr.cast::<Self>() = val; } Ok(()) } } unsafe impl<'a> GuestTypeTransparent<'a> for $i { #[inline] fn validate(_ptr: *mut $i) -> Result<(), GuestError> { // All bit patterns are safe, nothing to do here Ok(()) } } )*) } primitives! { // signed i8 i16 i32 i64 i128 isize // unsigned u8 u16 u32 u64 u128 usize // floats f32 f64 } // Support pointers-to-pointers where pointers are always 32-bits in wasm land impl<'a, T> GuestType<'a> for GuestPtr<'a, T> { fn guest_size() -> u32 { u32::guest_size() } fn guest_align() -> usize { u32::guest_align() } fn read(ptr: &GuestPtr<'a, Self>) -> Result<Self, GuestError> { let offset = ptr.cast::<u32>().read()?; Ok(GuestPtr::new(ptr.mem(), offset)) } fn write(ptr: &GuestPtr<'_, Self>, val: Self) -> Result<(), GuestError> { ptr.cast::<u32>().write(val.offset()) } }
37.138686
87
0.584119
6a7acc41170c6af02da468022dcd64de48afbbec
28,358
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. //! This module provides a TCP-based boundary. use serde::{Deserialize, Serialize}; use timely::dataflow::operators::capture::EventCore; use timely::logging::WorkerIdentifier; use tokio_serde::formats::Bincode; use tokio_util::codec::LengthDelimitedCodec; use mz_dataflow_types::DataflowError; use mz_expr::GlobalId; /// Type alias for source subscriptions, (dataflow_id, source_id). pub type SourceId = (GlobalId, GlobalId); /// Type alias for a source subscription including a source worker. pub type SubscriptionId = (SourceId, WorkerIdentifier); pub mod server { //! TCP boundary server use crate::server::boundary::StorageCapture; use crate::server::tcp_boundary::{length_delimited_codec, Command, Framed, Response}; use crate::tcp_boundary::SubscriptionId; use differential_dataflow::Collection; use futures::{SinkExt, TryStreamExt}; use mz_dataflow_types::{DataflowError, SourceInstanceKey}; use mz_expr::GlobalId; use mz_repr::{Diff, Row, Timestamp}; use std::any::Any; use std::collections::{HashMap, HashSet}; use std::rc::Rc; use std::sync::{Arc, Weak}; use timely::dataflow::operators::capture::{EventCore, EventPusherCore}; use timely::dataflow::operators::Capture; use timely::dataflow::Scope; use tokio::io::{AsyncRead, AsyncWrite}; use tokio::net::{TcpListener, TcpStream, ToSocketAddrs}; use tokio::select; use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; use tokio::sync::Mutex; use tokio::task::JoinHandle; use tokio_serde::formats::Bincode; use tracing::{debug, info, warn}; /// A framed connection from the server's perspective. type FramedServer<C> = Framed<C, Command, Response>; /// Constructs a framed connection for the server. fn framed_server<C>(conn: C) -> FramedServer<C> where C: AsyncRead + AsyncWrite, { tokio_serde::Framed::new( tokio_util::codec::Framed::new(conn, length_delimited_codec()), Bincode::default(), ) } /// Unique client identifier, only used internally type ClientId = u64; /// Shared state between main server loop and client-specific task. #[derive(Debug, Default)] struct Shared { subscriptions: HashMap<SubscriptionId, SourceState>, channels: HashMap<ClientId, UnboundedSender<Response>>, } /// Shared per-subscription state #[derive(Debug, Default)] struct SourceState { /// Pending responses stashed before client registered. stash: Vec<Response>, /// Client, once it registered client_id: Option<ClientId>, /// Tokens to drop to terminate source. token: Option<Arc<()>>, } /// Response from Timely workers to network handler. #[derive(Debug)] enum WorkerResponse { /// Announce the presence of a captured source. Announce { subscription_id: SubscriptionId, token: Arc<()>, }, /// Data from a source Response(Response), } /// Start the boundary server listening for connections on `addr`. /// /// Returns a handle implementing [StorageCapture] and a join handle to await termination. pub async fn serve<A: ToSocketAddrs + std::fmt::Display>( addr: A, ) -> std::io::Result<(TcpEventLinkHandle, JoinHandle<std::io::Result<()>>)> { let (worker_tx, worker_rx) = unbounded_channel(); info!("About to bind to {addr}"); let listener = TcpListener::bind(addr).await?; info!( "listening for storage connection on {:?}...", listener.local_addr() ); let thread = mz_ore::task::spawn(|| "storage server", accept(listener, worker_rx)); Ok((TcpEventLinkHandle { worker_tx }, thread)) } /// Accept connections on `listener` and listening for data on `worker_rx`. async fn accept( listener: TcpListener, mut worker_rx: UnboundedReceiver<WorkerResponse>, ) -> std::io::Result<()> { debug!("server listening {listener:?}"); let shared = Default::default(); let state = Arc::new(Mutex::new(shared)); loop { select! { _ = async { let mut client_id = 0; loop { client_id += 1; match listener.accept().await { Ok((socket, addr)) => { debug!("Accepting client {client_id} on {addr}..."); let state = Arc::clone(&state); mz_ore::task::spawn(|| "client loop", async move { handle_compute(client_id, Arc::clone(&state), socket).await }); } Err(e) => { warn!("Failed to accept connection: {e}"); } } } } => {} worker_response = worker_rx.recv() => match worker_response { Some(WorkerResponse::Announce{subscription_id, token}) => { debug!("Subscription announced: {subscription_id:?}"); let mut state = state.lock().await; let subscription = state.subscriptions.entry(subscription_id).or_default(); subscription.token = Some(token); } Some(WorkerResponse::Response(response)) => { let mut state = state.lock().await; if let Some(subscription) = state.subscriptions.get_mut(&response.subscription_id) { if let Some(client_id) = subscription.client_id { state.channels.get_mut(&client_id).unwrap().send(response).unwrap(); } else { subscription.stash.push(response); } } } None => return Ok(()), }, } } } /// Handle the server side of a compute client connection in `socket`, identified by /// `client_id`. `state` is a handle to the shared state. /// /// This function calls into the inner part and upon client termination cleans up state. async fn handle_compute( client_id: ClientId, state: Arc<Mutex<Shared>>, socket: TcpStream, ) -> std::io::Result<()> { let mut source_ids = HashSet::new(); let result = handle_compute_inner(client_id, Arc::clone(&state), socket, &mut source_ids).await; let mut state = state.lock().await; for source_id in source_ids { state.subscriptions.remove(&source_id); } state.channels.remove(&client_id); result } /// Inner portion to handle a compute client. async fn handle_compute_inner( client_id: ClientId, state: Arc<Mutex<Shared>>, socket: TcpStream, active_source_ids: &mut HashSet<SubscriptionId>, ) -> std::io::Result<()> { let mut connection = framed_server(socket); let (client_tx, mut client_rx) = unbounded_channel(); state.lock().await.channels.insert(client_id, client_tx); loop { select! { cmd = connection.try_next() => match cmd? { Some(Command::Subscribe(subscription_id, )) => { debug!("Subscribe client {client_id} to {subscription_id:?}"); let new = active_source_ids.insert(subscription_id); assert!(new, "Duplicate key: {subscription_id:?}"); let stashed = { let mut state = state.lock().await; let subscription = state.subscriptions.entry(subscription_id).or_default(); assert!(subscription.client_id.is_none()); subscription.client_id = Some(client_id); std::mem::take(&mut subscription.stash) }; for stashed in stashed { connection.send(stashed).await?; } } Some(Command::Unsubscribe(subscription_id)) => { debug!("Unsubscribe client {client_id} from {subscription_id:?}"); let mut state = state.lock().await; state.subscriptions.remove(&subscription_id); let removed = active_source_ids.remove(&subscription_id); assert!(removed, "Unknown key: {subscription_id:?}"); } None => { return Ok(()); } }, response = client_rx.recv() => connection.send(response.expect("Channel closed before dropping source")).await?, } } } /// A handle to the boundary service. Implements [StorageCapture] to capture sources. #[derive(Clone, Debug)] pub struct TcpEventLinkHandle { worker_tx: UnboundedSender<WorkerResponse>, } impl StorageCapture for TcpEventLinkHandle { fn capture<G: Scope<Timestamp = Timestamp>>( &mut self, id: SourceInstanceKey, ok: Collection<G, Row, Diff>, err: Collection<G, DataflowError, Diff>, token: Rc<dyn Any>, _name: &str, dataflow_id: GlobalId, ) { let subscription_id = ((dataflow_id, id.identifier), ok.inner.scope().index()); let client_token = Arc::new(()); // Announce that we're capturing data, with the source ID and a token. Once the token // is dropped, we drop the `token` to terminate the source. self.worker_tx .send(WorkerResponse::Announce { subscription_id, token: Arc::clone(&client_token), }) .unwrap(); ok.inner.capture_into(UnboundedEventPusher::new( self.worker_tx.clone(), Rc::clone(&token), &client_token, move |event| { WorkerResponse::Response(Response { subscription_id, data: Ok(event), }) }, )); err.inner.capture_into(UnboundedEventPusher::new( self.worker_tx.clone(), token, &client_token, move |event| { WorkerResponse::Response(Response { subscription_id, data: Err(event), }) }, )); } } /// Helper struct to capture data into a sender and drop tokens once dropped itself. struct UnboundedEventPusher<R, F> { /// The sender to pass all data to. sender: UnboundedSender<R>, /// A function to convert the input data into something the sender can transport. convert: F, /// A token that's dropped once `client_token` is dropped. token: Option<Rc<dyn Any>>, /// A weak reference to a token that e.g. the network layer can drop. client_token: Weak<()>, } impl<R, F> UnboundedEventPusher<R, F> { /// Construct a new pusher. It'll retain a weak reference to `client_token`. fn new( sender: UnboundedSender<R>, token: Rc<dyn Any>, client_token: &Arc<()>, convert: F, ) -> Self { Self { sender, client_token: Arc::downgrade(client_token), convert, token: Some(token), } } } impl<T, D, R, F: Fn(EventCore<T, D>) -> R> EventPusherCore<T, D> for UnboundedEventPusher<R, F> { fn push(&mut self, event: EventCore<T, D>) { if self.client_token.upgrade().is_none() { self.token.take(); } if self.token.is_some() { match self.sender.send((self.convert)(event)) { Err(_) => { self.token.take(); } _ => {} } } } } } pub mod client { //! TCP boundary client use crate::activator::{ActivatorTrait, ArcActivator}; use crate::replay::MzReplay; use crate::server::boundary::ComputeReplay; use crate::server::tcp_boundary::{ length_delimited_codec, Command, Framed, Response, SourceId, }; use differential_dataflow::{AsCollection, Collection}; use futures::{Sink, SinkExt, TryStreamExt}; use mz_dataflow_types::{DataflowError, SourceInstanceKey}; use mz_expr::GlobalId; use mz_repr::{Diff, Row, Timestamp}; use std::any::Any; use std::collections::HashMap; use std::rc::Rc; use std::time::Duration; use timely::dataflow::operators::capture::event::EventIteratorCore; use timely::dataflow::operators::capture::EventCore; use timely::dataflow::Scope; use timely::logging::WorkerIdentifier; use tokio::io::{AsyncRead, AsyncWrite}; use tokio::net::{TcpStream, ToSocketAddrs}; use tokio::select; use tokio::sync::mpsc::error::TryRecvError; use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; use tokio::task::JoinHandle; use tokio_serde::formats::Bincode; use tracing::{debug, info, warn}; /// A framed connection from the client's perspective. type FramedClient<C> = Framed<C, Response, Command>; /// Constructs a framed connection for the client. fn framed_client<C>(conn: C) -> FramedClient<C> where C: AsyncRead + AsyncWrite, { tokio_serde::Framed::new( tokio_util::codec::Framed::new(conn, length_delimited_codec()), Bincode::default(), ) } /// A handle to the storage client. Implements [ComputeReplay]. #[derive(Debug, Clone)] pub struct TcpEventLinkClientHandle { announce_tx: UnboundedSender<Announce>, storage_workers: usize, } /// State per worker and source. #[derive(Debug)] struct WorkerState<T, D, A: ActivatorTrait> { sender: UnboundedSender<EventCore<T, D>>, activator: Option<A>, } impl<T, D, A: ActivatorTrait> WorkerState<T, D, A> { /// Construct a new state object with the provided `sender` and no activator. fn new(sender: UnboundedSender<EventCore<T, D>>) -> Self { Self { sender, activator: None, } } /// Register an `activator` to wake the Timely operator. fn register(&mut self, activator: A) { self.activator = Some(activator); } /// Send data at the channel and activate if the activator is set. fn send_and_activate(&mut self, event: EventCore<T, D>) { let res = self.sender.send(event); if res.is_err() { warn!("Receiver hung up"); } if let Some(activator) = &mut self.activator { activator.activate(); } } } #[derive(Debug, Default)] struct SubscriptionState<T, R> { ok_state: HashMap<WorkerIdentifier, WorkerState<T, Vec<(Row, T, R)>, ArcActivator>>, err_state: HashMap<WorkerIdentifier, WorkerState<T, Vec<(DataflowError, T, R)>, ArcActivator>>, } #[derive(Debug)] struct ClientState { subscriptions: HashMap<SourceId, SubscriptionState<mz_repr::Timestamp, mz_repr::Diff>>, workers: usize, } impl ClientState { fn new(workers: usize) -> Self { Self { workers, subscriptions: Default::default(), } } async fn handle_announce<C: Sink<Command, Error = std::io::Error> + Unpin>( &mut self, client: &mut C, announce: Announce, ) -> std::io::Result<()> { match announce { Announce::Register { source_id, worker, storage_workers, ok_tx, ok_activator, err_activator, err_tx, } => { let state = self.subscriptions.entry(source_id).or_default(); state.ok_state.insert(worker, WorkerState::new(ok_tx)); state.err_state.insert(worker, WorkerState::new(err_tx)); let worker_state = state.ok_state.get_mut(&worker).unwrap(); worker_state.register(ok_activator); let worker_state = state.err_state.get_mut(&worker).unwrap(); worker_state.register(err_activator); // Send subscription command to server debug!("Subscribing to {source_id:?}"); client .send_all(&mut futures::stream::iter(storage_workers.into_iter().map( |storage_worker| Ok(Command::Subscribe((source_id, storage_worker))), ))) .await?; } Announce::Drop(source_id, worker, storage_workers) => { // Announce to unsubscribe from the source. if let Some(state) = self.subscriptions.get_mut(&source_id) { state.ok_state.remove(&worker); state.err_state.remove(&worker); debug!("Unsubscribing from {source_id:?}"); client .send_all(&mut futures::stream::iter(storage_workers.into_iter().map( |storage_worker| { Ok(Command::Unsubscribe((source_id, storage_worker))) }, ))) .await?; let cleanup = state.ok_state.is_empty(); if cleanup { self.subscriptions.remove(&source_id); } } } } Ok(()) } async fn handle_response( &mut self, Response { subscription_id, data, }: Response, ) { if let Some(state) = self.subscriptions.get_mut(&subscription_id.0) { let worker = subscription_id.1 % self.workers; match data { Ok(event) => { // We might have dropped the local worker already but still receive data if let Some(channel) = state.ok_state.get_mut(&worker) { channel.send_and_activate(event); } } Err(event) => { // We might have dropped the local worker already but still receive data if let Some(channel) = state.err_state.get_mut(&worker) { channel.send_and_activate(event); } } } } } } /// Connect to a storage boundary server. Returns a handle to replay sources and a join handle /// to await termination. pub async fn connect<A: ToSocketAddrs + std::fmt::Debug>( addr: A, workers: usize, storage_workers: usize, ) -> std::io::Result<(TcpEventLinkClientHandle, JoinHandle<std::io::Result<()>>)> { let (announce_tx, announce_rx) = unbounded_channel(); info!("About to connect to {addr:?}"); let stream = TcpStream::connect(addr).await?; info!("Connected to storage server"); let thread = mz_ore::task::spawn( || "storage client", run_client(stream, announce_rx, workers), ); Ok(( TcpEventLinkClientHandle { announce_tx, storage_workers, }, thread, )) } /// Communicate data and subscriptions on `stream`, receiving local replay notifications on /// `announce_rx`. `workers` is the number of local Timely workers. async fn run_client( stream: TcpStream, mut announce_rx: UnboundedReceiver<Announce>, workers: usize, ) -> std::io::Result<()> { debug!("client: connected to server"); let mut client = framed_client(stream); let mut state = ClientState::new(workers); loop { select! { response = client.try_next() => match response? { Some(response) => state.handle_response(response).await, None => break, }, announce = announce_rx.recv() => match announce { Some(announce) => state.handle_announce(&mut client, announce).await?, None => break, } } } Ok(()) } /// Announcement protocol from a Timely worker to the storage client. #[derive(Debug)] enum Announce { /// Provide activators for the source Register { source_id: SourceId, worker: WorkerIdentifier, storage_workers: Vec<WorkerIdentifier>, ok_activator: ArcActivator, err_activator: ArcActivator, ok_tx: UnboundedSender<EventCore<Timestamp, Vec<(Row, Timestamp, Diff)>>>, err_tx: UnboundedSender<EventCore<Timestamp, Vec<(DataflowError, Timestamp, Diff)>>>, }, /// Replayer dropped Drop(SourceId, WorkerIdentifier, Vec<WorkerIdentifier>), } impl ComputeReplay for TcpEventLinkClientHandle { fn replay<G: Scope<Timestamp = Timestamp>>( &mut self, id: SourceInstanceKey, scope: &mut G, name: &str, dataflow_id: GlobalId, ) -> ( Collection<G, Row, Diff>, Collection<G, DataflowError, Diff>, Rc<dyn Any>, ) { let source_id = (dataflow_id, id.identifier); // Create a channel to receive worker/replay-specific data channels let (ok_tx, ok_rx) = unbounded_channel(); let (err_tx, err_rx) = unbounded_channel(); let ok_activator = ArcActivator::new(format!("{name}-ok-activator"), 1); let err_activator = ArcActivator::new(format!("{name}-err-activator"), 1); let storage_workers = (0..self.storage_workers) .into_iter() .map(|x| scope.index() + x * scope.peers()) .filter(|x| *x < self.storage_workers) .collect::<Vec<_>>(); // Register with the storage client let register = Announce::Register { source_id, worker: scope.index(), storage_workers: storage_workers.clone(), ok_tx, err_tx, ok_activator: ok_activator.clone(), err_activator: err_activator.clone(), }; self.announce_tx.send(register).unwrap(); // Construct activators and replay data let mut ok_rx = Some(ok_rx); let ok = storage_workers .iter() .map(|_| { UnboundedEventPuller::new(ok_rx.take().unwrap_or_else(|| unbounded_channel().1)) }) .mz_replay(scope, &format!("{name}-ok"), Duration::MAX, ok_activator) .as_collection(); let mut err_rx = Some(err_rx); let err = storage_workers .iter() .map(|_| { UnboundedEventPuller::new( err_rx.take().unwrap_or_else(|| unbounded_channel().1), ) }) .mz_replay(scope, &format!("{name}-err"), Duration::MAX, err_activator) .as_collection(); // Construct token to unsubscribe from source let token = Rc::new(DropReplay { announce_tx: self.announce_tx.clone(), message: Some(Announce::Drop(source_id, scope.index(), storage_workers)), }); (ok, err, Rc::new(token)) } } /// Utility to send a message on drop. struct DropReplay { /// Channel where to send the message announce_tx: UnboundedSender<Announce>, /// Pre-defined message to send message: Option<Announce>, } impl Drop for DropReplay { fn drop(&mut self) { if let Some(message) = self.message.take() { // Igore errors on send as it indicates the client is no longer running let _ = self.announce_tx.send(message); } } } /// Puller reading from a `receiver` channel. struct UnboundedEventPuller<D> { /// The receiver to read from. receiver: UnboundedReceiver<D>, /// Current element element: Option<D>, } impl<D> UnboundedEventPuller<D> { /// Construct a new puller reading from `receiver`. fn new(receiver: UnboundedReceiver<D>) -> Self { Self { receiver, element: None, } } } impl<T, D> EventIteratorCore<T, D> for UnboundedEventPuller<EventCore<T, D>> { fn next(&mut self) -> Option<&EventCore<T, D>> { match self.receiver.try_recv() { Ok(element) => { self.element = Some(element); self.element.as_ref() } Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) => { self.element.take(); None } } } } } /// A command sent from the storage client to the storage server. #[derive(Clone, Debug, Serialize, Deserialize)] enum Command { /// Subscribe the client to `source_id`. Subscribe(SubscriptionId), /// Unsubscribe the client from `source_id`. Unsubscribe(SubscriptionId), } /// Data provided to the storage client from the storage server upon successful registration. /// /// Each message has a source_id to identify the subscription, a worker that produced the data, /// and the data itself. When replaying, the mapping of storage worker to compute worker needs /// (at least) to be static. #[derive(Clone, Debug, Serialize, Deserialize)] struct Response { subscription_id: SubscriptionId, /// Contents of the Ok-collection data: Result< EventCore<mz_repr::Timestamp, Vec<(mz_repr::Row, mz_repr::Timestamp, mz_repr::Diff)>>, EventCore<mz_repr::Timestamp, Vec<(DataflowError, mz_repr::Timestamp, mz_repr::Diff)>>, >, } /// A framed connection to a storage server. pub type Framed<C, T, U> = tokio_serde::Framed<tokio_util::codec::Framed<C, LengthDelimitedCodec>, T, U, Bincode<T, U>>; fn length_delimited_codec() -> LengthDelimitedCodec { // NOTE(benesch): using an unlimited maximum frame length is problematic // because Tokio never shrinks its buffer. Sending or receiving one large // message of size N means the client will hold on to a buffer of size // N forever. We should investigate alternative transport protocols that // do not have this limitation. let mut codec = LengthDelimitedCodec::new(); codec.set_max_frame_length(usize::MAX); codec }
38.06443
128
0.538296
61bf06e48f2e895b08ba7747a62ce015a7954b52
25,983
use super::params::{DeleteParams, ListParams, Patch, PatchParams, PostParams}; use crate::{ api::{DynamicResource, Meta}, Error, Result, }; /// A Kubernetes resource that can be accessed through the API #[derive(Clone, Debug)] pub struct Resource { /// The API version of the resource. /// /// This is a composite of `Resource::GROUP` and `Resource::VERSION` /// (eg "apiextensions.k8s.io/v1beta1") /// or just the version for resources without a group (eg "v1"). /// This is the string used in the `apiVersion` field of the resource's serialized form. pub api_version: String, /// The group of the resource /// /// or the empty string if the resource doesn't have a group. pub group: String, /// The kind of the resource. /// /// This is the string used in the kind field of the resource's serialized form. pub kind: String, /// The version of the resource. pub version: String, /// The namespace if the resource resides (if namespaced) pub namespace: Option<String>, } impl Resource { /// Cluster level resources, or resources viewed across all namespaces /// /// This function accepts `K::DynamicType` so it can be used with dynamic resources. pub fn all_with<K: Meta>(dyntype: &K::DynamicType) -> Self { Self { api_version: K::api_version(dyntype).into_owned(), kind: K::kind(dyntype).into_owned(), group: K::group(dyntype).into_owned(), version: K::version(dyntype).into_owned(), namespace: None, } } /// Namespaced resource within a given namespace /// /// This function accepts `K::DynamicType` so it can be used with dynamic resources. pub fn namespaced_with<K: Meta>(ns: &str, dyntype: &K::DynamicType) -> Self { let kind = K::kind(dyntype); match kind.as_ref() { "Node" | "Namespace" | "ClusterRole" | "CustomResourceDefinition" => { panic!("{} is not a namespace scoped resource", kind) } _ => {} } Self { api_version: K::api_version(dyntype).into_owned(), kind: kind.into_owned(), group: K::group(dyntype).into_owned(), version: K::version(dyntype).into_owned(), namespace: Some(ns.to_string()), } } /// Cluster level resources, or resources viewed across all namespaces pub fn all<K: Meta>() -> Self where <K as Meta>::DynamicType: Default, { Self::all_with::<K>(&Default::default()) } /// Namespaced resource within a given namespace pub fn namespaced<K: Meta>(ns: &str) -> Self where <K as Meta>::DynamicType: Default, { Self::namespaced_with::<K>(ns, &Default::default()) } /// Manually configured resource or custom resource /// /// This is the only entrypoint to `Resource` that bypasses [`k8s_openapi`] entirely. /// If you need a `CustomResource` consider using `kube-derive` for its /// `#[derive(CustomResource)]` proc-macro. pub fn dynamic(kind: &str) -> DynamicResource { DynamicResource::new(kind) } } // ------------------------------------------------------- impl Resource { pub(crate) fn make_url(&self) -> String { let n = if let Some(ns) = &self.namespace { format!("namespaces/{}/", ns) } else { "".into() }; format!( "/{group}/{api_version}/{namespaces}{resource}", group = if self.group.is_empty() { "api" } else { "apis" }, api_version = self.api_version, namespaces = n, resource = to_plural(&self.kind.to_ascii_lowercase()), ) } } /// Convenience methods found from API conventions impl Resource { /// List a collection of a resource pub fn list(&self, lp: &ListParams) -> Result<http::Request<Vec<u8>>> { let base_url = self.make_url() + "?"; let mut qp = url::form_urlencoded::Serializer::new(base_url); if let Some(fields) = &lp.field_selector { qp.append_pair("fieldSelector", &fields); } if let Some(labels) = &lp.label_selector { qp.append_pair("labelSelector", &labels); } if let Some(limit) = &lp.limit { qp.append_pair("limit", &limit.to_string()); } if let Some(continue_token) = &lp.continue_token { qp.append_pair("continue", continue_token); } let urlstr = qp.finish(); let req = http::Request::get(urlstr); req.body(vec![]).map_err(Error::HttpError) } /// Watch a resource at a given version pub fn watch(&self, lp: &ListParams, ver: &str) -> Result<http::Request<Vec<u8>>> { let base_url = self.make_url() + "?"; let mut qp = url::form_urlencoded::Serializer::new(base_url); lp.validate()?; if lp.limit.is_some() { return Err(Error::RequestValidation( "ListParams::limit cannot be used with a watch.".into(), )); } if lp.continue_token.is_some() { return Err(Error::RequestValidation( "ListParams::continue_token cannot be used with a watch.".into(), )); } qp.append_pair("watch", "true"); qp.append_pair("resourceVersion", ver); // https://github.com/kubernetes/kubernetes/issues/6513 qp.append_pair("timeoutSeconds", &lp.timeout.unwrap_or(290).to_string()); if let Some(fields) = &lp.field_selector { qp.append_pair("fieldSelector", &fields); } if let Some(labels) = &lp.label_selector { qp.append_pair("labelSelector", &labels); } if lp.bookmarks { qp.append_pair("allowWatchBookmarks", "true"); } let urlstr = qp.finish(); let req = http::Request::get(urlstr); req.body(vec![]).map_err(Error::HttpError) } /// Get a single instance pub fn get(&self, name: &str) -> Result<http::Request<Vec<u8>>> { let base_url = self.make_url() + "/" + name; let mut qp = url::form_urlencoded::Serializer::new(base_url); let urlstr = qp.finish(); let req = http::Request::get(urlstr); req.body(vec![]).map_err(Error::HttpError) } /// Create an instance of a resource pub fn create(&self, pp: &PostParams, data: Vec<u8>) -> Result<http::Request<Vec<u8>>> { pp.validate()?; let base_url = self.make_url() + "?"; let mut qp = url::form_urlencoded::Serializer::new(base_url); if pp.dry_run { qp.append_pair("dryRun", "All"); } let urlstr = qp.finish(); let req = http::Request::post(urlstr); req.body(data).map_err(Error::HttpError) } /// Delete an instance of a resource pub fn delete(&self, name: &str, dp: &DeleteParams) -> Result<http::Request<Vec<u8>>> { let base_url = self.make_url() + "/" + name + "?"; let mut qp = url::form_urlencoded::Serializer::new(base_url); let urlstr = qp.finish(); let body = serde_json::to_vec(&dp)?; let req = http::Request::delete(urlstr); req.body(body).map_err(Error::HttpError) } /// Delete a collection of a resource pub fn delete_collection(&self, dp: &DeleteParams, lp: &ListParams) -> Result<http::Request<Vec<u8>>> { let base_url = self.make_url() + "?"; let mut qp = url::form_urlencoded::Serializer::new(base_url); if let Some(fields) = &lp.field_selector { qp.append_pair("fieldSelector", &fields); } if let Some(labels) = &lp.label_selector { qp.append_pair("labelSelector", &labels); } let urlstr = qp.finish(); let body = serde_json::to_vec(&dp)?; let req = http::Request::delete(urlstr); req.body(body).map_err(Error::HttpError) } /// Patch an instance of a resource /// /// Requires a serialized merge-patch+json at the moment. pub fn patch<P: serde::Serialize>( &self, name: &str, pp: &PatchParams, patch: &Patch<P>, ) -> Result<http::Request<Vec<u8>>> { pp.validate(patch)?; let base_url = self.make_url() + "/" + name + "?"; let mut qp = url::form_urlencoded::Serializer::new(base_url); pp.populate_qp(&mut qp); let urlstr = qp.finish(); http::Request::patch(urlstr) .header("Accept", "application/json") .header("Content-Type", patch.content_type()) .body(patch.serialize()?) .map_err(Error::HttpError) } /// Replace an instance of a resource /// /// Requires `metadata.resourceVersion` set in data pub fn replace(&self, name: &str, pp: &PostParams, data: Vec<u8>) -> Result<http::Request<Vec<u8>>> { let base_url = self.make_url() + "/" + name + "?"; let mut qp = url::form_urlencoded::Serializer::new(base_url); if pp.dry_run { qp.append_pair("dryRun", "All"); } let urlstr = qp.finish(); let req = http::Request::put(urlstr); req.body(data).map_err(Error::HttpError) } } /// Scale subresource impl Resource { /// Get an instance of the scale subresource pub fn get_scale(&self, name: &str) -> Result<http::Request<Vec<u8>>> { let base_url = self.make_url() + "/" + name + "/scale"; let mut qp = url::form_urlencoded::Serializer::new(base_url); let urlstr = qp.finish(); let req = http::Request::get(urlstr); req.body(vec![]).map_err(Error::HttpError) } /// Patch an instance of the scale subresource pub fn patch_scale<P: serde::Serialize>( &self, name: &str, pp: &PatchParams, patch: &Patch<P>, ) -> Result<http::Request<Vec<u8>>> { pp.validate(patch)?; let base_url = self.make_url() + "/" + name + "/scale?"; let mut qp = url::form_urlencoded::Serializer::new(base_url); pp.populate_qp(&mut qp); let urlstr = qp.finish(); http::Request::patch(urlstr) .header("Accept", "application/json") .header("Content-Type", patch.content_type()) .body(patch.serialize()?) .map_err(Error::HttpError) } /// Replace an instance of the scale subresource pub fn replace_scale( &self, name: &str, pp: &PostParams, data: Vec<u8>, ) -> Result<http::Request<Vec<u8>>> { let base_url = self.make_url() + "/" + name + "/scale?"; let mut qp = url::form_urlencoded::Serializer::new(base_url); if pp.dry_run { qp.append_pair("dryRun", "All"); } let urlstr = qp.finish(); let req = http::Request::put(urlstr); req.body(data).map_err(Error::HttpError) } } /// Status subresource impl Resource { /// Get an instance of the status subresource pub fn get_status(&self, name: &str) -> Result<http::Request<Vec<u8>>> { let base_url = self.make_url() + "/" + name + "/status"; let mut qp = url::form_urlencoded::Serializer::new(base_url); let urlstr = qp.finish(); let req = http::Request::get(urlstr); req.body(vec![]).map_err(Error::HttpError) } /// Patch an instance of the status subresource pub fn patch_status<P: serde::Serialize>( &self, name: &str, pp: &PatchParams, patch: &Patch<P>, ) -> Result<http::Request<Vec<u8>>> { pp.validate(patch)?; let base_url = self.make_url() + "/" + name + "/status?"; let mut qp = url::form_urlencoded::Serializer::new(base_url); pp.populate_qp(&mut qp); let urlstr = qp.finish(); http::Request::patch(urlstr) .header("Accept", "application/json") .header("Content-Type", patch.content_type()) .body(patch.serialize()?) .map_err(Error::HttpError) } /// Replace an instance of the status subresource pub fn replace_status( &self, name: &str, pp: &PostParams, data: Vec<u8>, ) -> Result<http::Request<Vec<u8>>> { let base_url = self.make_url() + "/" + name + "/status?"; let mut qp = url::form_urlencoded::Serializer::new(base_url); if pp.dry_run { qp.append_pair("dryRun", "All"); } let urlstr = qp.finish(); let req = http::Request::put(urlstr); req.body(data).map_err(Error::HttpError) } } // Simple pluralizer. Handles the special cases. fn to_plural(word: &str) -> String { if word == "endpoints" || word == "endpointslices" { return word.to_owned(); } else if word == "nodemetrics" { return "nodes".to_owned(); } else if word == "podmetrics" { return "pods".to_owned(); } // Words ending in s, x, z, ch, sh will be pluralized with -es (eg. foxes). if word.ends_with('s') || word.ends_with('x') || word.ends_with('z') || word.ends_with("ch") || word.ends_with("sh") { return format!("{}es", word); } // Words ending in y that are preceded by a consonant will be pluralized by // replacing y with -ies (eg. puppies). if word.ends_with('y') { if let Some(c) = word.chars().nth(word.len() - 2) { if !matches!(c, 'a' | 'e' | 'i' | 'o' | 'u') { // Remove 'y' and add `ies` let mut chars = word.chars(); chars.next_back(); return format!("{}ies", chars.as_str()); } } } // All other words will have "s" added to the end (eg. days). format!("{}s", word) } #[test] fn test_to_plural_native() { // Extracted from `swagger.json` #[rustfmt::skip] let native_kinds = vec![ ("APIService", "apiservices"), ("Binding", "bindings"), ("CertificateSigningRequest", "certificatesigningrequests"), ("ClusterRole", "clusterroles"), ("ClusterRoleBinding", "clusterrolebindings"), ("ComponentStatus", "componentstatuses"), ("ConfigMap", "configmaps"), ("ControllerRevision", "controllerrevisions"), ("CronJob", "cronjobs"), ("CSIDriver", "csidrivers"), ("CSINode", "csinodes"), ("CSIStorageCapacity", "csistoragecapacities"), ("CustomResourceDefinition", "customresourcedefinitions"), ("DaemonSet", "daemonsets"), ("Deployment", "deployments"), ("Endpoints", "endpoints"), ("EndpointSlice", "endpointslices"), ("Event", "events"), ("FlowSchema", "flowschemas"), ("HorizontalPodAutoscaler", "horizontalpodautoscalers"), ("Ingress", "ingresses"), ("IngressClass", "ingressclasses"), ("Job", "jobs"), ("Lease", "leases"), ("LimitRange", "limitranges"), ("LocalSubjectAccessReview", "localsubjectaccessreviews"), ("MutatingWebhookConfiguration", "mutatingwebhookconfigurations"), ("Namespace", "namespaces"), ("NetworkPolicy", "networkpolicies"), ("Node", "nodes"), ("PersistentVolumeClaim", "persistentvolumeclaims"), ("PersistentVolume", "persistentvolumes"), ("PodDisruptionBudget", "poddisruptionbudgets"), ("Pod", "pods"), ("PodSecurityPolicy", "podsecuritypolicies"), ("PodTemplate", "podtemplates"), ("PriorityClass", "priorityclasses"), ("PriorityLevelConfiguration", "prioritylevelconfigurations"), ("ReplicaSet", "replicasets"), ("ReplicationController", "replicationcontrollers"), ("ResourceQuota", "resourcequotas"), ("Role", "roles"), ("RoleBinding", "rolebindings"), ("RuntimeClass", "runtimeclasses"), ("Secret", "secrets"), ("SelfSubjectAccessReview", "selfsubjectaccessreviews"), ("SelfSubjectRulesReview", "selfsubjectrulesreviews"), ("ServiceAccount", "serviceaccounts"), ("Service", "services"), ("StatefulSet", "statefulsets"), ("StorageClass", "storageclasses"), ("StorageVersion", "storageversions"), ("SubjectAccessReview", "subjectaccessreviews"), ("TokenReview", "tokenreviews"), ("ValidatingWebhookConfiguration", "validatingwebhookconfigurations"), ("VolumeAttachment", "volumeattachments"), ]; for (kind, plural) in native_kinds { assert_eq!(to_plural(&kind.to_ascii_lowercase()), plural); } } /// Extensive tests for Resource::<k8s_openapi::Resource impls> /// /// Cheap sanity check to ensure type maps work as expected /// Only uses Resource::create to check the general url format. #[cfg(test)] mod test { use crate::api::{PostParams, Resource}; use k8s::{ admissionregistration::v1beta1 as adregv1beta1, apps::v1 as appsv1, authorization::v1 as authv1, autoscaling::v1 as autoscalingv1, batch::v1beta1 as batchv1beta1, core::v1 as corev1, extensions::v1beta1 as extsv1beta1, networking::{v1 as networkingv1, v1beta1 as networkingv1beta1}, rbac::v1 as rbacv1, storage::v1 as storagev1, }; use k8s_openapi::api as k8s; // use k8s::batch::v1 as batchv1; // NB: stable requires >= 1.17 use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1 as apiextsv1; // TODO: fixturize these tests // these are sanity tests for macros that create the Resource::v1Ctors #[test] fn api_url_secret() { let r = Resource::namespaced::<corev1::Secret>("ns"); let req = r.create(&PostParams::default(), vec![]).unwrap(); assert_eq!(req.uri(), "/api/v1/namespaces/ns/secrets?"); } #[test] fn api_url_rs() { let r = Resource::namespaced::<appsv1::ReplicaSet>("ns"); let req = r.create(&PostParams::default(), vec![]).unwrap(); assert_eq!(req.uri(), "/apis/apps/v1/namespaces/ns/replicasets?"); } #[test] fn api_url_role() { let r = Resource::namespaced::<rbacv1::Role>("ns"); let req = r.create(&PostParams::default(), vec![]).unwrap(); assert_eq!( req.uri(), "/apis/rbac.authorization.k8s.io/v1/namespaces/ns/roles?" ); } #[test] fn api_url_cj() { let r = Resource::namespaced::<batchv1beta1::CronJob>("ns"); let req = r.create(&PostParams::default(), vec![]).unwrap(); assert_eq!(req.uri(), "/apis/batch/v1beta1/namespaces/ns/cronjobs?"); } #[test] fn api_url_hpa() { let r = Resource::namespaced::<autoscalingv1::HorizontalPodAutoscaler>("ns"); let req = r.create(&PostParams::default(), vec![]).unwrap(); assert_eq!( req.uri(), "/apis/autoscaling/v1/namespaces/ns/horizontalpodautoscalers?" ); } #[test] fn api_url_np() { let r = Resource::namespaced::<networkingv1::NetworkPolicy>("ns"); let req = r.create(&PostParams::default(), vec![]).unwrap(); assert_eq!( req.uri(), "/apis/networking.k8s.io/v1/namespaces/ns/networkpolicies?" ); } #[test] fn api_url_ingress() { let r = Resource::namespaced::<extsv1beta1::Ingress>("ns"); let req = r.create(&PostParams::default(), vec![]).unwrap(); assert_eq!(req.uri(), "/apis/extensions/v1beta1/namespaces/ns/ingresses?"); } #[test] fn api_url_vattach() { let r = Resource::all::<storagev1::VolumeAttachment>(); let req = r.create(&PostParams::default(), vec![]).unwrap(); assert_eq!(req.uri(), "/apis/storage.k8s.io/v1/volumeattachments?"); } #[test] fn api_url_admission() { let r = Resource::all::<adregv1beta1::ValidatingWebhookConfiguration>(); let req = r.create(&PostParams::default(), vec![]).unwrap(); assert_eq!( req.uri(), "/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations?" ); } #[test] fn api_auth_selfreview() { let r = Resource::all::<authv1::SelfSubjectRulesReview>(); assert_eq!(r.group, "authorization.k8s.io"); assert_eq!(r.kind, "SelfSubjectRulesReview"); let req = r.create(&PostParams::default(), vec![]).unwrap(); assert_eq!( req.uri(), "/apis/authorization.k8s.io/v1/selfsubjectrulesreviews?" ); } #[test] fn api_apiextsv1_crd() { let r = Resource::all::<apiextsv1::CustomResourceDefinition>(); let req = r.create(&PostParams::default(), vec![]).unwrap(); assert_eq!( req.uri(), "/apis/apiextensions.k8s.io/v1/customresourcedefinitions?" ); } /// ----------------------------------------------------------------- /// Tests that the misc mappings are also sensible use crate::api::{DeleteParams, ListParams, Patch, PatchParams}; use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1beta1 as apiextsv1beta1; #[test] fn list_path() { let r = Resource::namespaced::<appsv1::Deployment>("ns"); let gp = ListParams::default(); let req = r.list(&gp).unwrap(); assert_eq!(req.uri(), "/apis/apps/v1/namespaces/ns/deployments"); } #[test] fn watch_path() { let r = Resource::namespaced::<corev1::Pod>("ns"); let gp = ListParams::default(); let req = r.watch(&gp, "0").unwrap(); assert_eq!( req.uri(), "/api/v1/namespaces/ns/pods?&watch=true&resourceVersion=0&timeoutSeconds=290&allowWatchBookmarks=true" ); } #[test] fn replace_path() { let r = Resource::all::<appsv1::DaemonSet>(); let pp = PostParams { dry_run: true, ..Default::default() }; let req = r.replace("myds", &pp, vec![]).unwrap(); assert_eq!(req.uri(), "/apis/apps/v1/daemonsets/myds?&dryRun=All"); } #[test] fn delete_path() { let r = Resource::namespaced::<appsv1::ReplicaSet>("ns"); let dp = DeleteParams::default(); let req = r.delete("myrs", &dp).unwrap(); assert_eq!(req.uri(), "/apis/apps/v1/namespaces/ns/replicasets/myrs"); assert_eq!(req.method(), "DELETE") } #[test] fn delete_collection_path() { let r = Resource::namespaced::<appsv1::ReplicaSet>("ns"); let lp = ListParams::default(); let dp = DeleteParams::default(); let req = r.delete_collection(&dp, &lp).unwrap(); assert_eq!(req.uri(), "/apis/apps/v1/namespaces/ns/replicasets"); assert_eq!(req.method(), "DELETE") } #[test] fn namespace_path() { let r = Resource::all::<corev1::Namespace>(); let gp = ListParams::default(); let req = r.list(&gp).unwrap(); assert_eq!(req.uri(), "/api/v1/namespaces") } // subresources with weird version accuracy #[test] fn patch_status_path() { let r = Resource::all::<corev1::Node>(); let pp = PatchParams::default(); let req = r.patch_status("mynode", &pp, &Patch::Merge(())).unwrap(); assert_eq!(req.uri(), "/api/v1/nodes/mynode/status?"); assert_eq!( req.headers().get("Content-Type").unwrap().to_str().unwrap(), Patch::Merge(()).content_type() ); assert_eq!(req.method(), "PATCH"); } #[test] fn replace_status_path() { let r = Resource::all::<corev1::Node>(); let pp = PostParams::default(); let req = r.replace_status("mynode", &pp, vec![]).unwrap(); assert_eq!(req.uri(), "/api/v1/nodes/mynode/status?"); assert_eq!(req.method(), "PUT"); } #[test] fn create_ingress() { // NB: Ingress exists in extensions AND networking let r = Resource::namespaced::<networkingv1beta1::Ingress>("ns"); let pp = PostParams::default(); let req = r.create(&pp, vec![]).unwrap(); assert_eq!( req.uri(), "/apis/networking.k8s.io/v1beta1/namespaces/ns/ingresses?" ); let patch_params = PatchParams::default(); let req = r.patch("baz", &patch_params, &Patch::Merge(())).unwrap(); assert_eq!( req.uri(), "/apis/networking.k8s.io/v1beta1/namespaces/ns/ingresses/baz?" ); assert_eq!(req.method(), "PATCH"); } #[test] fn replace_status() { let r = Resource::all::<apiextsv1beta1::CustomResourceDefinition>(); let pp = PostParams::default(); let req = r.replace_status("mycrd.domain.io", &pp, vec![]).unwrap(); assert_eq!( req.uri(), "/apis/apiextensions.k8s.io/v1beta1/customresourcedefinitions/mycrd.domain.io/status?" ); } #[test] fn get_scale_path() { let r = Resource::all::<corev1::Node>(); let req = r.get_scale("mynode").unwrap(); assert_eq!(req.uri(), "/api/v1/nodes/mynode/scale"); assert_eq!(req.method(), "GET"); } #[test] fn patch_scale_path() { let r = Resource::all::<corev1::Node>(); let pp = PatchParams::default(); let req = r.patch_scale("mynode", &pp, &Patch::Merge(())).unwrap(); assert_eq!(req.uri(), "/api/v1/nodes/mynode/scale?"); assert_eq!(req.method(), "PATCH"); } #[test] fn replace_scale_path() { let r = Resource::all::<corev1::Node>(); let pp = PostParams::default(); let req = r.replace_scale("mynode", &pp, vec![]).unwrap(); assert_eq!(req.uri(), "/api/v1/nodes/mynode/scale?"); assert_eq!(req.method(), "PUT"); } #[test] #[should_panic] fn all_resources_not_namespaceable() { Resource::namespaced::<corev1::Node>("ns"); } }
36.037448
114
0.572028
d9ec9cc9b5709842f7a36f3c3221d526918900a3
2,686
use liturgy::{Psalm, PsalmSection, PsalmVerse, Reference, Source}; lazy_static! { pub static ref PSALM_12: Psalm = Psalm { number: 12, citation: None, sections: vec![PsalmSection { reference: Reference { source: Source::BCP1979, page: 597 }, local_name: String::from("Psalm 12"), latin_name: String::from("Salvum me fac"), verses: vec![ PsalmVerse { number: 1, a: String::from("Help me, LORD, for there is no godly one left; *"), b: String::from("the faithful have vanished from among us.") }, PsalmVerse { number: 2, a: String::from("Everyone speaks falsely with his neighbor; *"), b: String::from("with a smooth tongue they speak from a double heart.") }, PsalmVerse { number: 3, a: String::from("Oh, that the LORD would cut off all smooth tongues, *"), b: String::from("and close the lips that utter proud boasts!") }, PsalmVerse { number: 4, a: String::from("Those who say, “With our tongue will we prevail; *"), b: String::from("our lips are our own; who is lord over us?”") }, PsalmVerse { number: 5, a: String::from( "“Because the needy are oppressed,\nand the poor cry out in misery, *" ), b: String::from( "I will rise up,” says the LORD,\n “and give them the help they long for.”" ) }, PsalmVerse { number: 6, a: String::from("The words of the LORD are pure words, *"), b: String::from( "like silver refined from ore\n and purified seven times in the fire." ) }, PsalmVerse { number: 7, a: String::from("O LORD, watch over us *"), b: String::from("and save us from this generation for ever.") }, PsalmVerse { number: 8, a: String::from("The wicked prowl on every side, *"), b: String::from("and that which is worthless is highly prized by everyone.") }, ] }] }; }
41.96875
99
0.431124
9c7784844877307dcd2963a817be2e4092210dd7
1,887
//! https://cloud.google.com/vision/docs/reference/rest/v1/ImageContext use serde::{Deserialize, Serialize}; use crate::{ shared_types::LatLng, v1::resources::projects_locations_products_reference_images::BoundingPoly, }; #[derive(Serialize, Deserialize, Debug, Clone, Default)] #[serde(rename_all = "camelCase")] pub struct ImageContext { #[serde(skip_serializing_if = "Option::is_none")] pub lat_long_rect: Option<LatLongRect>, #[serde(skip_serializing_if = "Option::is_none")] pub language_hints: Option<Vec<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub crop_hints_params: Option<CropHintsParams>, #[serde(skip_serializing_if = "Option::is_none")] pub product_search_params: Option<ProductSearchParams>, #[serde(skip_serializing_if = "Option::is_none")] pub web_detection_params: Option<WebDetectionParams>, #[serde(skip_serializing_if = "Option::is_none")] pub text_detection_params: Option<TextDetectionParams>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct LatLongRect { pub min_lat_lng: LatLng, pub max_lat_lng: LatLng, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct CropHintsParams { pub aspect_ratios: Vec<isize>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct ProductSearchParams { pub bounding_poly: BoundingPoly, pub product_set: String, pub product_categories: Vec<String>, pub filter: String, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct WebDetectionParams { pub include_geo_results: bool, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(rename_all = "camelCase")] pub struct TextDetectionParams { pub enable_text_detection_confidence_score: bool, }
31.983051
100
0.738209
7a5d71ee21b93e16961a60171ba94d80cba525dd
2,225
// Copyright 2017 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. // compile-flags: -Z identify_regions -Z span_free_formats -Z emit-end-regions // Unwinding should EndRegion for in-scope borrows: Borrowing via by-ref closure. fn main() { let d = D(0); foo(|| -> i32 { d.0 }); } struct D(i32); impl Drop for D { fn drop(&mut self) { println!("dropping D({})", self.0); } } fn foo<F>(f: F) where F: FnOnce() -> i32 { if f() > 0 { panic!("im positive"); } } // END RUST SOURCE // START rustc.main.SimplifyCfg-qualify-consts.after.mir // fn main() -> () { // ... // let mut _0: (); // ... // let _1: D; // ... // let mut _2: (); // let mut _3: [closure@NodeId(18) d:&'14s D]; // let mut _4: &'14s D; // bb0: { // StorageLive(_1); // _1 = D::{{constructor}}(const 0i32,); // FakeRead(ForLet, _1); // StorageLive(_3); // StorageLive(_4); // _4 = &'14s _1; // _3 = [closure@NodeId(18)] { d: move _4 }; // StorageDead(_4); // _2 = const foo(move _3) -> [return: bb2, unwind: bb3]; // } // bb1: { // resume; // } // bb2: { // EndRegion('14s); // StorageDead(_3); // _0 = (); // drop(_1) -> [return: bb4, unwind: bb1]; // } // bb3: { // EndRegion('14s); // drop(_1) -> bb1; // } // bb4: { // StorageDead(_1); // return; // } // } // END rustc.main.SimplifyCfg-qualify-consts.after.mir // START rustc.main-{{closure}}.SimplifyCfg-qualify-consts.after.mir // fn main::{{closure}}(_1: [closure@NodeId(18) d:&'14s D]) -> i32 { // let mut _0: i32; // // bb0: { // _0 = ((*(_1.0: &'14s D)).0: i32); // return; // } // END rustc.main-{{closure}}.SimplifyCfg-qualify-consts.after.mir
28.525641
81
0.542472
2130ff1e4b106b0ad294b84b4ec443d1d4806264
2,475
// This file is part of Substrate. // Copyright (C) 2018-2020 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. use sc_cli::{RunCmd, KeySubcommand, SignCmd, VanityCmd, VerifyCmd}; use structopt::StructOpt; /// An overarching CLI command definition. #[derive(Debug, StructOpt)] pub struct Cli { /// Possible subcommand with parameters. #[structopt(subcommand)] pub subcommand: Option<Subcommand>, #[allow(missing_docs)] #[structopt(flatten)] pub run: RunCmd, } /// Possible subcommands of the main binary. #[derive(Debug, StructOpt)] pub enum Subcommand { /// Key management cli utilities Key(KeySubcommand), /// The custom inspect subcommmand for decoding blocks and extrinsics. #[structopt( name = "inspect", about = "Decode given block or extrinsic using current native runtime." )] Inspect(node_inspect::cli::InspectCmd), /// The custom benchmark subcommmand benchmarking runtime pallets. #[structopt(name = "benchmark", about = "Benchmark runtime pallets.")] Benchmark(frame_benchmarking_cli::BenchmarkCmd), /// Verify a signature for a message, provided on STDIN, with a given (public or secret) key. Verify(VerifyCmd), /// Generate a seed that provides a vanity address. Vanity(VanityCmd), /// Sign a message, with a given (secret) key. Sign(SignCmd), /// Build a chain specification. BuildSpec(sc_cli::BuildSpecCmd), /// Validate blocks. CheckBlock(sc_cli::CheckBlockCmd), /// Export blocks. ExportBlocks(sc_cli::ExportBlocksCmd), /// Export the state of a given block into a chain spec. ExportState(sc_cli::ExportStateCmd), /// Import blocks. ImportBlocks(sc_cli::ImportBlocksCmd), /// Remove the whole chain. PurgeChain(sc_cli::PurgeChainCmd), /// Revert the chain to a previous state. Revert(sc_cli::RevertCmd), }
30.9375
94
0.741414
f9a723314569d7a778d9febb8696b302a2ed2e18
201
mod connection; mod error; mod message; mod stdio; pub use connection::Connection; pub use error::ProtocolError; pub use message::{Message, Notification, Request, RequestId, Response, ResponseError};
22.333333
86
0.78607
6149a27fc30cdd956128bd902cb2774fe2902368
655
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{CanonicalAddr, StdResult, Storage}; use cosmwasm_storage::{singleton, singleton_read}; static KEY_CONFIG: &[u8] = b"richard_config"; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct Config { pub owner: CanonicalAddr, pub currency: CanonicalAddr, pub count: u32, } pub fn store_config(storage: &mut dyn Storage, config: &Config) -> StdResult<()> { singleton(storage, KEY_CONFIG).save(config) } pub fn read_config(storage: &dyn Storage) -> StdResult<Config> { singleton_read(storage, KEY_CONFIG).load() }
28.478261
82
0.719084
e63a1a9134f3484b1dbd307ceafec384db68d81e
8,439
#![allow(non_snake_case, non_upper_case_globals)] #![allow(non_camel_case_types)] //! KPP Registers //! //! Used by: imxrt1011, imxrt1015 use crate::RWRegister; #[cfg(not(feature = "nosync"))] use core::marker::PhantomData; /// Keypad Control Register pub mod KPCR { /// Keypad Row Enable pub mod KRE { /// Offset (0 bits) pub const offset: u16 = 0; /// Mask (8 bits: 0xff << 0) pub const mask: u16 = 0xff << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values pub mod RW { /// 0b00000000: Row is not included in the keypad key press detect. pub const KRE_0: u16 = 0b00000000; /// 0b00000001: Row is included in the keypad key press detect. pub const KRE_1: u16 = 0b00000001; } } /// Keypad Column Strobe Open-Drain Enable pub mod KCO { /// Offset (8 bits) pub const offset: u16 = 8; /// Mask (8 bits: 0xff << 8) pub const mask: u16 = 0xff << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values pub mod RW { /// 0b00000000: Column strobe output is totem pole drive. pub const TOTEM_POLE: u16 = 0b00000000; /// 0b00000001: Column strobe output is open drain. pub const OPEN_DRAIN: u16 = 0b00000001; } } } /// Keypad Status Register pub mod KPSR { /// Keypad Key Depress pub mod KPKD { /// Offset (0 bits) pub const offset: u16 = 0; /// Mask (1 bit: 1 << 0) pub const mask: u16 = 1 << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values pub mod RW { /// 0b0: No key presses detected pub const KPKD_0: u16 = 0b0; /// 0b1: A key has been depressed pub const KPKD_1: u16 = 0b1; } } /// Keypad Key Release pub mod KPKR { /// Offset (1 bits) pub const offset: u16 = 1; /// Mask (1 bit: 1 << 1) pub const mask: u16 = 1 << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values pub mod RW { /// 0b0: No key release detected pub const KPKR_0: u16 = 0b0; /// 0b1: All keys have been released pub const KPKR_1: u16 = 0b1; } } /// Key Depress Synchronizer Clear pub mod KDSC { /// Offset (2 bits) pub const offset: u16 = 2; /// Mask (1 bit: 1 << 2) pub const mask: u16 = 1 << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values pub mod RW { /// 0b0: No effect pub const KDSC_0: u16 = 0b0; /// 0b1: Set bits that clear the keypad depress synchronizer chain pub const KDSC_1: u16 = 0b1; } } /// Key Release Synchronizer Set pub mod KRSS { /// Offset (3 bits) pub const offset: u16 = 3; /// Mask (1 bit: 1 << 3) pub const mask: u16 = 1 << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values pub mod RW { /// 0b0: No effect pub const KRSS_0: u16 = 0b0; /// 0b1: Set bits which sets keypad release synchronizer chain pub const KRSS_1: u16 = 0b1; } } /// Keypad Key Depress Interrupt Enable pub mod KDIE { /// Offset (8 bits) pub const offset: u16 = 8; /// Mask (1 bit: 1 << 8) pub const mask: u16 = 1 << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values pub mod RW { /// 0b0: No interrupt request is generated when KPKD is set. pub const KDIE_0: u16 = 0b0; /// 0b1: An interrupt request is generated when KPKD is set. pub const KDIE_1: u16 = 0b1; } } /// Keypad Release Interrupt Enable pub mod KRIE { /// Offset (9 bits) pub const offset: u16 = 9; /// Mask (1 bit: 1 << 9) pub const mask: u16 = 1 << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values pub mod RW { /// 0b0: No interrupt request is generated when KPKR is set. pub const KRIE_0: u16 = 0b0; /// 0b1: An interrupt request is generated when KPKR is set. pub const KRIE_1: u16 = 0b1; } } } /// Keypad Data Direction Register pub mod KDDR { /// Keypad Row Data Direction pub mod KRDD { /// Offset (0 bits) pub const offset: u16 = 0; /// Mask (8 bits: 0xff << 0) pub const mask: u16 = 0xff << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values pub mod RW { /// 0b00000000: ROWn pin configured as an input. pub const INPUT: u16 = 0b00000000; /// 0b00000001: ROWn pin configured as an output. pub const OUTPUT: u16 = 0b00000001; } } /// Keypad Column Data Direction Register pub mod KCDD { /// Offset (8 bits) pub const offset: u16 = 8; /// Mask (8 bits: 0xff << 8) pub const mask: u16 = 0xff << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values pub mod RW { /// 0b00000000: COLn pin is configured as an input. pub const INPUT: u16 = 0b00000000; /// 0b00000001: COLn pin is configured as an output. pub const OUTPUT: u16 = 0b00000001; } } } /// Keypad Data Register pub mod KPDR { /// Keypad Row Data pub mod KRD { /// Offset (0 bits) pub const offset: u16 = 0; /// Mask (8 bits: 0xff << 0) pub const mask: u16 = 0xff << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values (empty) pub mod RW {} } /// Keypad Column Data pub mod KCD { /// Offset (8 bits) pub const offset: u16 = 8; /// Mask (8 bits: 0xff << 8) pub const mask: u16 = 0xff << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values (empty) pub mod RW {} } } #[repr(C)] pub struct RegisterBlock { /// Keypad Control Register pub KPCR: RWRegister<u16>, /// Keypad Status Register pub KPSR: RWRegister<u16>, /// Keypad Data Direction Register pub KDDR: RWRegister<u16>, /// Keypad Data Register pub KPDR: RWRegister<u16>, } pub struct ResetValues { pub KPCR: u16, pub KPSR: u16, pub KDDR: u16, pub KPDR: u16, } #[cfg(not(feature = "nosync"))] pub struct Instance { pub(crate) addr: u32, pub(crate) _marker: PhantomData<*const RegisterBlock>, pub(crate) intrs: &'static [crate::Interrupt], } #[cfg(not(feature = "nosync"))] impl ::core::ops::Deref for Instance { type Target = RegisterBlock; #[inline(always)] fn deref(&self) -> &RegisterBlock { unsafe { &*(self.addr as *const _) } } } #[cfg(not(feature = "nosync"))] unsafe impl Send for Instance {} #[cfg(not(feature = "nosync"))] impl Instance { /// Return the interrupt signals associated with this /// peripheral instance /// /// Collection may be empty if there is no interrupt signal /// associated with the peripheral. There's no guarantee for /// interrupt signal ordering in the collection. #[inline(always)] pub const fn interrupts<'a>(&'a self) -> &'a [crate::Interrupt] { self.intrs } }
26.790476
79
0.521744
ed0682098745d5804b4b1841d9db835df262b8d7
4,512
// crypto_generichash.h pub const crypto_generichash_BYTES_MIN: usize = crypto_generichash_blake2b_BYTES_MIN; pub const crypto_generichash_BYTES_MAX: usize = crypto_generichash_blake2b_BYTES_MAX; pub const crypto_generichash_BYTES: usize = crypto_generichash_blake2b_BYTES; pub const crypto_generichash_KEYBYTES_MIN: usize = crypto_generichash_blake2b_KEYBYTES_MIN; pub const crypto_generichash_KEYBYTES_MAX: usize = crypto_generichash_blake2b_KEYBYTES_MAX; pub const crypto_generichash_KEYBYTES: usize = crypto_generichash_blake2b_KEYBYTES; pub const crypto_generichash_PRIMITIVE: &'static str = "blake2b"; #[allow(non_camel_case_types)] pub enum crypto_generichash_state { } extern { pub fn crypto_generichash_bytes_min() -> size_t; pub fn crypto_generichash_bytes_max() -> size_t; pub fn crypto_generichash_bytes() -> size_t; pub fn crypto_generichash_keybytes_min() -> size_t; pub fn crypto_generichash_keybytes_max() -> size_t; pub fn crypto_generichash_keybytes() -> size_t; pub fn crypto_generichash_primitive() -> *const c_char; pub fn crypto_generichash( out: *mut u8, outlen: size_t, in_: *const u8, inlen: c_ulonglong, key: *const u8, keylen: size_t) -> c_int; pub fn crypto_generichash_init( state: *mut crypto_generichash_state, key: *const u8, keylen: size_t, outlen: size_t) -> c_int; pub fn crypto_generichash_update( state: *mut crypto_generichash_state, in_: *const u8, inlen: c_ulonglong) -> c_int; pub fn crypto_generichash_final( state: *mut crypto_generichash_state, out: *mut u8, outlen: size_t) -> c_int; pub fn crypto_generichash_statebytes() -> size_t; } #[test] fn test_crypto_generichash_bytes_min() { assert_eq!(unsafe { crypto_generichash_bytes_min() as usize }, crypto_generichash_BYTES_MIN) } #[test] fn test_crypto_generichash_bytes_max() { assert_eq!(unsafe { crypto_generichash_bytes_max() as usize }, crypto_generichash_BYTES_MAX) } #[test] fn test_crypto_generichash_bytes() { assert_eq!(unsafe { crypto_generichash_bytes() as usize }, crypto_generichash_BYTES) } #[test] fn test_crypto_generichash_keybytes_min() { assert_eq!(unsafe { crypto_generichash_keybytes_min() as usize }, crypto_generichash_KEYBYTES_MIN) } #[test] fn test_crypto_generichash_keybytes_max() { assert_eq!(unsafe { crypto_generichash_keybytes_max() as usize }, crypto_generichash_KEYBYTES_MAX) } #[test] fn test_crypto_generichash_keybytes() { assert_eq!(unsafe { crypto_generichash_keybytes() as usize }, crypto_generichash_KEYBYTES) } #[test] fn test_crypto_generichash_primitive() { unsafe { let s = crypto_generichash_primitive(); let s = std::ffi::CStr::from_ptr(s).to_bytes(); assert_eq!(s, crypto_generichash_PRIMITIVE.as_bytes()); } } #[test] fn test_crypto_generichash_statebytes() { assert!(unsafe { crypto_generichash_statebytes() } > 0); } #[test] fn test_crypto_generichash() { let mut out = [0u8; crypto_generichash_BYTES]; let m = [0u8; 64]; let key = [0u8; crypto_generichash_KEYBYTES]; assert_eq!(unsafe { crypto_generichash(out.as_mut_ptr(), out.len(), m.as_ptr(), m.len() as u64, key.as_ptr(), key.len()) }, 0); } #[cfg(test)] use std::mem; #[test] fn test_crypto_generichash_multipart() { let mut out = [0u8; crypto_generichash_BYTES]; let m = [0u8; 64]; let key = [0u8; crypto_generichash_KEYBYTES]; let mut st = vec![0u8; (unsafe { crypto_generichash_statebytes() })]; let pst = unsafe { mem::transmute::<*mut u8, *mut crypto_generichash_state>(st.as_mut_ptr()) }; assert_eq!(unsafe { crypto_generichash_init(pst, key.as_ptr(), key.len(), out.len()) }, 0); assert_eq!(unsafe { crypto_generichash_update(pst, m.as_ptr(), m.len() as u64) }, 0); assert_eq!(unsafe { crypto_generichash_update(pst, m.as_ptr(), m.len() as u64) }, 0); assert_eq!(unsafe { crypto_generichash_final(pst, out.as_mut_ptr(), out.len()) }, 0); }
30.281879
99
0.647828
ff2d433c5a26ea19a9c7e24aa291a1a12bf04eae
1,937
use bip39lib::{Language, Mnemonic}; use bitcoin::{secp256k1, util::bip32, Network}; use serde::{Deserialize, Serialize}; #[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)] pub struct MnemonicInfo { pub mnemonic: String, pub entropy: ::HexBytes, pub entropy_bits: usize, pub language: &'static str, pub passphrase: String, pub seed: SeedInfo, } impl MnemonicInfo { pub fn from_mnemonic_with_passphrase( mnemonic: &Mnemonic, passphrase: &str, network: Network, ) -> MnemonicInfo { let entropy: Vec<u8> = mnemonic.to_entropy().into(); MnemonicInfo { mnemonic: mnemonic.to_string(), entropy_bits: entropy.len() * 8, entropy: entropy.into(), language: match mnemonic.language() { Language::English => "english", Language::Czech => "czech", Language::French => "french", Language::Italian => "italian", Language::Japanese => "japanese", Language::Korean => "korean", Language::Spanish => "spanish", Language::SimplifiedChinese => "simplified-chinese", Language::TraditionalChinese => "traditional-chinese", }, passphrase: passphrase.to_owned(), seed: ::GetInfo::get_info(&mnemonic.to_seed(passphrase), network), } } } impl ::GetInfo<MnemonicInfo> for Mnemonic { fn get_info(&self, network: Network) -> MnemonicInfo { MnemonicInfo::from_mnemonic_with_passphrase(self, "", network) } } #[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)] pub struct SeedInfo { pub seed: ::HexBytes, pub bip32_xpriv: bip32::ExtendedPrivKey, pub bip32_xpub: bip32::ExtendedPubKey, } impl ::GetInfo<SeedInfo> for [u8; 64] { fn get_info(&self, network: Network) -> SeedInfo { let xpriv = bip32::ExtendedPrivKey::new_master(network, &self[..]).unwrap(); let xpub = bip32::ExtendedPubKey::from_private(&secp256k1::Secp256k1::signing_only(), &xpriv); SeedInfo { seed: self.to_vec().into(), bip32_xpriv: xpriv, bip32_xpub: xpub, } } }
28.485294
86
0.694889
fb4734d85e2ab3f2940399f29397005d08daf214
8,009
use std::{iter, rc::Rc}; use search_state::{SearchOptions, SearchSelected}; use dominator_helpers::futures::AsyncLoader; use futures_signals::{signal::Mutable, signal_vec::MutableVec}; use shared::domain::jig::{JigResponse, JigId, JigSearchQuery}; mod search_state; pub struct State { pub loader: AsyncLoader, pub mode: Mutable<HomePageMode>, pub is_logged_in: Mutable<bool>, pub search_options: SearchOptions, pub search_selected: SearchSelected, pub quick_searches: Vec<QuickSearch>, pub whats_new: Vec<WhatsNewItem>, pub parents_testimonials: Vec<Testimonial>, pub teachers_testimonials: Vec<Testimonial>, pub total_jigs_count: Mutable<u64>, pub play_jig: Mutable<Option<JigId>>, } impl State { pub fn new() -> Self { Self::new_with_search_selected(SearchSelected::new()) } pub fn new_search(query_params: Option<JigSearchQuery>) -> Self { let search_selected = match query_params { Some(query_params) => SearchSelected::from_search_request(query_params), None => SearchSelected::new(), }; Self::new_with_search_selected(search_selected) } fn new_with_search_selected(search_selected: SearchSelected) -> Self { Self { search_selected, loader: AsyncLoader::new(), mode: Mutable::new(HomePageMode::Home), is_logged_in: Mutable::new(false), search_options: SearchOptions::new(), quick_searches: Self::get_quick_searches(), whats_new: Self::get_whats_new(), parents_testimonials: Self::get_parents_testimonials(), teachers_testimonials: Self::get_teachers_testimonials(), total_jigs_count: Mutable::new(0), play_jig: Mutable::new(None), } } fn get_quick_searches() -> Vec<QuickSearch> { vec![ QuickSearch { search_term: String::from("Hebrew"), }, QuickSearch { search_term: String::from("Tishrei"), }, QuickSearch { search_term: String::from("Chanukah"), }, QuickSearch { search_term: String::from("Israel"), }, ] } fn get_whats_new() -> Vec<WhatsNewItem> { iter::repeat(WhatsNewItem { image_id: String::from("something.jpg"), image_lib: String::from("mock"), header: String::from("HOP TV - New Hebrew Series"), paragraph: String::from("Learning Hebrew with HOP Channel, Learning Hebrew with HOP Channel, Learning Hebrew with HOP Channel, Learning Hebrew with HOP Channel Learning Hebrew with HOP"), link: String::from(""), }).take(3).collect() } fn get_parents_testimonials() -> Vec<Testimonial> { vec![ Testimonial { image_id: String::from("orly-rachamim.jpg"), name: String::from("Orly Rachamim"), bio: String::from("Netivot HaTorah Day School, Ontario, Canada"), paragraph: String::from("Having the ability to search for and download games and activities in addition to creating your own and sharing it in the platform is a great crowd-sourcing opportunity. Using the rich creation packs as well as interactive layers helps enhance the learning experience for students by bringing the material to life."), }, Testimonial { image_id: String::from("liat-walker.png"), name: String::from("Liat Walker"), bio: String::from("Jewish Studies Coordinator, Martin J Gottlieb Day School, FL, USA"), paragraph: String::from("I use Ji as a way to enrich the students’ Jewish knowledge and experience. The lessons and images include every contemporary subject in the Jewish world and Israel and is an excellent way for our students to feel connected to their Jewish identity. Before Ji this kind of information would be found in a book or on an Internet site, which is geared for adults. In my opinion, there is no kid-friendly space for our students to learn about Jewish contemporary topics other than Ji."), }, Testimonial { image_id: String::from("jonathon-simons.png"), name: String::from("Jonathon Simons"), bio: String::from("Broughton Jewish, Manchester, UK"), paragraph: String::from("In the last three months, I have found that I have been able to get 100% engagement from students and have been able to improve their grades."), }, Testimonial { image_id: String::from("dana-cappel.png"), name: String::from("Dana Cappel"), bio: String::from("Beit Issie Shapiro, Israel"), paragraph: String::from("Ji is a fantastic resource for our students. The fact that I can create customized activities for my students means that I can create activities in exactly the way that they need them to be so that they can learn and participate to their maximum potential."), }, ] } fn get_teachers_testimonials() -> Vec<Testimonial> { vec![ Testimonial { image_id: String::from("rabbi-yakov-shafferman.png"), name: String::from("Rabbi Yakov Shafferman"), bio: String::from("Jesode Hatorah, Antwerp, Belgium"), paragraph: String::from("I think this tool is going to be very, very useful for our school for many different subjects. We’re teaching Hebrew and other traditional subjects like Chumash and Gemarah. We can use it for teaching itself and for assessing the students. I’m looking forward to enhancing Jewish learning in our school with Ji."), }, Testimonial { image_id: String::from("rabbi-hiller.jpg"), name: String::from("Rabbi Hersh Hiller"), bio: String::from("Yeshiva Elementary, Milwaukee"), paragraph: String::from("Yesterday, I tried the Tu’Bishvat app with our iPads. It was amazing! The 17 kids were super-engaged. You have to imagine five students with their heads packed tightly against each other in a tight circle hovering over the glow of the iPad on the floor. Thank you for all the work that you put into to make an amazing program that I could use my classroom."), }, Testimonial { image_id: String::from("adina-levin.png"), name: String::from("Adina Levin"), bio: String::from("Hillel Day School, Detroit, USA"), paragraph: String::from("I’m amazed with what is finally, finally available for the Jewish Studies teachers. I always was jealous of the English teachers, that have so much material, and so much sources, and we as the Judaic Studies teachers are always trying to create our own material and come up with innovations."), }, Testimonial { image_id: String::from("rabbi-moshe-rosenberg.jpg"), name: String::from("Rabbi Moshe Rosenberg"), bio: String::from("SAR Academy, NY"), paragraph: String::from("What sets your products apart is that you do not compromise on either the substance or the style. You have both the truly professional look and true content."), }, ] } } #[derive(Clone)] pub enum HomePageMode { Home, Search(String, Rc<MutableVec<JigResponse>>), } #[derive(Clone)] pub struct QuickSearch { pub search_term: String, } #[derive(Clone)] pub struct WhatsNewItem { pub image_id: String, pub image_lib: String, // is this always the same? pub header: String, pub paragraph: String, pub link: String, } #[derive(Clone)] pub struct Testimonial { pub image_id: String, pub name: String, pub bio: String, pub paragraph: String, }
48.835366
524
0.636284
4aee97bb2b8b0a1f728158014585297123ca9557
12,113
//! This file contains code for parsing SSR rules, which look something like `foo($a) ==>> bar($b)`. //! We first split everything before and after the separator `==>>`. Next, both the search pattern //! and the replacement template get tokenized by the Rust tokenizer. Tokens are then searched for //! placeholders, which start with `$`. For replacement templates, this is the final form. For //! search patterns, we go further and parse the pattern as each kind of thing that we can match. //! e.g. expressions, type references etc. use crate::errors::bail; use crate::{SsrError, SsrPattern, SsrRule}; use ra_syntax::{ast, AstNode, SmolStr, SyntaxKind, T}; use rustc_hash::{FxHashMap, FxHashSet}; use std::str::FromStr; #[derive(Clone, Debug)] pub(crate) struct SsrTemplate { pub(crate) tokens: Vec<PatternElement>, } #[derive(Debug)] pub(crate) struct RawSearchPattern { tokens: Vec<PatternElement>, } // Part of a search or replace pattern. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum PatternElement { Token(Token), Placeholder(Placeholder), } #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct Placeholder { /// The name of this placeholder. e.g. for "$a", this would be "a" pub(crate) ident: SmolStr, /// A unique name used in place of this placeholder when we parse the pattern as Rust code. stand_in_name: String, pub(crate) constraints: Vec<Constraint>, } #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Constraint { Kind(NodeKind), Not(Box<Constraint>), } #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum NodeKind { Literal, } #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct Token { kind: SyntaxKind, pub(crate) text: SmolStr, } impl FromStr for SsrRule { type Err = SsrError; fn from_str(query: &str) -> Result<SsrRule, SsrError> { let mut it = query.split("==>>"); let pattern = it.next().expect("at least empty string").trim(); let template = it .next() .ok_or_else(|| SsrError("Cannot find delimiter `==>>`".into()))? .trim() .to_string(); if it.next().is_some() { return Err(SsrError("More than one delimiter found".into())); } let rule = SsrRule { pattern: pattern.parse()?, template: template.parse()? }; validate_rule(&rule)?; Ok(rule) } } impl FromStr for RawSearchPattern { type Err = SsrError; fn from_str(pattern_str: &str) -> Result<RawSearchPattern, SsrError> { Ok(RawSearchPattern { tokens: parse_pattern(pattern_str)? }) } } impl RawSearchPattern { /// Returns this search pattern as Rust source code that we can feed to the Rust parser. fn as_rust_code(&self) -> String { let mut res = String::new(); for t in &self.tokens { res.push_str(match t { PatternElement::Token(token) => token.text.as_str(), PatternElement::Placeholder(placeholder) => placeholder.stand_in_name.as_str(), }); } res } fn placeholders_by_stand_in(&self) -> FxHashMap<SmolStr, Placeholder> { let mut res = FxHashMap::default(); for t in &self.tokens { if let PatternElement::Placeholder(placeholder) = t { res.insert(SmolStr::new(placeholder.stand_in_name.clone()), placeholder.clone()); } } res } } impl FromStr for SsrPattern { type Err = SsrError; fn from_str(pattern_str: &str) -> Result<SsrPattern, SsrError> { let raw: RawSearchPattern = pattern_str.parse()?; let raw_str = raw.as_rust_code(); let res = SsrPattern { expr: ast::Expr::parse(&raw_str).ok().map(|n| n.syntax().clone()), type_ref: ast::TypeRef::parse(&raw_str).ok().map(|n| n.syntax().clone()), item: ast::ModuleItem::parse(&raw_str).ok().map(|n| n.syntax().clone()), path: ast::Path::parse(&raw_str).ok().map(|n| n.syntax().clone()), pattern: ast::Pat::parse(&raw_str).ok().map(|n| n.syntax().clone()), placeholders_by_stand_in: raw.placeholders_by_stand_in(), raw, }; if res.expr.is_none() && res.type_ref.is_none() && res.item.is_none() && res.path.is_none() && res.pattern.is_none() { bail!("Pattern is not a valid Rust expression, type, item, path or pattern"); } Ok(res) } } impl FromStr for SsrTemplate { type Err = SsrError; fn from_str(pattern_str: &str) -> Result<SsrTemplate, SsrError> { let tokens = parse_pattern(pattern_str)?; // Validate that the template is a valid fragment of Rust code. We reuse the validation // logic for search patterns since the only thing that differs is the error message. if SsrPattern::from_str(pattern_str).is_err() { bail!("Replacement is not a valid Rust expression, type, item, path or pattern"); } // Our actual template needs to preserve whitespace, so we can't reuse `tokens`. Ok(SsrTemplate { tokens }) } } /// Returns `pattern_str`, parsed as a search or replace pattern. If `remove_whitespace` is true, /// then any whitespace tokens will be removed, which we do for the search pattern, but not for the /// replace pattern. fn parse_pattern(pattern_str: &str) -> Result<Vec<PatternElement>, SsrError> { let mut res = Vec::new(); let mut placeholder_names = FxHashSet::default(); let mut tokens = tokenize(pattern_str)?.into_iter(); while let Some(token) = tokens.next() { if token.kind == T![$] { let placeholder = parse_placeholder(&mut tokens)?; if !placeholder_names.insert(placeholder.ident.clone()) { bail!("Name `{}` repeats more than once", placeholder.ident); } res.push(PatternElement::Placeholder(placeholder)); } else { res.push(PatternElement::Token(token)); } } Ok(res) } /// Checks for errors in a rule. e.g. the replace pattern referencing placeholders that the search /// pattern didn't define. fn validate_rule(rule: &SsrRule) -> Result<(), SsrError> { let mut defined_placeholders = FxHashSet::default(); for p in &rule.pattern.raw.tokens { if let PatternElement::Placeholder(placeholder) = p { defined_placeholders.insert(&placeholder.ident); } } let mut undefined = Vec::new(); for p in &rule.template.tokens { if let PatternElement::Placeholder(placeholder) = p { if !defined_placeholders.contains(&placeholder.ident) { undefined.push(format!("${}", placeholder.ident)); } if !placeholder.constraints.is_empty() { bail!("Replacement placeholders cannot have constraints"); } } } if !undefined.is_empty() { bail!("Replacement contains undefined placeholders: {}", undefined.join(", ")); } Ok(()) } fn tokenize(source: &str) -> Result<Vec<Token>, SsrError> { let mut start = 0; let (raw_tokens, errors) = ra_syntax::tokenize(source); if let Some(first_error) = errors.first() { bail!("Failed to parse pattern: {}", first_error); } let mut tokens: Vec<Token> = Vec::new(); for raw_token in raw_tokens { let token_len = usize::from(raw_token.len); tokens.push(Token { kind: raw_token.kind, text: SmolStr::new(&source[start..start + token_len]), }); start += token_len; } Ok(tokens) } fn parse_placeholder(tokens: &mut std::vec::IntoIter<Token>) -> Result<Placeholder, SsrError> { let mut name = None; let mut constraints = Vec::new(); if let Some(token) = tokens.next() { match token.kind { SyntaxKind::IDENT => { name = Some(token.text); } T!['{'] => { let token = tokens.next().ok_or_else(|| SsrError::new("Unexpected end of placeholder"))?; if token.kind == SyntaxKind::IDENT { name = Some(token.text); } loop { let token = tokens .next() .ok_or_else(|| SsrError::new("Placeholder is missing closing brace '}'"))?; match token.kind { T![:] => { constraints.push(parse_constraint(tokens)?); } T!['}'] => break, _ => bail!("Unexpected token while parsing placeholder: '{}'", token.text), } } } _ => { bail!("Placeholders should either be $name or ${{name:constraints}}"); } } } let name = name.ok_or_else(|| SsrError::new("Placeholder ($) with no name"))?; Ok(Placeholder::new(name, constraints)) } fn parse_constraint(tokens: &mut std::vec::IntoIter<Token>) -> Result<Constraint, SsrError> { let constraint_type = tokens .next() .ok_or_else(|| SsrError::new("Found end of placeholder while looking for a constraint"))? .text .to_string(); match constraint_type.as_str() { "kind" => { expect_token(tokens, "(")?; let t = tokens.next().ok_or_else(|| { SsrError::new("Unexpected end of constraint while looking for kind") })?; if t.kind != SyntaxKind::IDENT { bail!("Expected ident, found {:?} while parsing kind constraint", t.kind); } expect_token(tokens, ")")?; Ok(Constraint::Kind(NodeKind::from(&t.text)?)) } "not" => { expect_token(tokens, "(")?; let sub = parse_constraint(tokens)?; expect_token(tokens, ")")?; Ok(Constraint::Not(Box::new(sub))) } x => bail!("Unsupported constraint type '{}'", x), } } fn expect_token(tokens: &mut std::vec::IntoIter<Token>, expected: &str) -> Result<(), SsrError> { if let Some(t) = tokens.next() { if t.text == expected { return Ok(()); } bail!("Expected {} found {}", expected, t.text); } bail!("Expected {} found end of stream", expected); } impl NodeKind { fn from(name: &SmolStr) -> Result<NodeKind, SsrError> { Ok(match name.as_str() { "literal" => NodeKind::Literal, _ => bail!("Unknown node kind '{}'", name), }) } } impl Placeholder { fn new(name: SmolStr, constraints: Vec<Constraint>) -> Self { Self { stand_in_name: format!("__placeholder_{}", name), constraints, ident: name } } } #[cfg(test)] mod tests { use super::*; #[test] fn parser_happy_case() { fn token(kind: SyntaxKind, text: &str) -> PatternElement { PatternElement::Token(Token { kind, text: SmolStr::new(text) }) } fn placeholder(name: &str) -> PatternElement { PatternElement::Placeholder(Placeholder::new(SmolStr::new(name), Vec::new())) } let result: SsrRule = "foo($a, $b) ==>> bar($b, $a)".parse().unwrap(); assert_eq!( result.pattern.raw.tokens, vec![ token(SyntaxKind::IDENT, "foo"), token(T!['('], "("), placeholder("a"), token(T![,], ","), token(SyntaxKind::WHITESPACE, " "), placeholder("b"), token(T![')'], ")"), ] ); assert_eq!( result.template.tokens, vec![ token(SyntaxKind::IDENT, "bar"), token(T!['('], "("), placeholder("b"), token(T![,], ","), token(SyntaxKind::WHITESPACE, " "), placeholder("a"), token(T![')'], ")"), ] ); } }
35.212209
100
0.562701
fe03b509e4ff2f7d66fdfd67fffa91d8bf170b21
26,038
//! FIXME: write short doc here mod cargo_workspace; mod json_project; mod sysroot; use std::{ fs::{read_dir, File, ReadDir}, io::{self, BufReader}, path::{Path, PathBuf}, process::{Command, Output}, }; use anyhow::{bail, Context, Result}; use ra_cfg::CfgOptions; use ra_db::{CrateGraph, CrateName, Edition, Env, ExternSource, ExternSourceId, FileId}; use rustc_hash::{FxHashMap, FxHashSet}; use serde_json::from_reader; pub use crate::{ cargo_workspace::{CargoConfig, CargoWorkspace, Package, Target, TargetKind}, json_project::JsonProject, sysroot::Sysroot, }; pub use ra_proc_macro::ProcMacroClient; #[derive(Debug, Clone)] pub enum ProjectWorkspace { /// Project workspace was discovered by running `cargo metadata` and `rustc --print sysroot`. Cargo { cargo: CargoWorkspace, sysroot: Sysroot }, /// Project workspace was manually specified using a `rust-project.json` file. Json { project: JsonProject }, } impl From<JsonProject> for ProjectWorkspace { fn from(project: JsonProject) -> ProjectWorkspace { ProjectWorkspace::Json { project } } } /// `PackageRoot` describes a package root folder. /// Which may be an external dependency, or a member of /// the current workspace. #[derive(Debug, Clone)] pub struct PackageRoot { /// Path to the root folder path: PathBuf, /// Is a member of the current workspace is_member: bool, } impl PackageRoot { pub fn new_member(path: PathBuf) -> PackageRoot { Self { path, is_member: true } } pub fn new_non_member(path: PathBuf) -> PackageRoot { Self { path, is_member: false } } pub fn path(&self) -> &Path { &self.path } pub fn is_member(&self) -> bool { self.is_member } } #[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)] pub enum ProjectManifest { ProjectJson(PathBuf), CargoToml(PathBuf), } impl ProjectManifest { pub fn from_manifest_file(path: PathBuf) -> Result<ProjectManifest> { if path.ends_with("rust-project.json") { return Ok(ProjectManifest::ProjectJson(path)); } if path.ends_with("Cargo.toml") { return Ok(ProjectManifest::CargoToml(path)); } bail!("project root must point to Cargo.toml or rust-project.json: {}", path.display()) } pub fn discover_single(path: &Path) -> Result<ProjectManifest> { let mut candidates = ProjectManifest::discover(path)?; let res = match candidates.pop() { None => bail!("no projects"), Some(it) => it, }; if !candidates.is_empty() { bail!("more than one project") } Ok(res) } pub fn discover(path: &Path) -> io::Result<Vec<ProjectManifest>> { if let Some(project_json) = find_in_parent_dirs(path, "rust-project.json") { return Ok(vec![ProjectManifest::ProjectJson(project_json)]); } return find_cargo_toml(path) .map(|paths| paths.into_iter().map(ProjectManifest::CargoToml).collect()); fn find_cargo_toml(path: &Path) -> io::Result<Vec<PathBuf>> { match find_in_parent_dirs(path, "Cargo.toml") { Some(it) => Ok(vec![it]), None => Ok(find_cargo_toml_in_child_dir(read_dir(path)?)), } } fn find_in_parent_dirs(path: &Path, target_file_name: &str) -> Option<PathBuf> { if path.ends_with(target_file_name) { return Some(path.to_owned()); } let mut curr = Some(path); while let Some(path) = curr { let candidate = path.join(target_file_name); if candidate.exists() { return Some(candidate); } curr = path.parent(); } None } fn find_cargo_toml_in_child_dir(entities: ReadDir) -> Vec<PathBuf> { // Only one level down to avoid cycles the easy way and stop a runaway scan with large projects entities .filter_map(Result::ok) .map(|it| it.path().join("Cargo.toml")) .filter(|it| it.exists()) .collect() } } pub fn discover_all(paths: &[impl AsRef<Path>]) -> Vec<ProjectManifest> { let mut res = paths .iter() .filter_map(|it| ProjectManifest::discover(it.as_ref()).ok()) .flatten() .collect::<FxHashSet<_>>() .into_iter() .collect::<Vec<_>>(); res.sort(); res } } impl ProjectWorkspace { pub fn load( manifest: ProjectManifest, cargo_features: &CargoConfig, with_sysroot: bool, ) -> Result<ProjectWorkspace> { let res = match manifest { ProjectManifest::ProjectJson(project_json) => { let file = File::open(&project_json).with_context(|| { format!("Failed to open json file {}", project_json.display()) })?; let reader = BufReader::new(file); ProjectWorkspace::Json { project: from_reader(reader).with_context(|| { format!("Failed to deserialize json file {}", project_json.display()) })?, } } ProjectManifest::CargoToml(cargo_toml) => { let cargo = CargoWorkspace::from_cargo_metadata(&cargo_toml, cargo_features) .with_context(|| { format!( "Failed to read Cargo metadata from Cargo.toml file {}", cargo_toml.display() ) })?; let sysroot = if with_sysroot { Sysroot::discover(&cargo_toml).with_context(|| { format!( "Failed to find sysroot for Cargo.toml file {}. Is rust-src installed?", cargo_toml.display() ) })? } else { Sysroot::default() }; ProjectWorkspace::Cargo { cargo, sysroot } } }; Ok(res) } /// Returns the roots for the current `ProjectWorkspace` /// The return type contains the path and whether or not /// the root is a member of the current workspace pub fn to_roots(&self) -> Vec<PackageRoot> { match self { ProjectWorkspace::Json { project } => { project.roots.iter().map(|r| PackageRoot::new_member(r.path.clone())).collect() } ProjectWorkspace::Cargo { cargo, sysroot } => cargo .packages() .map(|pkg| PackageRoot { path: cargo[pkg].root().to_path_buf(), is_member: cargo[pkg].is_member, }) .chain(sysroot.crates().map(|krate| { PackageRoot::new_non_member(sysroot[krate].root_dir().to_path_buf()) })) .collect(), } } pub fn out_dirs(&self) -> Vec<PathBuf> { match self { ProjectWorkspace::Json { project } => { project.crates.iter().filter_map(|krate| krate.out_dir.as_ref()).cloned().collect() } ProjectWorkspace::Cargo { cargo, sysroot: _ } => { cargo.packages().filter_map(|pkg| cargo[pkg].out_dir.as_ref()).cloned().collect() } } } pub fn proc_macro_dylib_paths(&self) -> Vec<PathBuf> { match self { ProjectWorkspace::Json { project } => project .crates .iter() .filter_map(|krate| krate.proc_macro_dylib_path.as_ref()) .cloned() .collect(), ProjectWorkspace::Cargo { cargo, sysroot: _sysroot } => cargo .packages() .filter_map(|pkg| cargo[pkg].proc_macro_dylib_path.as_ref()) .cloned() .collect(), } } pub fn n_packages(&self) -> usize { match self { ProjectWorkspace::Json { project } => project.crates.len(), ProjectWorkspace::Cargo { cargo, sysroot } => { cargo.packages().len() + sysroot.crates().len() } } } pub fn to_crate_graph( &self, target: Option<&str>, extern_source_roots: &FxHashMap<PathBuf, ExternSourceId>, proc_macro_client: &ProcMacroClient, load: &mut dyn FnMut(&Path) -> Option<FileId>, ) -> CrateGraph { let mut crate_graph = CrateGraph::default(); match self { ProjectWorkspace::Json { project } => { let crates: FxHashMap<_, _> = project .crates .iter() .enumerate() .filter_map(|(seq_index, krate)| { let file_id = load(&krate.root_module)?; let edition = match krate.edition { json_project::Edition::Edition2015 => Edition::Edition2015, json_project::Edition::Edition2018 => Edition::Edition2018, }; let cfg_options = { let mut opts = CfgOptions::default(); for cfg in &krate.cfg { match cfg.find('=') { None => opts.insert_atom(cfg.into()), Some(pos) => { let key = &cfg[..pos]; let value = cfg[pos + 1..].trim_matches('"'); opts.insert_key_value(key.into(), value.into()); } } } for name in &krate.atom_cfgs { opts.insert_atom(name.into()); } for (key, value) in &krate.key_value_cfgs { opts.insert_key_value(key.into(), value.into()); } opts }; let mut env = Env::default(); let mut extern_source = ExternSource::default(); if let Some(out_dir) = &krate.out_dir { // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!() if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) { env.set("OUT_DIR", out_dir); } if let Some(&extern_source_id) = extern_source_roots.get(out_dir) { extern_source.set_extern_path(&out_dir, extern_source_id); } } let proc_macro = krate .proc_macro_dylib_path .clone() .map(|it| proc_macro_client.by_dylib_path(&it)); // FIXME: No crate name in json definition such that we cannot add OUT_DIR to env Some(( json_project::CrateId(seq_index), crate_graph.add_crate_root( file_id, edition, // FIXME json definitions can store the crate name None, cfg_options, env, extern_source, proc_macro.unwrap_or_default(), ), )) }) .collect(); for (id, krate) in project.crates.iter().enumerate() { for dep in &krate.deps { let from_crate_id = json_project::CrateId(id); let to_crate_id = dep.krate; if let (Some(&from), Some(&to)) = (crates.get(&from_crate_id), crates.get(&to_crate_id)) { if crate_graph .add_dep(from, CrateName::new(&dep.name).unwrap(), to) .is_err() { log::error!( "cyclic dependency {:?} -> {:?}", from_crate_id, to_crate_id ); } } } } } ProjectWorkspace::Cargo { cargo, sysroot } => { let mut cfg_options = get_rustc_cfg_options(target); let sysroot_crates: FxHashMap<_, _> = sysroot .crates() .filter_map(|krate| { let file_id = load(&sysroot[krate].root)?; let env = Env::default(); let extern_source = ExternSource::default(); let proc_macro = vec![]; let crate_name = CrateName::new(&sysroot[krate].name) .expect("Sysroot crate names should not contain dashes"); let crate_id = crate_graph.add_crate_root( file_id, Edition::Edition2018, Some(crate_name), cfg_options.clone(), env, extern_source, proc_macro, ); Some((krate, crate_id)) }) .collect(); for from in sysroot.crates() { for &to in sysroot[from].deps.iter() { let name = &sysroot[to].name; if let (Some(&from), Some(&to)) = (sysroot_crates.get(&from), sysroot_crates.get(&to)) { if crate_graph.add_dep(from, CrateName::new(name).unwrap(), to).is_err() { log::error!("cyclic dependency between sysroot crates") } } } } let libcore = sysroot.core().and_then(|it| sysroot_crates.get(&it).copied()); let liballoc = sysroot.alloc().and_then(|it| sysroot_crates.get(&it).copied()); let libstd = sysroot.std().and_then(|it| sysroot_crates.get(&it).copied()); let libproc_macro = sysroot.proc_macro().and_then(|it| sysroot_crates.get(&it).copied()); let mut pkg_to_lib_crate = FxHashMap::default(); let mut pkg_crates = FxHashMap::default(); // Add test cfg for non-sysroot crates cfg_options.insert_atom("test".into()); // Next, create crates for each package, target pair for pkg in cargo.packages() { let mut lib_tgt = None; for &tgt in cargo[pkg].targets.iter() { let root = cargo[tgt].root.as_path(); if let Some(file_id) = load(root) { let edition = cargo[pkg].edition; let cfg_options = { let mut opts = cfg_options.clone(); for feature in cargo[pkg].features.iter() { opts.insert_key_value("feature".into(), feature.into()); } for cfg in cargo[pkg].cfgs.iter() { match cfg.find('=') { Some(split) => opts.insert_key_value( cfg[..split].into(), cfg[split + 1..].trim_matches('"').into(), ), None => opts.insert_atom(cfg.into()), }; } opts }; let mut env = Env::default(); let mut extern_source = ExternSource::default(); if let Some(out_dir) = &cargo[pkg].out_dir { // NOTE: cargo and rustc seem to hide non-UTF-8 strings from env! and option_env!() if let Some(out_dir) = out_dir.to_str().map(|s| s.to_owned()) { env.set("OUT_DIR", out_dir); } if let Some(&extern_source_id) = extern_source_roots.get(out_dir) { extern_source.set_extern_path(&out_dir, extern_source_id); } } let proc_macro = cargo[pkg] .proc_macro_dylib_path .as_ref() .map(|it| proc_macro_client.by_dylib_path(&it)) .unwrap_or_default(); let crate_id = crate_graph.add_crate_root( file_id, edition, Some(CrateName::normalize_dashes(&cargo[pkg].name)), cfg_options, env, extern_source, proc_macro.clone(), ); if cargo[tgt].kind == TargetKind::Lib { lib_tgt = Some((crate_id, cargo[tgt].name.clone())); pkg_to_lib_crate.insert(pkg, crate_id); } if cargo[tgt].is_proc_macro { if let Some(proc_macro) = libproc_macro { if crate_graph .add_dep( crate_id, CrateName::new("proc_macro").unwrap(), proc_macro, ) .is_err() { log::error!( "cyclic dependency on proc_macro for {}", &cargo[pkg].name ) } } } pkg_crates.entry(pkg).or_insert_with(Vec::new).push(crate_id); } } // Set deps to the core, std and to the lib target of the current package for &from in pkg_crates.get(&pkg).into_iter().flatten() { if let Some((to, name)) = lib_tgt.clone() { if to != from && crate_graph .add_dep( from, // For root projects with dashes in their name, // cargo metadata does not do any normalization, // so we do it ourselves currently CrateName::normalize_dashes(&name), to, ) .is_err() { { log::error!( "cyclic dependency between targets of {}", &cargo[pkg].name ) } } } // core is added as a dependency before std in order to // mimic rustcs dependency order if let Some(core) = libcore { if crate_graph .add_dep(from, CrateName::new("core").unwrap(), core) .is_err() { log::error!("cyclic dependency on core for {}", &cargo[pkg].name) } } if let Some(alloc) = liballoc { if crate_graph .add_dep(from, CrateName::new("alloc").unwrap(), alloc) .is_err() { log::error!("cyclic dependency on alloc for {}", &cargo[pkg].name) } } if let Some(std) = libstd { if crate_graph .add_dep(from, CrateName::new("std").unwrap(), std) .is_err() { log::error!("cyclic dependency on std for {}", &cargo[pkg].name) } } } } // Now add a dep edge from all targets of upstream to the lib // target of downstream. for pkg in cargo.packages() { for dep in cargo[pkg].dependencies.iter() { if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) { for &from in pkg_crates.get(&pkg).into_iter().flatten() { if crate_graph .add_dep(from, CrateName::new(&dep.name).unwrap(), to) .is_err() { log::error!( "cyclic dependency {} -> {}", &cargo[pkg].name, &cargo[dep.pkg].name ) } } } } } } } crate_graph } pub fn workspace_root_for(&self, path: &Path) -> Option<&Path> { match self { ProjectWorkspace::Cargo { cargo, .. } => { Some(cargo.workspace_root()).filter(|root| path.starts_with(root)) } ProjectWorkspace::Json { project: JsonProject { roots, .. } } => roots .iter() .find(|root| path.starts_with(&root.path)) .map(|root| root.path.as_ref()), } } } fn get_rustc_cfg_options(target: Option<&str>) -> CfgOptions { let mut cfg_options = CfgOptions::default(); // Some nightly-only cfgs, which are required for stdlib { cfg_options.insert_atom("target_thread_local".into()); for &target_has_atomic in ["8", "16", "32", "64", "cas", "ptr"].iter() { cfg_options.insert_key_value("target_has_atomic".into(), target_has_atomic.into()); cfg_options .insert_key_value("target_has_atomic_load_store".into(), target_has_atomic.into()); } } let rustc_cfgs = || -> Result<String> { // `cfg(test)` and `cfg(debug_assertion)` are handled outside, so we suppress them here. let mut cmd = Command::new(ra_toolchain::rustc()); cmd.args(&["--print", "cfg", "-O"]); if let Some(target) = target { cmd.args(&["--target", target]); } let output = output(cmd)?; Ok(String::from_utf8(output.stdout)?) }(); match rustc_cfgs { Ok(rustc_cfgs) => { for line in rustc_cfgs.lines() { match line.find('=') { None => cfg_options.insert_atom(line.into()), Some(pos) => { let key = &line[..pos]; let value = line[pos + 1..].trim_matches('"'); cfg_options.insert_key_value(key.into(), value.into()); } } } } Err(e) => log::error!("failed to get rustc cfgs: {:#}", e), } cfg_options.insert_atom("debug_assertion".into()); cfg_options } fn output(mut cmd: Command) -> Result<Output> { let output = cmd.output().with_context(|| format!("{:?} failed", cmd))?; if !output.status.success() { match String::from_utf8(output.stderr) { Ok(stderr) if !stderr.is_empty() => { bail!("{:?} failed, {}\nstderr:\n{}", cmd, output.status, stderr) } _ => bail!("{:?} failed, {}", cmd, output.status), } } Ok(output) }
41.996774
115
0.422536
e4ffcbfe7546d0025387c26ded600c7c8e31f553
7,655
use core::fmt; use core::str; #[cfg(feature = "std")] use std::error; /// An XML parser errors. #[allow(missing_docs)] #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum Error { InvalidDeclaration(StreamError, TextPos), InvalidComment(StreamError, TextPos), InvalidPI(StreamError, TextPos), InvalidDoctype(StreamError, TextPos), InvalidEntity(StreamError, TextPos), InvalidElement(StreamError, TextPos), InvalidAttribute(StreamError, TextPos), InvalidCdata(StreamError, TextPos), InvalidCharData(StreamError, TextPos), UnknownToken(TextPos), } impl Error { /// Returns the error position. pub fn pos(&self) -> TextPos { match *self { Error::InvalidDeclaration(_, pos) => pos, Error::InvalidComment(_, pos) => pos, Error::InvalidPI(_, pos) => pos, Error::InvalidDoctype(_, pos) => pos, Error::InvalidEntity(_, pos) => pos, Error::InvalidElement(_, pos) => pos, Error::InvalidAttribute(_, pos) => pos, Error::InvalidCdata(_, pos) => pos, Error::InvalidCharData(_, pos) => pos, Error::UnknownToken(pos) => pos, } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::InvalidDeclaration(ref cause, pos) => { write!(f, "invalid XML declaration at {} cause {}", pos, cause) } Error::InvalidComment(ref cause, pos) => { write!(f, "invalid comment at {} cause {}", pos, cause) } Error::InvalidPI(ref cause, pos) => { write!( f, "invalid processing instruction at {} cause {}", pos, cause ) } Error::InvalidDoctype(ref cause, pos) => { write!(f, "invalid DTD at {} cause {}", pos, cause) } Error::InvalidEntity(ref cause, pos) => { write!(f, "invalid DTD entity at {} cause {}", pos, cause) } Error::InvalidElement(ref cause, pos) => { write!(f, "invalid element at {} cause {}", pos, cause) } Error::InvalidAttribute(ref cause, pos) => { write!(f, "invalid attribute at {} cause {}", pos, cause) } Error::InvalidCdata(ref cause, pos) => { write!(f, "invalid CDATA at {} cause {}", pos, cause) } Error::InvalidCharData(ref cause, pos) => { write!(f, "invalid character data at {} cause {}", pos, cause) } Error::UnknownToken(pos) => { write!(f, "unknown token at {}", pos) } } } } #[cfg(feature = "std")] impl error::Error for Error { fn description(&self) -> &str { "an XML parsing error" } } /// A stream parser errors. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum StreamError { /// The steam ended earlier than we expected. /// /// Should only appear on invalid input data. /// Errors in a valid XML should be handled by errors below. UnexpectedEndOfStream, /// An invalid name. InvalidName, /// A non-XML character has occurred. /// /// Valid characters are: <https://www.w3.org/TR/xml/#char32> NonXmlChar(char, TextPos), /// An invalid/unexpected character. /// /// The first byte is an actual one, the second one is expected. /// /// We are using a single value to reduce the struct size. InvalidChar(u8, u8, TextPos), /// An invalid/unexpected character. /// /// Just like `InvalidChar`, but specifies multiple expected characters. InvalidCharMultiple(u8, &'static [u8], TextPos), /// An unexpected character instead of `"` or `'`. InvalidQuote(u8, TextPos), /// An unexpected character instead of an XML space. /// /// Includes: `' ' \n \r \t &#x20; &#x9; &#xD; &#xA;`. InvalidSpace(u8, TextPos), /// An unexpected string. /// /// Contains what string was expected. InvalidString(&'static str, TextPos), /// An invalid reference. InvalidReference, /// An invalid ExternalID in the DTD. InvalidExternalID, /// Comment cannot contain `--`. InvalidCommentData, /// Comment cannot end with `-`. InvalidCommentEnd, /// A Character Data node contains an invalid data. /// /// Currently, only `]]>` is not allowed. InvalidCharacterData, } impl fmt::Display for StreamError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { StreamError::UnexpectedEndOfStream => { write!(f, "unexpected end of stream") } StreamError::InvalidName => { write!(f, "invalid name token") } StreamError::NonXmlChar(c, pos) => { write!(f, "a non-XML character {:?} found at {}", c, pos) } StreamError::InvalidChar(actual, expected, pos) => { write!( f, "expected '{}' not '{}' at {}", expected as char, actual as char, pos ) } StreamError::InvalidCharMultiple(actual, ref expected, pos) => { let mut expected_iter = expected.iter().peekable(); write!(f, "expected ")?; while let Some(&c) = expected_iter.next() { write!(f, "'{}'", c as char)?; if expected_iter.peek().is_some() { write!(f, ", ")?; } } write!(f, " not '{}' at {}", actual as char, pos) } StreamError::InvalidQuote(c, pos) => { write!(f, "expected quote mark not '{}' at {}", c as char, pos) } StreamError::InvalidSpace(c, pos) => { write!(f, "expected space not '{}' at {}", c as char, pos) } StreamError::InvalidString(expected, pos) => { write!(f, "expected '{}' at {}", expected, pos) } StreamError::InvalidReference => { write!(f, "invalid reference") } StreamError::InvalidExternalID => { write!(f, "invalid ExternalID") } StreamError::InvalidCommentData => { write!(f, "'--' is not allowed in comments") } StreamError::InvalidCommentEnd => { write!(f, "comment cannot end with '-'") } StreamError::InvalidCharacterData => { write!(f, "']]>' is not allowed inside a character data") } } } } #[cfg(feature = "std")] impl error::Error for StreamError { fn description(&self) -> &str { "an XML stream parsing error" } } /// Position in text. /// /// Position indicates a row/line and a column in the original text. Starting from 1:1. #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] #[allow(missing_docs)] pub struct TextPos { pub row: u32, pub col: u32, } impl TextPos { /// Constructs a new `TextPos`. /// /// Should not be invoked manually, but rather via `Stream::gen_text_pos`. pub fn new(row: u32, col: u32) -> TextPos { TextPos { row, col } } } impl fmt::Display for TextPos { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}:{}", self.row, self.col) } }
32.163866
87
0.523971
11e1cc88878831facd8b5bb5b48be51fc09f915f
10,599
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct InvokeEndpointAsyncOutput { /// <p>Identifier for an inference request. This will be the same as the <code>InferenceId</code> specified /// in the input. Amazon SageMaker will generate an identifier for you if you do not specify one.</p> pub inference_id: std::option::Option<std::string::String>, /// <p>The Amazon S3 URI where the inference response payload is stored.</p> pub output_location: std::option::Option<std::string::String>, } impl std::fmt::Debug for InvokeEndpointAsyncOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("InvokeEndpointAsyncOutput"); formatter.field("inference_id", &self.inference_id); formatter.field("output_location", &self.output_location); formatter.finish() } } /// See [`InvokeEndpointAsyncOutput`](crate::output::InvokeEndpointAsyncOutput) pub mod invoke_endpoint_async_output { /// A builder for [`InvokeEndpointAsyncOutput`](crate::output::InvokeEndpointAsyncOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) inference_id: std::option::Option<std::string::String>, pub(crate) output_location: std::option::Option<std::string::String>, } impl Builder { /// <p>Identifier for an inference request. This will be the same as the <code>InferenceId</code> specified /// in the input. Amazon SageMaker will generate an identifier for you if you do not specify one.</p> pub fn inference_id(mut self, input: impl Into<std::string::String>) -> Self { self.inference_id = Some(input.into()); self } pub fn set_inference_id(mut self, input: std::option::Option<std::string::String>) -> Self { self.inference_id = input; self } /// <p>The Amazon S3 URI where the inference response payload is stored.</p> pub fn output_location(mut self, input: impl Into<std::string::String>) -> Self { self.output_location = Some(input.into()); self } pub fn set_output_location( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.output_location = input; self } /// Consumes the builder and constructs a [`InvokeEndpointAsyncOutput`](crate::output::InvokeEndpointAsyncOutput) pub fn build(self) -> crate::output::InvokeEndpointAsyncOutput { crate::output::InvokeEndpointAsyncOutput { inference_id: self.inference_id, output_location: self.output_location, } } } } impl InvokeEndpointAsyncOutput { /// Creates a new builder-style object to manufacture [`InvokeEndpointAsyncOutput`](crate::output::InvokeEndpointAsyncOutput) pub fn builder() -> crate::output::invoke_endpoint_async_output::Builder { crate::output::invoke_endpoint_async_output::Builder::default() } } #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct InvokeEndpointOutput { /// <p>Includes the inference provided by the model.</p> /// <p>For information about the format of the response body, see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-inference.html">Common Data /// Formats-Inference</a>.</p> pub body: std::option::Option<smithy_types::Blob>, /// <p>The MIME type of the inference returned in the response body.</p> pub content_type: std::option::Option<std::string::String>, /// <p>Identifies the production variant that was invoked.</p> pub invoked_production_variant: std::option::Option<std::string::String>, /// <p>Provides additional information in the response about the inference returned by a /// model hosted at an Amazon SageMaker endpoint. The information is an opaque value that is /// forwarded verbatim. You could use this value, for example, to return an ID received in /// the <code>CustomAttributes</code> header of a request or other metadata that a service /// endpoint was programmed to produce. The value must consist of no more than 1024 visible /// US-ASCII characters as specified in <a href="https://tools.ietf.org/html/rfc7230#section-3.2.6">Section 3.3.6. Field Value /// Components</a> of the Hypertext Transfer Protocol (HTTP/1.1). If the customer /// wants the custom attribute returned, the model must set the custom attribute to be /// included on the way back. </p> /// <p>The code in your model is responsible for setting or updating any custom attributes in /// the response. If your code does not set this value in the response, an empty value is /// returned. For example, if a custom attribute represents the trace ID, your model can /// prepend the custom attribute with <code>Trace ID:</code> in your post-processing /// function.</p> /// <p>This feature is currently supported in the AWS SDKs but not in the Amazon SageMaker Python /// SDK.</p> pub custom_attributes: std::option::Option<std::string::String>, } impl std::fmt::Debug for InvokeEndpointOutput { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("InvokeEndpointOutput"); formatter.field("body", &"*** Sensitive Data Redacted ***"); formatter.field("content_type", &self.content_type); formatter.field( "invoked_production_variant", &self.invoked_production_variant, ); formatter.field("custom_attributes", &"*** Sensitive Data Redacted ***"); formatter.finish() } } /// See [`InvokeEndpointOutput`](crate::output::InvokeEndpointOutput) pub mod invoke_endpoint_output { /// A builder for [`InvokeEndpointOutput`](crate::output::InvokeEndpointOutput) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) body: std::option::Option<smithy_types::Blob>, pub(crate) content_type: std::option::Option<std::string::String>, pub(crate) invoked_production_variant: std::option::Option<std::string::String>, pub(crate) custom_attributes: std::option::Option<std::string::String>, } impl Builder { /// <p>Includes the inference provided by the model.</p> /// <p>For information about the format of the response body, see <a href="https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-inference.html">Common Data /// Formats-Inference</a>.</p> pub fn body(mut self, input: smithy_types::Blob) -> Self { self.body = Some(input); self } pub fn set_body(mut self, input: std::option::Option<smithy_types::Blob>) -> Self { self.body = input; self } /// <p>The MIME type of the inference returned in the response body.</p> pub fn content_type(mut self, input: impl Into<std::string::String>) -> Self { self.content_type = Some(input.into()); self } pub fn set_content_type(mut self, input: std::option::Option<std::string::String>) -> Self { self.content_type = input; self } /// <p>Identifies the production variant that was invoked.</p> pub fn invoked_production_variant(mut self, input: impl Into<std::string::String>) -> Self { self.invoked_production_variant = Some(input.into()); self } pub fn set_invoked_production_variant( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.invoked_production_variant = input; self } /// <p>Provides additional information in the response about the inference returned by a /// model hosted at an Amazon SageMaker endpoint. The information is an opaque value that is /// forwarded verbatim. You could use this value, for example, to return an ID received in /// the <code>CustomAttributes</code> header of a request or other metadata that a service /// endpoint was programmed to produce. The value must consist of no more than 1024 visible /// US-ASCII characters as specified in <a href="https://tools.ietf.org/html/rfc7230#section-3.2.6">Section 3.3.6. Field Value /// Components</a> of the Hypertext Transfer Protocol (HTTP/1.1). If the customer /// wants the custom attribute returned, the model must set the custom attribute to be /// included on the way back. </p> /// <p>The code in your model is responsible for setting or updating any custom attributes in /// the response. If your code does not set this value in the response, an empty value is /// returned. For example, if a custom attribute represents the trace ID, your model can /// prepend the custom attribute with <code>Trace ID:</code> in your post-processing /// function.</p> /// <p>This feature is currently supported in the AWS SDKs but not in the Amazon SageMaker Python /// SDK.</p> pub fn custom_attributes(mut self, input: impl Into<std::string::String>) -> Self { self.custom_attributes = Some(input.into()); self } pub fn set_custom_attributes( mut self, input: std::option::Option<std::string::String>, ) -> Self { self.custom_attributes = input; self } /// Consumes the builder and constructs a [`InvokeEndpointOutput`](crate::output::InvokeEndpointOutput) pub fn build(self) -> crate::output::InvokeEndpointOutput { crate::output::InvokeEndpointOutput { body: self.body, content_type: self.content_type, invoked_production_variant: self.invoked_production_variant, custom_attributes: self.custom_attributes, } } } } impl InvokeEndpointOutput { /// Creates a new builder-style object to manufacture [`InvokeEndpointOutput`](crate::output::InvokeEndpointOutput) pub fn builder() -> crate::output::invoke_endpoint_output::Builder { crate::output::invoke_endpoint_output::Builder::default() } }
53.80203
162
0.655345
71eaee3b066a97064fd515eb73fa6787f6500578
785
use std::hash::{BuildHasher, Hasher}; /// Builder for `NopHasher` hashers. pub struct NoopHasherBuilder; /// Hasher that perform no operations. /// Can be used for keys that are already hashed, /// such as [`TypeId`]. pub struct NopHasher(u64); impl BuildHasher for NoopHasherBuilder { type Hasher = NopHasher; fn build_hasher(&self) -> NopHasher { NopHasher(0) } } impl Hasher for NopHasher { #[inline(always)] fn finish(&self) -> u64 { self.0 } #[inline(always)] fn write(&mut self, bytes: &[u8]) { let mut copy = [0u8; 8]; copy[..bytes.len().min(8)].copy_from_slice(bytes); self.0 = u64::from_ne_bytes(copy); } #[inline(always)] fn write_u64(&mut self, i: u64) { self.0 = i; } }
21.216216
58
0.598726
3a5727e0ecf981dc252663355bdff52786ef09ca
43,176
use std::{ cell::{Ref, RefCell, RefMut}, rc::Rc, }; use indexmap::IndexSet; use swc_atoms::{js_word, JsWord}; use swc_common::{ collections::{AHashMap, AHashSet}, FileName, Mark, Span, DUMMY_SP, }; use swc_ecma_ast::*; use swc_ecma_transforms_base::helper; use swc_ecma_utils::{ ident::IdentLike, member_expr, private_ident, quote_ident, quote_str, var::VarCollector, DestructuringFinder, ExprFactory, IsDirective, }; use swc_ecma_visit::{noop_fold_type, noop_visit_type, Fold, FoldWith, Visit, VisitWith}; pub use super::util::Config; use super::util::{ define_es_module, define_property, has_use_strict, initialize_to_undefined, make_descriptor, use_strict, ModulePass, Scope, }; use crate::path::{ImportResolver, Resolver}; pub fn common_js( top_level_mark: Mark, config: Config, scope: Option<Rc<RefCell<Scope>>>, ) -> impl Fold { let scope = scope.unwrap_or_default(); CommonJs { top_level_mark, config, scope, in_top_level: Default::default(), resolver: Resolver::Default, vars: Default::default(), } } pub fn common_js_with_resolver( resolver: Box<dyn ImportResolver>, base: FileName, top_level_mark: Mark, config: Config, scope: Option<Rc<RefCell<Scope>>>, ) -> impl Fold { let scope = scope.unwrap_or_default(); CommonJs { top_level_mark, config, scope, in_top_level: Default::default(), resolver: Resolver::Real { base, resolver }, vars: Default::default(), } } struct LazyIdentifierVisitor { scope: Rc<RefCell<Scope>>, top_level_idents: AHashSet<JsWord>, } impl LazyIdentifierVisitor { fn new(scope: Rc<RefCell<Scope>>) -> Self { LazyIdentifierVisitor { scope, top_level_idents: Default::default(), } } } /* An import can be performed lazily if it isn't used at the module's top-level. This visitor scans only the identifiers at the top level by not traversing nodes that introduce nesting. It then looks up identifiers to see if they match an imported specifier name. */ impl Visit for LazyIdentifierVisitor { noop_visit_type!(); fn visit_import_decl(&mut self, _: &ImportDecl) {} fn visit_export_decl(&mut self, _: &ExportDecl) {} fn visit_named_export(&mut self, _: &NamedExport) {} fn visit_export_default_decl(&mut self, _: &ExportDefaultDecl) {} fn visit_export_default_expr(&mut self, _: &ExportDefaultExpr) {} fn visit_export_all(&mut self, export: &ExportAll) { self.top_level_idents.insert(export.src.value.clone()); } fn visit_labeled_stmt(&mut self, _: &LabeledStmt) {} fn visit_continue_stmt(&mut self, _: &ContinueStmt) {} fn visit_arrow_expr(&mut self, _: &ArrowExpr) {} fn visit_function(&mut self, _: &Function) {} fn visit_constructor(&mut self, _: &Constructor) {} fn visit_setter_prop(&mut self, _: &SetterProp) {} fn visit_getter_prop(&mut self, _: &GetterProp) {} fn visit_class_prop(&mut self, _: &ClassProp) {} fn visit_prop_name(&mut self, prop_name: &PropName) { if let PropName::Computed(n) = prop_name { n.visit_with(self) } } fn visit_decl(&mut self, decl: &Decl) { if let Decl::Class(ref c) = decl { c.class.super_class.visit_with(self); c.class.body.visit_with(self); } } fn visit_ident(&mut self, ident: &Ident) { let v = self.scope.borrow().idents.get(&ident.to_id()).cloned(); if let Some((src, _)) = v { self.top_level_idents.insert(src); } } } struct CommonJs { top_level_mark: Mark, config: Config, scope: Rc<RefCell<Scope>>, in_top_level: bool, resolver: Resolver, vars: Rc<RefCell<Vec<VarDeclarator>>>, } /// TODO: VisitMut impl Fold for CommonJs { noop_fold_type!(); mark_as_nested!(); fn fold_module_items(&mut self, items: Vec<ModuleItem>) -> Vec<ModuleItem> { let mut emitted_esmodule = false; let mut stmts = Vec::with_capacity(items.len() + 5); let mut extra_stmts = Vec::with_capacity(items.len()); if self.config.strict_mode && !has_use_strict(&items) { stmts.push(ModuleItem::Stmt(use_strict())); } let mut exports = vec![]; let mut initialized = IndexSet::default(); let mut export_alls: AHashMap<JsWord, Ident> = Default::default(); // Used only if export * exists let mut exported_names: Option<Ident> = None; // Make a preliminary pass through to collect exported names ahead of time for item in &items { if let ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(NamedExport { ref specifiers, .. })) = item { for ExportNamedSpecifier { orig, exported, .. } in specifiers.iter().filter_map(|e| match e { ExportSpecifier::Named(e) => Some(e), _ => None, }) { let exported = match &exported { Some(ModuleExportName::Ident(ident)) => Some(ident), Some(ModuleExportName::Str(..)) => { unimplemented!("module string names unimplemented") } _ => None, }; let orig = match &orig { ModuleExportName::Ident(ident) => ident, _ => unimplemented!("module string names unimplemented"), }; if let Some(exported) = &exported { exports.push(exported.sym.clone()); } else { exports.push(orig.sym.clone()); } } } } // Make another preliminary pass to collect all import sources and their // specifiers. for item in &items { self.in_top_level = true; if let ModuleItem::ModuleDecl(ModuleDecl::Import(import)) = item { self.scope.borrow_mut().insert_import(import.clone()) } } // Map all top-level identifiers that match imported specifiers, and blacklist // them from lazy imports. let mut visitor = LazyIdentifierVisitor::new(self.scope.clone()); items.visit_with(&mut visitor); for ident in visitor.top_level_idents { self.scope.borrow_mut().lazy_blacklist.insert(ident); } for item in items { self.in_top_level = true; match item { ModuleItem::Stmt(ref s) if s.is_use_strict() => { stmts.push(item); } ModuleItem::ModuleDecl(ModuleDecl::Import(import)) => { self.scope.borrow_mut().insert_import(import) } ModuleItem::ModuleDecl(ModuleDecl::ExportAll(..)) | ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(..)) | ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(..)) | ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(..)) | ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(..)) => { if !self.config.strict && !emitted_esmodule { emitted_esmodule = true; stmts.push(ModuleItem::Stmt(define_es_module(quote_ident!("exports")))); } let mut scope_ref_mut = self.scope.borrow_mut(); let scope = &mut *scope_ref_mut; macro_rules! init_export { ("default") => {{ init_export!(js_word!("default")) }}; ($name:expr) => {{ exports.push($name.clone()); initialized.insert($name.clone()); }}; } match item { ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl( ExportDefaultDecl { decl: DefaultDecl::Fn(..), .. }, )) => { // initialized.insert(js_word!("default")); } ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl( ExportDefaultDecl { decl: DefaultDecl::TsInterfaceDecl(..), .. }, )) => {} ModuleItem::ModuleDecl(ModuleDecl::ExportAll(ref export)) => { scope.import_to_export(&export.src, true); scope .import_types .entry(export.src.value.clone()) .and_modify(|v| *v = true); } ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(..)) | ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(..)) => { init_export!("default") } ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(NamedExport { src: Some(ref src), ref specifiers, .. })) => { scope.import_to_export(src, !specifiers.is_empty()); } _ => {} } drop(scope_ref_mut); match item { ModuleItem::ModuleDecl(ModuleDecl::ExportAll(export)) => { let mut scope_ref_mut = self.scope.borrow_mut(); let scope = &mut *scope_ref_mut; if exported_names.is_none() && (!export_alls.is_empty() || !exports.is_empty()) { let exported_names_ident = private_ident!("_exportNames"); stmts.push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, decls: vec![VarDeclarator { span: DUMMY_SP, name: exported_names_ident.clone().into(), init: Some(Box::new(Expr::Object(ObjectLit { span: DUMMY_SP, props: exports .clone() .into_iter() .filter_map(|export| { if export == js_word!("default") { return None; } Some(PropOrSpread::Prop(Box::new( Prop::KeyValue(KeyValueProp { key: PropName::Ident(Ident::new( export, DUMMY_SP, )), value: true.into(), }), ))) }) .collect(), }))), definite: false, }], declare: false, })))); exported_names = Some(exported_names_ident); } let data = scope .import_to_export(&export.src, true) .expect("Export should exists"); export_alls.entry(export.src.value.clone()).or_insert(data); drop(scope_ref_mut); } ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl { decl: decl @ Decl::Class(..), .. })) | ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl { decl: decl @ Decl::Fn(..), .. })) => { let (ident, is_class) = match decl { Decl::Class(ref c) => (c.ident.clone(), true), Decl::Fn(ref f) => (f.ident.clone(), false), _ => unreachable!(), }; extra_stmts.push(ModuleItem::Stmt(Stmt::Decl(decl.fold_with(self)))); if !is_class { let mut scope = self.scope.borrow_mut(); scope .exported_bindings .entry((ident.sym.clone(), ident.span.ctxt())) .or_default() .push((ident.sym.clone(), ident.span.ctxt())); } let append_to: &mut Vec<_> = if is_class { &mut extra_stmts } else { // Function declaration cannot throw &mut stmts }; append_to.push( AssignExpr { span: DUMMY_SP, left: PatOrExpr::Expr(Box::new( quote_ident!("exports").make_member(ident.clone()), )), op: op!("="), right: Box::new(ident.into()), } .into_stmt() .into(), ); } ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(ExportDecl { decl: Decl::Var(var), .. })) => { extra_stmts.push(ModuleItem::Stmt(Stmt::Decl(Decl::Var( var.clone().fold_with(self), )))); let mut scope = self.scope.borrow_mut(); var.decls.visit_with(&mut VarCollector { to: &mut scope.declared_vars, }); let mut found: Vec<Ident> = vec![]; for decl in var.decls { let mut v = DestructuringFinder { found: &mut found }; decl.visit_with(&mut v); for ident in found.drain(..) { scope .exported_bindings .entry((ident.sym.clone(), ident.span.ctxt())) .or_default() .push((ident.sym.clone(), ident.span.ctxt())); init_export!(ident.sym); extra_stmts.push( AssignExpr { span: DUMMY_SP, left: PatOrExpr::Expr(Box::new( quote_ident!("exports").make_member(ident.clone()), )), op: op!("="), right: Box::new(ident.into()), } .into_stmt() .into(), ); } } drop(scope); } ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(..)) => { // extra_stmts.push(item.fold_with(self)); } ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(decl)) => { match decl.decl { DefaultDecl::Class(ClassExpr { ident, class }) => { let class = class.fold_with(self); init_export!("default"); let ident = ident.unwrap_or_else(|| private_ident!("_default")); extra_stmts.push(ModuleItem::Stmt(Stmt::Decl(Decl::Class( ClassDecl { ident: ident.clone(), class, declare: false, } .fold_with(self), )))); extra_stmts.push( AssignExpr { span: DUMMY_SP, left: PatOrExpr::Expr(member_expr!( DUMMY_SP, exports.default )), op: op!("="), right: Box::new(ident.into()), } .into_stmt() .into(), ); } DefaultDecl::Fn(FnExpr { ident, function }) => { // init_export!("default"); let ident = ident.unwrap_or_else(|| private_ident!("_default")); // bind default exported fn into scope. Note this assigns // syntaxcontext // for the `default` ident, since default export is always named // as `export.default` // instead of actual ident of FnExpr even if it exists. { let mut scope = self.scope.borrow_mut(); scope .exported_bindings .entry((ident.sym.clone(), ident.span.ctxt())) .or_default() .push((js_word!("default"), DUMMY_SP.ctxt())); } extra_stmts.push(ModuleItem::Stmt(Stmt::Decl(Decl::Fn( FnDecl { ident: ident.clone(), function, declare: false, } .fold_with(self), )))); stmts.push( AssignExpr { span: DUMMY_SP, left: PatOrExpr::Expr(member_expr!( DUMMY_SP, exports.default )), op: op!("="), right: Box::new(ident.into()), } .into_stmt() .into(), ); } _ => extra_stmts.push( ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultDecl(decl)) .fold_with(self), ), } } ModuleItem::ModuleDecl(ModuleDecl::ExportDefaultExpr(expr)) => { let ident = private_ident!("_default"); // TODO: Optimization (when expr cannot throw, `exports.default = // void 0` is not required) // We use extra statements because of the initialization extra_stmts.push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, decls: vec![VarDeclarator { span: DUMMY_SP, name: ident.clone().into(), init: Some(expr.expr.fold_with(self)), definite: false, }], declare: false, })))); extra_stmts.push( AssignExpr { span: DUMMY_SP, left: PatOrExpr::Expr(member_expr!(DUMMY_SP, exports.default)), op: op!("="), right: Box::new(ident.into()), } .into_stmt() .into(), ); } // export { foo } from 'foo'; ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(export)) => { let mut scope = self.scope.borrow_mut(); let imported = export.src.clone().map(|src| { scope.import_to_export(&src, !export.specifiers.is_empty()) }); stmts.reserve(export.specifiers.len()); drop(scope); for ExportNamedSpecifier { orig, exported, .. } in export .specifiers .into_iter() .map(|e| match e { ExportSpecifier::Named(e) => e, _ => unreachable!( "export default from 'foo'; should be removed by previous \ pass" ), }) .filter(|e| !e.is_type_only) { let exported = match &exported { Some(ModuleExportName::Ident(ident)) => Some(ident), Some(ModuleExportName::Str(..)) => { unimplemented!("module string names unimplemented") } _ => None, }; let orig = match &orig { ModuleExportName::Ident(ident) => ident, _ => unimplemented!("module string names unimplemented"), }; let mut scope = self.scope.borrow_mut(); let is_import_default = orig.sym == js_word!("default"); let key = orig.to_id(); if scope.declared_vars.contains(&key) { scope .exported_bindings .entry(key.clone()) .or_default() .push( exported .map(|i| (i.sym.clone(), i.span.ctxt())) .unwrap_or_else(|| { (orig.sym.clone(), orig.span.ctxt()) }), ); } if let Some(ref src) = export.src { if is_import_default { scope .import_types .entry(src.value.clone()) .or_insert(false); } } let lazy = if let Some(ref src) = export.src { if scope.lazy_blacklist.contains(&src.value) { false } else { self.config.lazy.is_lazy(&src.value) } } else { match scope.idents.get(&(orig.sym.clone(), orig.span.ctxt())) { Some((ref src, _)) => { if scope.lazy_blacklist.contains(src) { false } else { self.config.lazy.is_lazy(src) } } None => false, } }; drop(scope); let old = self.in_top_level; let value = match imported { Some(ref imported) => { let receiver = if lazy { Expr::Call(CallExpr { span: DUMMY_SP, callee: imported.clone().unwrap().as_callee(), args: vec![], type_args: Default::default(), }) } else { Expr::Ident(imported.clone().unwrap()) }; Box::new(receiver.make_member(orig.clone())) } None => Box::new(Expr::Ident(orig.clone()).fold_with(self)), }; // True if we are exporting our own stuff. let is_value_ident = matches!(*value, Expr::Ident(..)); self.in_top_level = old; if is_value_ident { let exported_symbol = exported .as_ref() .map(|e| e.sym.clone()) .unwrap_or_else(|| orig.sym.clone()); init_export!(exported_symbol); extra_stmts.push( AssignExpr { span: DUMMY_SP, left: PatOrExpr::Expr(Box::new( quote_ident!("exports").make_member( (exported.unwrap_or(orig)).clone(), ), )), op: op!("="), right: value, } .into_stmt() .into(), ); } else { stmts.push( define_property(vec![ quote_ident!("exports").as_arg(), { // export { foo } // -> 'foo' // export { foo as bar } // -> 'bar' let i = exported.unwrap_or(orig).clone(); quote_str!(i.span, i.sym).as_arg() }, make_descriptor(value).as_arg(), ]) .into_stmt() .into(), ); } } } _ => unreachable!(), } } _ => extra_stmts.push(item.fold_with(self)), } } if !initialized.is_empty() { stmts.extend(initialize_to_undefined( quote_ident!("exports"), initialized, )); } let vars = self.vars_take(); if !vars.is_empty() { let var_stmt = Stmt::Decl( VarDecl { span: DUMMY_SP, kind: VarDeclKind::Var, declare: false, decls: vars, } .into(), ) .into(); stmts.push(var_stmt); } let mut scope_ref_mut = self.scope.borrow_mut(); let scope = &mut *scope_ref_mut; let scope = &mut *scope; for (src, import) in scope.imports.drain(..) { let lazy = if scope.lazy_blacklist.contains(&src) { false } else { self.config.lazy.is_lazy(&src) }; let require = self .resolver .make_require_call(self.top_level_mark, src.clone()); match import { Some(import) => { let ty = scope.import_types.get(&src); let rhs = match ty { Some(true) if !self.config.no_interop => Box::new(Expr::Call(CallExpr { span: DUMMY_SP, callee: helper!(interop_require_wildcard, "interopRequireWildcard"), args: vec![require.as_arg()], type_args: Default::default(), })), Some(false) if !self.config.no_interop => Box::new(Expr::Call(CallExpr { span: DUMMY_SP, callee: helper!(interop_require_default, "interopRequireDefault"), args: vec![require.as_arg()], type_args: Default::default(), })), _ => Box::new(require), }; let ident = Ident::new(import.0, import.1); if lazy { let return_data = Stmt::Return(ReturnStmt { span: DUMMY_SP, arg: Some(Box::new(quote_ident!("data").into())), }); stmts.push(ModuleItem::Stmt(Stmt::Decl(Decl::Fn(FnDecl { ident: ident.clone(), function: Function { span: DUMMY_SP, is_async: false, is_generator: false, decorators: Default::default(), body: Some(BlockStmt { span: DUMMY_SP, stmts: vec![ // const data = require(); Stmt::Decl(Decl::Var(VarDecl { span: DUMMY_SP, kind: VarDeclKind::Const, decls: vec![VarDeclarator { span: DUMMY_SP, name: quote_ident!("data").into(), init: Some(rhs), definite: false, }], declare: false, })), // foo = function() { return data; }; AssignExpr { span: DUMMY_SP, left: PatOrExpr::Pat(ident.into()), op: op!("="), right: Box::new( FnExpr { ident: None, function: Function { span: DUMMY_SP, is_async: false, is_generator: false, decorators: Default::default(), body: Some(BlockStmt { span: DUMMY_SP, stmts: vec![return_data.clone()], }), params: vec![], type_params: Default::default(), return_type: Default::default(), }, } .into(), ), } .into_stmt(), // return data return_data, ], }), params: vec![], type_params: Default::default(), return_type: Default::default(), }, declare: false, })))); } else { stmts.push(ModuleItem::Stmt(Stmt::Decl(Decl::Var(VarDecl { span: import.1, kind: VarDeclKind::Var, decls: vec![VarDeclarator { span: DUMMY_SP, name: ident.into(), init: Some(rhs), definite: false, }], declare: false, })))); } } None => { stmts.push(require.into_stmt().into()); } } let exported = export_alls.remove(&src); if let Some(export) = exported { stmts.push(ModuleItem::Stmt(Scope::handle_export_all( quote_ident!("exports"), exported_names.clone(), export, ))); } } stmts.append(&mut extra_stmts); stmts } fn fold_expr(&mut self, expr: Expr) -> Expr { let top_level = self.in_top_level; Scope::fold_expr(self, quote_ident!("exports"), top_level, expr) } fn fold_prop(&mut self, p: Prop) -> Prop { match p { Prop::Shorthand(ident) => Scope::fold_shorthand_prop(self, ident), _ => p.fold_children_with(self), } } /// /// - collects all declared variables for let and var. fn fold_var_decl(&mut self, var: VarDecl) -> VarDecl { if var.kind != VarDeclKind::Const { var.decls.visit_with(&mut VarCollector { to: &mut self.scope.borrow_mut().declared_vars, }); } VarDecl { decls: var.decls.fold_with(self), ..var } } fn fold_fn_decl(&mut self, node: FnDecl) -> FnDecl { self.scope .borrow_mut() .declared_vars .push((node.ident.sym.clone(), node.ident.span.ctxt())); node.fold_children_with(self) } fn fold_class_decl(&mut self, node: ClassDecl) -> ClassDecl { self.scope .borrow_mut() .declared_vars .push((node.ident.sym.clone(), node.ident.span.ctxt())); node.fold_children_with(self) } } impl ModulePass for CommonJs { fn config(&self) -> &Config { &self.config } fn scope(&self) -> Ref<Scope> { self.scope.borrow() } fn scope_mut(&mut self) -> RefMut<Scope> { self.scope.borrow_mut() } fn resolver(&self) -> &Resolver { &self.resolver } fn make_dynamic_import(&mut self, span: Span, args: Vec<ExprOrSpread>) -> Expr { handle_dynamic_import(span, args, !self.config.no_interop) } fn vars(&mut self) -> Ref<Vec<VarDeclarator>> { self.vars.borrow() } fn vars_mut(&mut self) -> RefMut<Vec<VarDeclarator>> { self.vars.borrow_mut() } fn vars_take(&mut self) -> Vec<VarDeclarator> { self.vars.take() } } /// ```js /// Promise.resolve().then(function () { return require('./foo'); }) /// ``` pub(super) fn handle_dynamic_import( span: Span, args: Vec<ExprOrSpread>, es_module_interop: bool, ) -> Expr { let resolve_call = CallExpr { span: DUMMY_SP, callee: member_expr!(DUMMY_SP, Promise.resolve).as_callee(), args: Default::default(), type_args: Default::default(), }; // Promise.resolve().then let then = resolve_call.make_member(quote_ident!("then")); return Expr::Call(CallExpr { span, callee: then.as_callee(), args: vec![ // function () { return require('./foo'); } FnExpr { ident: None, function: Function { span: DUMMY_SP, params: vec![], is_generator: false, is_async: false, type_params: Default::default(), return_type: Default::default(), decorators: Default::default(), body: Some(BlockStmt { span: DUMMY_SP, stmts: vec![Stmt::Return(ReturnStmt { span: DUMMY_SP, arg: Some({ let mut expr = Box::new(Expr::Call(CallExpr { span: DUMMY_SP, callee: quote_ident!("require").as_callee(), args, type_args: Default::default(), })); if es_module_interop { expr = Box::new(Expr::Call(CallExpr { span: DUMMY_SP, callee: helper!( interop_require_wildcard, "interopRequireWildcard" ), args: vec![expr.as_arg()], type_args: Default::default(), })); } expr }), })], }), }, } .as_arg(), ], type_args: Default::default(), }); }
42.833333
100
0.34818
e4c4e65158bd6c33107b219d4e04ef00a7e21aa0
43,312
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. use crate::error::is_instance_of_error; use crate::modules::ModuleMap; use crate::resolve_url_or_path; use crate::JsRuntime; use crate::Op; use crate::OpId; use crate::OpPayload; use crate::OpResult; use crate::OpTable; use crate::PromiseId; use crate::ZeroCopyBuf; use anyhow::Error; use log::debug; use serde::Deserialize; use serde::Serialize; use serde_v8::to_v8; use std::cell::RefCell; use std::option::Option; use url::Url; use v8::HandleScope; use v8::Local; use v8::MapFnTo; use v8::SharedArrayBuffer; use v8::ValueDeserializerHelper; use v8::ValueSerializerHelper; lazy_static::lazy_static! { pub static ref EXTERNAL_REFERENCES: v8::ExternalReferences = v8::ExternalReferences::new(&[ v8::ExternalReference { function: opcall_async.map_fn_to() }, v8::ExternalReference { function: opcall_sync.map_fn_to() }, v8::ExternalReference { function: ref_op.map_fn_to() }, v8::ExternalReference { function: unref_op.map_fn_to() }, v8::ExternalReference { function: set_macrotask_callback.map_fn_to() }, v8::ExternalReference { function: set_nexttick_callback.map_fn_to() }, v8::ExternalReference { function: set_promise_reject_callback.map_fn_to() }, v8::ExternalReference { function: set_uncaught_exception_callback.map_fn_to() }, v8::ExternalReference { function: run_microtasks.map_fn_to() }, v8::ExternalReference { function: has_tick_scheduled.map_fn_to() }, v8::ExternalReference { function: set_has_tick_scheduled.map_fn_to() }, v8::ExternalReference { function: eval_context.map_fn_to() }, v8::ExternalReference { function: queue_microtask.map_fn_to() }, v8::ExternalReference { function: create_host_object.map_fn_to() }, v8::ExternalReference { function: encode.map_fn_to() }, v8::ExternalReference { function: decode.map_fn_to() }, v8::ExternalReference { function: serialize.map_fn_to() }, v8::ExternalReference { function: deserialize.map_fn_to() }, v8::ExternalReference { function: get_promise_details.map_fn_to() }, v8::ExternalReference { function: get_proxy_details.map_fn_to() }, v8::ExternalReference { function: is_proxy.map_fn_to() }, v8::ExternalReference { function: memory_usage.map_fn_to(), }, v8::ExternalReference { function: call_console.map_fn_to(), }, v8::ExternalReference { function: set_wasm_streaming_callback.map_fn_to() } ]); } pub fn script_origin<'a>( s: &mut v8::HandleScope<'a>, resource_name: v8::Local<'a, v8::String>, ) -> v8::ScriptOrigin<'a> { let source_map_url = v8::String::new(s, "").unwrap(); v8::ScriptOrigin::new( s, resource_name.into(), 0, 0, false, 123, source_map_url.into(), true, false, false, ) } pub fn module_origin<'a>( s: &mut v8::HandleScope<'a>, resource_name: v8::Local<'a, v8::String>, ) -> v8::ScriptOrigin<'a> { let source_map_url = v8::String::new(s, "").unwrap(); v8::ScriptOrigin::new( s, resource_name.into(), 0, 0, false, 123, source_map_url.into(), true, false, true, ) } pub fn initialize_context<'s>( scope: &mut v8::HandleScope<'s, ()>, ) -> v8::Local<'s, v8::Context> { let scope = &mut v8::EscapableHandleScope::new(scope); let context = v8::Context::new(scope); let global = context.global(scope); let scope = &mut v8::ContextScope::new(scope, context); // global.Deno = { core: {} }; let deno_key = v8::String::new(scope, "Deno").unwrap(); let deno_val = v8::Object::new(scope); global.set(scope, deno_key.into(), deno_val.into()); let core_key = v8::String::new(scope, "core").unwrap(); let core_val = v8::Object::new(scope); deno_val.set(scope, core_key.into(), core_val.into()); // Bind functions to Deno.core.* set_func(scope, core_val, "opcallSync", opcall_sync); set_func(scope, core_val, "opcallAsync", opcall_async); set_func(scope, core_val, "refOp", ref_op); set_func(scope, core_val, "unrefOp", unref_op); set_func( scope, core_val, "setMacrotaskCallback", set_macrotask_callback, ); set_func( scope, core_val, "setNextTickCallback", set_nexttick_callback, ); set_func( scope, core_val, "setPromiseRejectCallback", set_promise_reject_callback, ); set_func( scope, core_val, "setUncaughtExceptionCallback", set_uncaught_exception_callback, ); set_func(scope, core_val, "runMicrotasks", run_microtasks); set_func(scope, core_val, "hasTickScheduled", has_tick_scheduled); set_func( scope, core_val, "setHasTickScheduled", set_has_tick_scheduled, ); set_func(scope, core_val, "evalContext", eval_context); set_func(scope, core_val, "encode", encode); set_func(scope, core_val, "decode", decode); set_func(scope, core_val, "serialize", serialize); set_func(scope, core_val, "deserialize", deserialize); set_func(scope, core_val, "getPromiseDetails", get_promise_details); set_func(scope, core_val, "getProxyDetails", get_proxy_details); set_func(scope, core_val, "isProxy", is_proxy); set_func(scope, core_val, "memoryUsage", memory_usage); set_func(scope, core_val, "callConsole", call_console); set_func(scope, core_val, "createHostObject", create_host_object); set_func( scope, core_val, "setWasmStreamingCallback", set_wasm_streaming_callback, ); // Direct bindings on `window`. set_func(scope, global, "queueMicrotask", queue_microtask); scope.escape(context) } #[inline(always)] pub fn set_func( scope: &mut v8::HandleScope<'_>, obj: v8::Local<v8::Object>, name: &'static str, callback: impl v8::MapFnTo<v8::FunctionCallback>, ) { let key = v8::String::new(scope, name).unwrap(); let tmpl = v8::FunctionTemplate::new(scope, callback); let val = tmpl.get_function(scope).unwrap(); val.set_name(key); obj.set(scope, key.into(), val.into()); } pub extern "C" fn host_import_module_dynamically_callback( context: v8::Local<v8::Context>, referrer: v8::Local<v8::ScriptOrModule>, specifier: v8::Local<v8::String>, _import_assertions: v8::Local<v8::FixedArray>, ) -> *mut v8::Promise { let scope = &mut unsafe { v8::CallbackScope::new(context) }; // NOTE(bartlomieju): will crash for non-UTF-8 specifier let specifier_str = specifier .to_string(scope) .unwrap() .to_rust_string_lossy(scope); let referrer_name = referrer.get_resource_name(); let referrer_name_str = referrer_name .to_string(scope) .unwrap() .to_rust_string_lossy(scope); // TODO(ry) I'm not sure what HostDefinedOptions is for or if we're ever going // to use it. For now we check that it is not used. This check may need to be // changed in the future. let host_defined_options = referrer.get_host_defined_options(); assert_eq!(host_defined_options.length(), 0); let resolver = v8::PromiseResolver::new(scope).unwrap(); let promise = resolver.get_promise(scope); let resolver_handle = v8::Global::new(scope, resolver); { let state_rc = JsRuntime::state(scope); let module_map_rc = JsRuntime::module_map(scope); debug!( "dyn_import specifier {} referrer {} ", specifier_str, referrer_name_str ); ModuleMap::load_dynamic_import( module_map_rc, &specifier_str, &referrer_name_str, resolver_handle, ); state_rc.borrow_mut().notify_new_dynamic_import(); } // Map errors from module resolution (not JS errors from module execution) to // ones rethrown from this scope, so they include the call stack of the // dynamic import site. Error objects without any stack frames are assumed to // be module resolution errors, other exception values are left as they are. let map_err = |scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, _rv: v8::ReturnValue| { let arg = args.get(0); if is_instance_of_error(scope, arg) { let message = v8::Exception::create_message(scope, arg); if message.get_stack_trace(scope).unwrap().get_frame_count() == 0 { let arg: v8::Local<v8::Object> = arg.try_into().unwrap(); let message_key = v8::String::new(scope, "message").unwrap(); let message = arg.get(scope, message_key.into()).unwrap(); let exception = v8::Exception::type_error(scope, message.try_into().unwrap()); let code_key = v8::String::new(scope, "code").unwrap(); let code_value = v8::String::new(scope, "ERR_MODULE_NOT_FOUND").unwrap(); let exception_obj = exception.to_object(scope).unwrap(); exception_obj.set(scope, code_key.into(), code_value.into()); scope.throw_exception(exception); return; } } scope.throw_exception(arg); }; let map_err = v8::FunctionTemplate::new(scope, map_err); let map_err = map_err.get_function(scope).unwrap(); let promise = promise.catch(scope, map_err).unwrap(); &*promise as *const _ as *mut _ } pub extern "C" fn host_initialize_import_meta_object_callback( context: v8::Local<v8::Context>, module: v8::Local<v8::Module>, meta: v8::Local<v8::Object>, ) { let scope = &mut unsafe { v8::CallbackScope::new(context) }; let module_map_rc = JsRuntime::module_map(scope); let module_map = module_map_rc.borrow(); let module_global = v8::Global::new(scope, module); let info = module_map .get_info(&module_global) .expect("Module not found"); let url_key = v8::String::new(scope, "url").unwrap(); let url_val = v8::String::new(scope, &info.name).unwrap(); meta.create_data_property(scope, url_key.into(), url_val.into()); let main_key = v8::String::new(scope, "main").unwrap(); let main_val = v8::Boolean::new(scope, info.main); meta.create_data_property(scope, main_key.into(), main_val.into()); } pub extern "C" fn promise_reject_callback(message: v8::PromiseRejectMessage) { use v8::PromiseRejectEvent::*; let scope = &mut unsafe { v8::CallbackScope::new(&message) }; let state_rc = JsRuntime::state(scope); let mut state = state_rc.borrow_mut(); // Node compat: perform synchronous process.emit("unhandledRejection"). // // Note the callback follows the (type, promise, reason) signature of Node's // internal promiseRejectHandler from lib/internal/process/promises.js, not // the (promise, reason) signature of the "unhandledRejection" event listener. // // Short-circuits Deno's regular unhandled rejection logic because that's // a) asynchronous, and b) always terminates. if let Some(js_promise_reject_cb) = state.js_promise_reject_cb.clone() { let js_uncaught_exception_cb = state.js_uncaught_exception_cb.clone(); drop(state); // Drop borrow, callbacks can call back into runtime. let tc_scope = &mut v8::TryCatch::new(scope); let undefined: v8::Local<v8::Value> = v8::undefined(tc_scope).into(); let type_ = v8::Integer::new(tc_scope, message.get_event() as i32); let promise = message.get_promise(); let reason = match message.get_event() { PromiseRejectWithNoHandler | PromiseRejectAfterResolved | PromiseResolveAfterResolved => message.get_value().unwrap_or(undefined), PromiseHandlerAddedAfterReject => undefined, }; let args = &[type_.into(), promise.into(), reason]; js_promise_reject_cb .open(tc_scope) .call(tc_scope, undefined, args); if let Some(exception) = tc_scope.exception() { if let Some(js_uncaught_exception_cb) = js_uncaught_exception_cb { tc_scope.reset(); // Cancel pending exception. js_uncaught_exception_cb.open(tc_scope).call( tc_scope, undefined, &[exception], ); } } if tc_scope.has_caught() { // If we get here, an exception was thrown by the unhandledRejection // handler and there is ether no uncaughtException handler or the // handler threw an exception of its own. // // TODO(bnoordhuis) Node terminates the process or worker thread // but we don't really have that option. The exception won't bubble // up either because V8 cancels it when this function returns. let exception = tc_scope .stack_trace() .or_else(|| tc_scope.exception()) .map(|value| value.to_rust_string_lossy(tc_scope)) .unwrap_or_else(|| "no exception".into()); eprintln!("Unhandled exception: {}", exception); } } else { let promise = message.get_promise(); let promise_global = v8::Global::new(scope, promise); match message.get_event() { PromiseRejectWithNoHandler => { let error = message.get_value().unwrap(); let error_global = v8::Global::new(scope, error); state .pending_promise_exceptions .insert(promise_global, error_global); } PromiseHandlerAddedAfterReject => { state.pending_promise_exceptions.remove(&promise_global); } PromiseRejectAfterResolved => {} PromiseResolveAfterResolved => { // Should not warn. See #1272 } } } } fn opcall_sync<'s>( scope: &mut v8::HandleScope<'s>, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { let state_rc = JsRuntime::state(scope); let state = state_rc.borrow_mut(); let op_id = match v8::Local::<v8::Integer>::try_from(args.get(0)) .map(|l| l.value() as OpId) .map_err(Error::from) { Ok(op_id) => op_id, Err(err) => { throw_type_error(scope, format!("invalid op id: {}", err)); return; } }; // opcall(0) returns obj of all ops, handle as special case if op_id == 0 { // TODO: Serialize as HashMap when serde_v8 supports maps ... let ops = OpTable::op_entries(state.op_state.clone()); rv.set(to_v8(scope, ops).unwrap()); return; } // Deserializable args (may be structured args or ZeroCopyBuf) let a = args.get(1); let b = args.get(2); let payload = OpPayload { scope, a, b, op_id, promise_id: 0, }; let op = OpTable::route_op(op_id, state.op_state.clone(), payload); match op { Op::Sync(result) => { state.op_state.borrow().tracker.track_sync(op_id); rv.set(result.to_v8(scope).unwrap()); } Op::NotFound => { throw_type_error(scope, format!("Unknown op id: {}", op_id)); } // Async ops (ref or unref) _ => { throw_type_error( scope, format!("Can not call an async op [{}] with opSync()", op_id), ); } } } fn opcall_async<'s>( scope: &mut v8::HandleScope<'s>, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { let state_rc = JsRuntime::state(scope); let mut state = state_rc.borrow_mut(); let op_id = match v8::Local::<v8::Integer>::try_from(args.get(0)) .map(|l| l.value() as OpId) .map_err(Error::from) { Ok(op_id) => op_id, Err(err) => { throw_type_error(scope, format!("invalid op id: {}", err)); return; } }; // PromiseId let arg1 = args.get(1); let promise_id = v8::Local::<v8::Integer>::try_from(arg1) .map(|l| l.value() as PromiseId) .map_err(Error::from); // Fail if promise id invalid (not an int) let promise_id: PromiseId = match promise_id { Ok(promise_id) => promise_id, Err(err) => { throw_type_error(scope, format!("invalid promise id: {}", err)); return; } }; // Deserializable args (may be structured args or ZeroCopyBuf) let a = args.get(2); let b = args.get(3); let payload = OpPayload { scope, a, b, op_id, promise_id, }; let op = OpTable::route_op(op_id, state.op_state.clone(), payload); match op { Op::Sync(result) => match result { OpResult::Ok(_) => throw_type_error( scope, format!("Can not call a sync op [{}] with opAsync()", op_id), ), OpResult::Err(_) => rv.set(result.to_v8(scope).unwrap()), }, Op::Async(fut) => { state.op_state.borrow().tracker.track_async(op_id); state.pending_ops.push(fut); state.have_unpolled_ops = true; } Op::NotFound => { throw_type_error(scope, format!("Unknown op id: {}", op_id)); } } } fn ref_op<'s>( scope: &mut v8::HandleScope<'s>, args: v8::FunctionCallbackArguments, _rv: v8::ReturnValue, ) { let state_rc = JsRuntime::state(scope); let mut state = state_rc.borrow_mut(); let promise_id = match v8::Local::<v8::Integer>::try_from(args.get(0)) .map(|l| l.value() as PromiseId) .map_err(Error::from) { Ok(promise_id) => promise_id, Err(err) => { throw_type_error(scope, format!("invalid promise id: {}", err)); return; } }; state.unrefed_ops.remove(&promise_id); } fn unref_op<'s>( scope: &mut v8::HandleScope<'s>, args: v8::FunctionCallbackArguments, _rv: v8::ReturnValue, ) { let state_rc = JsRuntime::state(scope); let mut state = state_rc.borrow_mut(); let promise_id = match v8::Local::<v8::Integer>::try_from(args.get(0)) .map(|l| l.value() as PromiseId) .map_err(Error::from) { Ok(promise_id) => promise_id, Err(err) => { throw_type_error(scope, format!("invalid promise id: {}", err)); return; } }; state.unrefed_ops.insert(promise_id); } fn has_tick_scheduled( scope: &mut v8::HandleScope, _args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { let state_rc = JsRuntime::state(scope); let state = state_rc.borrow(); rv.set(to_v8(scope, state.has_tick_scheduled).unwrap()); } fn set_has_tick_scheduled( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, _rv: v8::ReturnValue, ) { let state_rc = JsRuntime::state(scope); let mut state = state_rc.borrow_mut(); state.has_tick_scheduled = args.get(0).is_true(); } fn run_microtasks( scope: &mut v8::HandleScope, _args: v8::FunctionCallbackArguments, _rv: v8::ReturnValue, ) { scope.perform_microtask_checkpoint(); } fn set_nexttick_callback( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, _rv: v8::ReturnValue, ) { if let Ok(cb) = arg0_to_cb(scope, args) { JsRuntime::state(scope) .borrow_mut() .js_nexttick_cbs .push(cb); } } fn set_macrotask_callback( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, _rv: v8::ReturnValue, ) { if let Ok(cb) = arg0_to_cb(scope, args) { JsRuntime::state(scope) .borrow_mut() .js_macrotask_cbs .push(cb); } } fn set_promise_reject_callback( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { if let Ok(new) = arg0_to_cb(scope, args) { if let Some(old) = JsRuntime::state(scope) .borrow_mut() .js_promise_reject_cb .replace(new) { let old = v8::Local::new(scope, old); rv.set(old.into()); } } } fn set_uncaught_exception_callback( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { if let Ok(new) = arg0_to_cb(scope, args) { if let Some(old) = JsRuntime::state(scope) .borrow_mut() .js_uncaught_exception_cb .replace(new) { let old = v8::Local::new(scope, old); rv.set(old.into()); } } } fn arg0_to_cb( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, ) -> Result<v8::Global<v8::Function>, ()> { v8::Local::<v8::Function>::try_from(args.get(0)) .map(|cb| v8::Global::new(scope, cb)) .map_err(|err| throw_type_error(scope, err.to_string())) } fn eval_context( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { let source = match v8::Local::<v8::String>::try_from(args.get(0)) { Ok(s) => s, Err(_) => { throw_type_error(scope, "Missing first argument"); return; } }; let url = match v8::Local::<v8::String>::try_from(args.get(1)) { Ok(s) => match resolve_url_or_path(&s.to_rust_string_lossy(scope)) { Ok(s) => Some(s), Err(err) => { throw_type_error(scope, &format!("Invalid specifier: {}", err)); return; } }, Err(_) => None, }; #[derive(Serialize)] struct Output<'s>(Option<serde_v8::Value<'s>>, Option<ErrInfo<'s>>); #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct ErrInfo<'s> { thrown: serde_v8::Value<'s>, is_native_error: bool, is_compile_error: bool, } let tc_scope = &mut v8::TryCatch::new(scope); let name = v8::String::new( tc_scope, url.as_ref().map_or(crate::DUMMY_SPECIFIER, Url::as_str), ) .unwrap(); let origin = script_origin(tc_scope, name); let maybe_script = v8::Script::compile(tc_scope, source, Some(&origin)); if maybe_script.is_none() { assert!(tc_scope.has_caught()); let exception = tc_scope.exception().unwrap(); let output = Output( None, Some(ErrInfo { thrown: exception.into(), is_native_error: is_instance_of_error(tc_scope, exception), is_compile_error: true, }), ); rv.set(to_v8(tc_scope, output).unwrap()); return; } let result = maybe_script.unwrap().run(tc_scope); if result.is_none() { assert!(tc_scope.has_caught()); let exception = tc_scope.exception().unwrap(); let output = Output( None, Some(ErrInfo { thrown: exception.into(), is_native_error: is_instance_of_error(tc_scope, exception), is_compile_error: false, }), ); rv.set(to_v8(tc_scope, output).unwrap()); return; } let output = Output(Some(result.unwrap().into()), None); rv.set(to_v8(tc_scope, output).unwrap()); } /// This binding should be used if there's a custom console implementation /// available. Using it will make sure that proper stack frames are displayed /// in the inspector console. /// /// Each method on console object should be bound to this function, eg: /// ```ignore /// function wrapConsole(consoleFromDeno, consoleFromV8) { /// const callConsole = core.callConsole; /// /// for (const key of Object.keys(consoleFromV8)) { /// if (consoleFromDeno.hasOwnProperty(key)) { /// consoleFromDeno[key] = callConsole.bind( /// consoleFromDeno, /// consoleFromV8[key], /// consoleFromDeno[key], /// ); /// } /// } /// } /// ``` /// /// Inspired by: /// https://github.com/nodejs/node/blob/1317252dfe8824fd9cfee125d2aaa94004db2f3b/src/inspector_js_api.cc#L194-L222 fn call_console( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, _rv: v8::ReturnValue, ) { assert!(args.length() >= 2); assert!(args.get(0).is_function()); assert!(args.get(1).is_function()); let mut call_args = vec![]; for i in 2..args.length() { call_args.push(args.get(i)); } let receiver = args.this(); let inspector_console_method = v8::Local::<v8::Function>::try_from(args.get(0)).unwrap(); let deno_console_method = v8::Local::<v8::Function>::try_from(args.get(1)).unwrap(); inspector_console_method.call(scope, receiver.into(), &call_args); deno_console_method.call(scope, receiver.into(), &call_args); } fn set_wasm_streaming_callback( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, _rv: v8::ReturnValue, ) { use crate::ops_builtin::WasmStreamingResource; let cb = match arg0_to_cb(scope, args) { Ok(cb) => cb, Err(()) => return, }; let state_rc = JsRuntime::state(scope); let mut state = state_rc.borrow_mut(); // The callback to pass to the v8 API has to be a unit type, so it can't // borrow or move any local variables. Therefore, we're storing the JS // callback in a JsRuntimeState slot. if let slot @ None = &mut state.js_wasm_streaming_cb { slot.replace(cb); } else { return throw_type_error( scope, "Deno.core.setWasmStreamingCallback() already called", ); } scope.set_wasm_streaming_callback(|scope, arg, wasm_streaming| { let (cb_handle, streaming_rid) = { let state_rc = JsRuntime::state(scope); let state = state_rc.borrow(); let cb_handle = state.js_wasm_streaming_cb.as_ref().unwrap().clone(); let streaming_rid = state .op_state .borrow_mut() .resource_table .add(WasmStreamingResource(RefCell::new(wasm_streaming))); (cb_handle, streaming_rid) }; let undefined = v8::undefined(scope); let rid = serde_v8::to_v8(scope, streaming_rid).unwrap(); cb_handle .open(scope) .call(scope, undefined.into(), &[arg, rid]); }); } fn encode( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { let text = match v8::Local::<v8::String>::try_from(args.get(0)) { Ok(s) => s, Err(_) => { throw_type_error(scope, "Invalid argument"); return; } }; let text_str = text.to_rust_string_lossy(scope); let zbuf: ZeroCopyBuf = text_str.into_bytes().into(); rv.set(to_v8(scope, zbuf).unwrap()) } fn decode( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { let zero_copy: ZeroCopyBuf = match serde_v8::from_v8(scope, args.get(0)) { Ok(zbuf) => zbuf, Err(_) => { throw_type_error(scope, "Invalid argument"); return; } }; let buf = &zero_copy; // Strip BOM let buf = if buf.len() >= 3 && buf[0] == 0xef && buf[1] == 0xbb && buf[2] == 0xbf { &buf[3..] } else { buf }; // If `String::new_from_utf8()` returns `None`, this means that the // length of the decoded string would be longer than what V8 can // handle. In this case we return `RangeError`. // // For more details see: // - https://encoding.spec.whatwg.org/#dom-textdecoder-decode // - https://github.com/denoland/deno/issues/6649 // - https://github.com/v8/v8/blob/d68fb4733e39525f9ff0a9222107c02c28096e2a/include/v8.h#L3277-L3278 match v8::String::new_from_utf8(scope, buf, v8::NewStringType::Normal) { Some(text) => rv.set(text.into()), None => { let msg = v8::String::new(scope, "string too long").unwrap(); let exception = v8::Exception::range_error(scope, msg); scope.throw_exception(exception); } }; } struct SerializeDeserialize<'a> { host_objects: Option<v8::Local<'a, v8::Array>>, } impl<'a> v8::ValueSerializerImpl for SerializeDeserialize<'a> { #[allow(unused_variables)] fn throw_data_clone_error<'s>( &mut self, scope: &mut v8::HandleScope<'s>, message: v8::Local<'s, v8::String>, ) { let error = v8::Exception::error(scope, message); scope.throw_exception(error); } fn get_shared_array_buffer_id<'s>( &mut self, scope: &mut HandleScope<'s>, shared_array_buffer: Local<'s, SharedArrayBuffer>, ) -> Option<u32> { let state_rc = JsRuntime::state(scope); let state = state_rc.borrow_mut(); if let Some(shared_array_buffer_store) = &state.shared_array_buffer_store { let backing_store = shared_array_buffer.get_backing_store(); let id = shared_array_buffer_store.insert(backing_store); Some(id) } else { None } } fn get_wasm_module_transfer_id( &mut self, scope: &mut HandleScope<'_>, module: Local<v8::WasmModuleObject>, ) -> Option<u32> { let state_rc = JsRuntime::state(scope); let state = state_rc.borrow_mut(); if let Some(compiled_wasm_module_store) = &state.compiled_wasm_module_store { let compiled_wasm_module = module.get_compiled_module(); let id = compiled_wasm_module_store.insert(compiled_wasm_module); Some(id) } else { None } } fn write_host_object<'s>( &mut self, scope: &mut v8::HandleScope<'s>, object: v8::Local<'s, v8::Object>, value_serializer: &mut dyn v8::ValueSerializerHelper, ) -> Option<bool> { if let Some(host_objects) = self.host_objects { for i in 0..host_objects.length() { let value = host_objects.get_index(scope, i).unwrap(); if value == object { value_serializer.write_uint32(i); return Some(true); } } } let message = v8::String::new(scope, "Unsupported object type").unwrap(); self.throw_data_clone_error(scope, message); None } } impl<'a> v8::ValueDeserializerImpl for SerializeDeserialize<'a> { fn get_shared_array_buffer_from_id<'s>( &mut self, scope: &mut HandleScope<'s>, transfer_id: u32, ) -> Option<Local<'s, SharedArrayBuffer>> { let state_rc = JsRuntime::state(scope); let state = state_rc.borrow_mut(); if let Some(shared_array_buffer_store) = &state.shared_array_buffer_store { let backing_store = shared_array_buffer_store.take(transfer_id)?; let shared_array_buffer = v8::SharedArrayBuffer::with_backing_store(scope, &backing_store); Some(shared_array_buffer) } else { None } } fn get_wasm_module_from_id<'s>( &mut self, scope: &mut HandleScope<'s>, clone_id: u32, ) -> Option<Local<'s, v8::WasmModuleObject>> { let state_rc = JsRuntime::state(scope); let state = state_rc.borrow_mut(); if let Some(compiled_wasm_module_store) = &state.compiled_wasm_module_store { let compiled_module = compiled_wasm_module_store.take(clone_id)?; v8::WasmModuleObject::from_compiled_module(scope, &compiled_module) } else { None } } fn read_host_object<'s>( &mut self, scope: &mut v8::HandleScope<'s>, value_deserializer: &mut dyn v8::ValueDeserializerHelper, ) -> Option<v8::Local<'s, v8::Object>> { if let Some(host_objects) = self.host_objects { let mut i = 0; if !value_deserializer.read_uint32(&mut i) { return None; } let maybe_value = host_objects.get_index(scope, i); if let Some(value) = maybe_value { return value.to_object(scope); } } let message = v8::String::new(scope, "Failed to deserialize host object").unwrap(); let error = v8::Exception::error(scope, message); scope.throw_exception(error); None } } fn serialize( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { let value = args.get(0); let options: Option<SerializeDeserializeOptions> = match serde_v8::from_v8(scope, args.get(1)) { Ok(opts) => opts, Err(_) => { throw_type_error(scope, "Invalid argument 2"); return; } }; let options = options.unwrap_or(SerializeDeserializeOptions { host_objects: None, transfered_array_buffers: None, }); let host_objects = match options.host_objects { Some(value) => match v8::Local::<v8::Array>::try_from(value.v8_value) { Ok(host_objects) => Some(host_objects), Err(_) => { throw_type_error(scope, "host_objects not an array"); return; } }, None => None, }; let transfered_array_buffers = match options.transfered_array_buffers { Some(value) => match v8::Local::<v8::Array>::try_from(value.v8_value) { Ok(transfered_array_buffers) => Some(transfered_array_buffers), Err(_) => { throw_type_error(scope, "transfered_array_buffers not an array"); return; } }, None => None, }; let serialize_deserialize = Box::new(SerializeDeserialize { host_objects }); let mut value_serializer = v8::ValueSerializer::new(scope, serialize_deserialize); value_serializer.write_header(); if let Some(transfered_array_buffers) = transfered_array_buffers { let state_rc = JsRuntime::state(scope); let state = state_rc.borrow_mut(); for i in 0..transfered_array_buffers.length() { let i = v8::Number::new(scope, i as f64).into(); let buf = transfered_array_buffers.get(scope, i).unwrap(); let buf = match v8::Local::<v8::ArrayBuffer>::try_from(buf) { Ok(buf) => buf, Err(_) => { throw_type_error( scope, "item in transfered_array_buffers not an ArrayBuffer", ); return; } }; if let Some(shared_array_buffer_store) = &state.shared_array_buffer_store { // TODO(lucacasonato): we need to check here that the buffer is not // already detached. We can not do that because V8 does not provide // a way to check if a buffer is already detached. if !buf.is_detachable() { throw_type_error( scope, "item in transfered_array_buffers is not transferable", ); return; } let backing_store = buf.get_backing_store(); buf.detach(); let id = shared_array_buffer_store.insert(backing_store); value_serializer.transfer_array_buffer(id, buf); let id = v8::Number::new(scope, id as f64).into(); transfered_array_buffers.set(scope, i, id); } } } match value_serializer.write_value(scope.get_current_context(), value) { Some(true) => { let vector = value_serializer.release(); let zbuf: ZeroCopyBuf = vector.into(); rv.set(to_v8(scope, zbuf).unwrap()); } _ => { throw_type_error(scope, "Failed to serialize response"); } } } #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct SerializeDeserializeOptions<'a> { host_objects: Option<serde_v8::Value<'a>>, transfered_array_buffers: Option<serde_v8::Value<'a>>, } fn deserialize( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { let zero_copy: ZeroCopyBuf = match serde_v8::from_v8(scope, args.get(0)) { Ok(zbuf) => zbuf, Err(_) => { throw_type_error(scope, "Invalid argument 1"); return; } }; let options: Option<SerializeDeserializeOptions> = match serde_v8::from_v8(scope, args.get(1)) { Ok(opts) => opts, Err(_) => { throw_type_error(scope, "Invalid argument 2"); return; } }; let options = options.unwrap_or(SerializeDeserializeOptions { host_objects: None, transfered_array_buffers: None, }); let host_objects = match options.host_objects { Some(value) => match v8::Local::<v8::Array>::try_from(value.v8_value) { Ok(host_objects) => Some(host_objects), Err(_) => { throw_type_error(scope, "host_objects not an array"); return; } }, None => None, }; let transfered_array_buffers = match options.transfered_array_buffers { Some(value) => match v8::Local::<v8::Array>::try_from(value.v8_value) { Ok(transfered_array_buffers) => Some(transfered_array_buffers), Err(_) => { throw_type_error(scope, "transfered_array_buffers not an array"); return; } }, None => None, }; let serialize_deserialize = Box::new(SerializeDeserialize { host_objects }); let mut value_deserializer = v8::ValueDeserializer::new(scope, serialize_deserialize, &zero_copy); let parsed_header = value_deserializer .read_header(scope.get_current_context()) .unwrap_or_default(); if !parsed_header { let msg = v8::String::new(scope, "could not deserialize value").unwrap(); let exception = v8::Exception::range_error(scope, msg); scope.throw_exception(exception); return; } if let Some(transfered_array_buffers) = transfered_array_buffers { let state_rc = JsRuntime::state(scope); let state = state_rc.borrow_mut(); if let Some(shared_array_buffer_store) = &state.shared_array_buffer_store { for i in 0..transfered_array_buffers.length() { let i = v8::Number::new(scope, i as f64).into(); let id_val = transfered_array_buffers.get(scope, i).unwrap(); let id = match id_val.number_value(scope) { Some(id) => id as u32, None => { throw_type_error( scope, "item in transfered_array_buffers not number", ); return; } }; if let Some(backing_store) = shared_array_buffer_store.take(id) { let array_buffer = v8::ArrayBuffer::with_backing_store(scope, &backing_store); value_deserializer.transfer_array_buffer(id, array_buffer); transfered_array_buffers.set(scope, id_val, array_buffer.into()); } else { throw_type_error( scope, "transfered array buffer not present in shared_array_buffer_store", ); return; } } } } let value = value_deserializer.read_value(scope.get_current_context()); match value { Some(deserialized) => rv.set(deserialized), None => { let msg = v8::String::new(scope, "could not deserialize value").unwrap(); let exception = v8::Exception::range_error(scope, msg); scope.throw_exception(exception); } }; } fn queue_microtask( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, _rv: v8::ReturnValue, ) { match v8::Local::<v8::Function>::try_from(args.get(0)) { Ok(f) => scope.enqueue_microtask(f), Err(_) => { throw_type_error(scope, "Invalid argument"); } }; } fn create_host_object( scope: &mut v8::HandleScope, _args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { let template = v8::ObjectTemplate::new(scope); template.set_internal_field_count(1); if let Some(obj) = template.new_instance(scope) { rv.set(obj.into()); }; } /// Called by V8 during `JsRuntime::instantiate_module`. /// /// This function borrows `ModuleMap` from the isolate slot, /// so it is crucial to ensure there are no existing borrows /// of `ModuleMap` when `JsRuntime::instantiate_module` is called. pub fn module_resolve_callback<'s>( context: v8::Local<'s, v8::Context>, specifier: v8::Local<'s, v8::String>, _import_assertions: v8::Local<'s, v8::FixedArray>, referrer: v8::Local<'s, v8::Module>, ) -> Option<v8::Local<'s, v8::Module>> { let scope = &mut unsafe { v8::CallbackScope::new(context) }; let module_map_rc = JsRuntime::module_map(scope); let module_map = module_map_rc.borrow(); let referrer_global = v8::Global::new(scope, referrer); let referrer_info = module_map .get_info(&referrer_global) .expect("ModuleInfo not found"); let referrer_name = referrer_info.name.to_string(); let specifier_str = specifier.to_rust_string_lossy(scope); let maybe_module = module_map.resolve_callback(scope, &specifier_str, &referrer_name); if let Some(module) = maybe_module { return Some(module); } let msg = format!( r#"Cannot resolve module "{}" from "{}""#, specifier_str, referrer_name ); throw_type_error(scope, msg); None } // Returns promise details or throw TypeError, if argument passed isn't a Promise. // Promise details is a js_two elements array. // promise_details = [State, Result] // State = enum { Pending = 0, Fulfilled = 1, Rejected = 2} // Result = PromiseResult<T> | PromiseError fn get_promise_details( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { let promise = match v8::Local::<v8::Promise>::try_from(args.get(0)) { Ok(val) => val, Err(_) => { throw_type_error(scope, "Invalid argument"); return; } }; #[derive(Serialize)] struct PromiseDetails<'s>(u32, Option<serde_v8::Value<'s>>); match promise.state() { v8::PromiseState::Pending => { rv.set(to_v8(scope, PromiseDetails(0, None)).unwrap()); } v8::PromiseState::Fulfilled => { let promise_result = promise.result(scope); rv.set( to_v8(scope, PromiseDetails(1, Some(promise_result.into()))).unwrap(), ); } v8::PromiseState::Rejected => { let promise_result = promise.result(scope); rv.set( to_v8(scope, PromiseDetails(2, Some(promise_result.into()))).unwrap(), ); } } } // Based on https://github.com/nodejs/node/blob/1e470510ff74391d7d4ec382909ea8960d2d2fbc/src/node_util.cc // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. fn get_proxy_details( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { // Return undefined if it's not a proxy. let proxy = match v8::Local::<v8::Proxy>::try_from(args.get(0)) { Ok(val) => val, Err(_) => { return; } }; let target = proxy.get_target(scope); let handler = proxy.get_handler(scope); let p: (serde_v8::Value, serde_v8::Value) = (target.into(), handler.into()); rv.set(to_v8(scope, p).unwrap()); } fn is_proxy( scope: &mut v8::HandleScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { rv.set(v8::Boolean::new(scope, args.get(0).is_proxy()).into()) } fn throw_type_error(scope: &mut v8::HandleScope, message: impl AsRef<str>) { let message = v8::String::new(scope, message.as_ref()).unwrap(); let exception = v8::Exception::type_error(scope, message); scope.throw_exception(exception); } fn memory_usage( scope: &mut v8::HandleScope, _args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue, ) { let stats = get_memory_usage(scope); rv.set(to_v8(scope, stats).unwrap()); } // HeapStats stores values from a isolate.get_heap_statistics() call #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct MemoryUsage { rss: usize, heap_total: usize, heap_used: usize, external: usize, // TODO: track ArrayBuffers, would require using a custom allocator to track // but it's otherwise a subset of external so can be indirectly tracked // array_buffers: usize, } fn get_memory_usage(isolate: &mut v8::Isolate) -> MemoryUsage { let mut s = v8::HeapStatistics::default(); isolate.get_heap_statistics(&mut s); MemoryUsage { rss: s.total_physical_size(), heap_total: s.total_heap_size(), heap_used: s.used_heap_size(), external: s.external_memory(), } }
29.788171
114
0.653606
1a13c0d7705a13086a72815ba65ffd5735cbda7c
11,779
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 OR MIT // Example from Firecracker virtio block device // We test the parse function against an arbitrary guest memory #![allow(dead_code)] #![allow(unused_variables)] macro_rules! error { ( $( $x:expr ),* ) => {}; } struct MyError {} unsafe impl kani::Invariant for MyError { fn is_valid(&self) -> bool { true } } #[derive(Default, Clone, Copy)] pub struct GuestAddress(pub u64); unsafe impl kani::Invariant for GuestAddress { fn is_valid(&self) -> bool { true } } static mut TRACK_CHECKED_OFFSET_NONE: bool = false; static mut TRACK_READ_OBJ: Option<GuestAddress> = None; pub struct GuestMemoryMmap {} impl GuestMemoryMmap { fn checked_offset(&self, base: GuestAddress, offset: usize) -> Option<GuestAddress> { let mut retval = None; if kani::any() { if let Some(sum) = base.0.checked_add(offset as u64) { retval = Some(GuestAddress(sum)) } } unsafe { if retval.is_none() && !TRACK_CHECKED_OFFSET_NONE { TRACK_CHECKED_OFFSET_NONE = true; } } return retval; } fn read_obj<T: kani::Invariant>(&self, addr: GuestAddress) -> Result<T, MyError> { // This assertion means that no descriptor is read more than once unsafe { if let Some(prev_addr) = TRACK_READ_OBJ { assert!(prev_addr.0 != addr.0); } if kani::any() && TRACK_READ_OBJ.is_none() { TRACK_READ_OBJ = Some(addr); } } if kani::any() { Ok(kani::any::<T>()) } else { Err(kani::any::<MyError>()) } } fn read_obj_request_header(&self, addr: GuestAddress) -> Result<RequestHeader, Error> { if kani::any() { Ok(kani::any::<RequestHeader>()) } else { Err(kani::any::<Error>()) } } } pub const VIRTQ_DESC_F_NEXT: u16 = 0x1; pub const VIRTQ_DESC_F_WRITE: u16 = 0x2; /// A virtio descriptor constraints with C representive. #[repr(C)] #[derive(Default, Clone, Copy)] struct Descriptor { addr: u64, len: u32, flags: u16, next: u16, } unsafe impl kani::Invariant for Descriptor { fn is_valid(&self) -> bool { true } } /// A virtio descriptor chain. pub struct DescriptorChain<'a> { desc_table: GuestAddress, queue_size: u16, ttl: u16, // used to prevent infinite chain cycles /// Reference to guest memory pub mem: &'a GuestMemoryMmap, /// Index into the descriptor table pub index: u16, /// Guest physical address of device specific data pub addr: GuestAddress, /// Length of device specific data pub len: u32, /// Includes next, write, and indirect bits pub flags: u16, /// Index into the descriptor table of the next descriptor if flags has /// the next bit set pub next: u16, } impl<'a> DescriptorChain<'a> { fn checked_new( mem: &GuestMemoryMmap, desc_table: GuestAddress, queue_size: u16, index: u16, ) -> Option<DescriptorChain> { if index >= queue_size { return None; } let desc_head = mem.checked_offset(desc_table, (index as usize) * 16)?; mem.checked_offset(desc_head, 16)?; // These reads can't fail unless Guest memory is hopelessly broken. let desc: Descriptor = match mem.read_obj(desc_head) { Ok(ret) => ret, Err(_) => { // TODO log address error!("Failed to read from memory"); return None; } }; let chain = DescriptorChain { mem, desc_table, queue_size, ttl: queue_size, index, addr: GuestAddress(desc.addr), len: desc.len, flags: desc.flags, next: desc.next, }; if chain.is_valid() { Some(chain) } else { None } } // Kani change: add check to avoid self-loops fn is_valid(&self) -> bool { !self.has_next() || (self.next < self.queue_size && self.next != self.index) } /// Gets if this descriptor chain has another descriptor chain linked after it. pub fn has_next(&self) -> bool { self.flags & VIRTQ_DESC_F_NEXT != 0 && self.ttl > 1 } /// If the driver designated this as a write only descriptor. /// /// If this is false, this descriptor is read only. /// Write only means the the emulated device can write and the driver can read. pub fn is_write_only(&self) -> bool { self.flags & VIRTQ_DESC_F_WRITE != 0 } /// Gets the next descriptor in this descriptor chain, if there is one. /// /// Note that this is distinct from the next descriptor chain returned by `AvailIter`, which is /// the head of the next _available_ descriptor chain. pub fn next_descriptor(&self) -> Option<DescriptorChain<'a>> { if self.has_next() { DescriptorChain::checked_new(self.mem, self.desc_table, self.queue_size, self.next).map( |mut c| { c.ttl = self.ttl - 1; c }, ) } else { None } } } #[derive(Copy, Clone, Default)] #[repr(C)] pub struct RequestHeader { request_type: u32, _reserved: u32, sector: u64, } unsafe impl kani::Invariant for RequestHeader { fn is_valid(&self) -> bool { true } } impl RequestHeader { pub fn new(request_type: u32, sector: u64) -> RequestHeader { RequestHeader { request_type, _reserved: 0, sector } } fn read_from(memory: &GuestMemoryMmap, addr: GuestAddress) -> Result<Self, Error> { memory.read_obj_request_header(addr) } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum RequestType { In, Out, Flush, GetDeviceID, Unsupported(u32), } pub const VIRTIO_BLK_T_IN: u32 = 0; pub const VIRTIO_BLK_T_OUT: u32 = 1; pub const VIRTIO_BLK_T_FLUSH: u32 = 4; pub const VIRTIO_BLK_T_GET_ID: u32 = 8; impl From<u32> for RequestType { fn from(value: u32) -> Self { match value { VIRTIO_BLK_T_IN => RequestType::In, VIRTIO_BLK_T_OUT => RequestType::Out, VIRTIO_BLK_T_FLUSH => RequestType::Flush, VIRTIO_BLK_T_GET_ID => RequestType::GetDeviceID, t => RequestType::Unsupported(t), } } } #[derive(Debug)] pub enum Error { /// Guest gave us too few descriptors in a descriptor chain. DescriptorChainTooShort, /// Guest gave us a descriptor that was too short to use. DescriptorLengthTooSmall, /// Getting a block's metadata fails for any reason. //TODO: Issue Padstone-4795 //GetFileMetadata(std::io::Error), /// Guest gave us bad memory addresses. GuestMemory, /// The requested operation would cause a seek beyond disk end. InvalidOffset, /// Guest gave us a read only descriptor that protocol says to write to. UnexpectedReadOnlyDescriptor, /// Guest gave us a write only descriptor that protocol says to read from. UnexpectedWriteOnlyDescriptor, } unsafe impl kani::Invariant for Error { fn is_valid(&self) -> bool { matches!( *self, Error::DescriptorChainTooShort | Error::DescriptorLengthTooSmall | Error::GuestMemory | Error::InvalidOffset | Error::UnexpectedReadOnlyDescriptor ) || matches!(*self, Error::UnexpectedWriteOnlyDescriptor) } } pub struct Request { pub request_type: RequestType, pub data_len: u32, pub status_addr: GuestAddress, sector: u64, data_addr: GuestAddress, } impl Request { pub fn parse(avail_desc: &DescriptorChain, mem: &GuestMemoryMmap) -> Result<Request, Error> { // The head contains the request type which MUST be readable. if avail_desc.is_write_only() { return Err(Error::UnexpectedWriteOnlyDescriptor); } let request_header = RequestHeader::read_from(mem, avail_desc.addr)?; let mut req = Request { request_type: RequestType::from(request_header.request_type), sector: request_header.sector, data_addr: GuestAddress(0), data_len: 0, status_addr: GuestAddress(0), }; let data_desc: DescriptorChain; let status_desc: DescriptorChain; let desc = avail_desc.next_descriptor().ok_or(Error::DescriptorChainTooShort)?; if !desc.has_next() { status_desc = desc; // Only flush requests are allowed to skip the data descriptor. if req.request_type != RequestType::Flush { return Err(Error::DescriptorChainTooShort); } } else { data_desc = desc; // Kani change: add chain loop check if data_desc.next == avail_desc.index { return Err(Error::DescriptorChainTooShort); } status_desc = data_desc.next_descriptor().ok_or(Error::DescriptorChainTooShort)?; if data_desc.is_write_only() && req.request_type == RequestType::Out { return Err(Error::UnexpectedWriteOnlyDescriptor); } if !data_desc.is_write_only() && req.request_type == RequestType::In { return Err(Error::UnexpectedReadOnlyDescriptor); } if !data_desc.is_write_only() && req.request_type == RequestType::GetDeviceID { return Err(Error::UnexpectedReadOnlyDescriptor); } // Check that the address of the data descriptor is valid in guest memory. let _ = mem .checked_offset(data_desc.addr, data_desc.len as usize) .ok_or(Error::GuestMemory)?; req.data_addr = data_desc.addr; req.data_len = data_desc.len; } // The status MUST always be writable. if !status_desc.is_write_only() { return Err(Error::UnexpectedReadOnlyDescriptor); } if status_desc.len < 1 { return Err(Error::DescriptorLengthTooSmall); } // Check that the address of the status descriptor is valid in guest memory. // We will write an u32 status here after executing the request. let _ = mem .checked_offset(status_desc.addr, std::mem::size_of::<u32>()) .ok_or(Error::GuestMemory)?; req.status_addr = status_desc.addr; Ok(req) } } fn is_nonzero_pow2(x: u16) -> bool { unsafe { (x != 0) && ((x & (x - 1)) == 0) } } fn main() { let mem = GuestMemoryMmap {}; let queue_size: u16 = kani::any(); if !is_nonzero_pow2(queue_size) { return; } let index: u16 = kani::any(); let desc_table = GuestAddress(kani::any::<u64>() & 0xffff_ffff_ffff_fff0); let desc = DescriptorChain::checked_new(&mem, desc_table, queue_size, index); match desc { Some(x) => { let addr = desc_table.0 + (index as u64) * 16; //< this arithmetic cannot fail unsafe { if let Some(v) = TRACK_READ_OBJ { assert!(v.0 == addr) } } assert!(x.index == index); assert!(x.index < queue_size); if x.has_next() { assert!(x.next < queue_size); } let req = Request::parse(&x, &mem); if let Ok(req) = req { unsafe { assert!(!TRACK_CHECKED_OFFSET_NONE); } } } None => assert!(true), }; }
30.436693
100
0.588165
09abe52c4dcb99584acbd816ff611cfa1eecf900
2,216
#[doc = "Reader of register CPUIRQSEL25"] pub type R = crate::R<u32, super::CPUIRQSEL25>; #[doc = "Writer for register CPUIRQSEL25"] pub type W = crate::W<u32, super::CPUIRQSEL25>; #[doc = "Register CPUIRQSEL25 `reset()`'s with value 0x26"] impl crate::ResetValue for super::CPUIRQSEL25 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x26 } } #[doc = "6:0\\] Read only selection value\n\nValue on reset: 38"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum EV_A { #[doc = "38: DMA bus error, corresponds to UDMA0:ERROR.STATUS"] DMA_ERR = 38, } impl From<EV_A> for u8 { #[inline(always)] fn from(variant: EV_A) -> Self { variant as _ } } #[doc = "Reader of field `EV`"] pub type EV_R = crate::R<u8, EV_A>; impl EV_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, EV_A> { use crate::Variant::*; match self.bits { 38 => Val(EV_A::DMA_ERR), i => Res(i), } } #[doc = "Checks if the value of the field is `DMA_ERR`"] #[inline(always)] pub fn is_dma_err(&self) -> bool { *self == EV_A::DMA_ERR } } #[doc = "Write proxy for field `EV`"] pub struct EV_W<'a> { w: &'a mut W, } impl<'a> EV_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: EV_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "DMA bus error, corresponds to UDMA0:ERROR.STATUS"] #[inline(always)] pub fn dma_err(self) -> &'a mut W { self.variant(EV_A::DMA_ERR) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x7f) | ((value as u32) & 0x7f); self.w } } impl R { #[doc = "Bits 0:6 - 6:0\\] Read only selection value"] #[inline(always)] pub fn ev(&self) -> EV_R { EV_R::new((self.bits & 0x7f) as u8) } } impl W { #[doc = "Bits 0:6 - 6:0\\] Read only selection value"] #[inline(always)] pub fn ev(&mut self) -> EV_W { EV_W { w: self } } }
26.698795
70
0.560469
919f9b4c1d14479333abb95c339f3a18a0323306
4,360
use crate::error::Error; use crate::media::dtls_transport::DTLSTransport; use crate::media::rtp::rtp_sender::RTPSenderInternal; use crate::media::rtp::SSRC; use srtp::session::Session; use srtp::stream::Stream; use anyhow::Result; use bytes::Bytes; use std::sync::Arc; use tokio::sync::Mutex; /// SrtpWriterFuture blocks Read/Write calls until /// the SRTP Session is available pub(crate) struct SrtpWriterFuture { pub(crate) ssrc: SSRC, pub(crate) rtp_sender: Arc<Mutex<RTPSenderInternal>>, pub(crate) rtp_transport: Arc<DTLSTransport>, pub(crate) rtcp_read_stream: Mutex<Option<Arc<Stream>>>, // atomic.Value // * pub(crate) rtp_write_session: Mutex<Option<Arc<Session>>>, // atomic.Value // * } impl SrtpWriterFuture { async fn init(&self, return_when_no_srtp: bool) -> Result<()> { { let mut rx = self.rtp_transport.srtp_ready_rx.lock().await; if let Some(srtp_ready_rx) = &mut *rx { let mut rtp_sender = self.rtp_sender.lock().await; if return_when_no_srtp { tokio::select! { _ = rtp_sender.stop_called_rx.recv()=> return Err(Error::ErrClosedPipe.into()), _ = srtp_ready_rx.recv() =>{} else => { //TODO: How to implement default? return Ok(()); } } } else { tokio::select! { _ = rtp_sender.stop_called_rx.recv()=> return Err(Error::ErrClosedPipe.into()), _ = srtp_ready_rx.recv() =>{} } } } } if let Some(srtcp_session) = self.rtp_transport.get_srtcp_session().await { //TODO: use srtcp_session.open(self.ssrc).await? let rtcp_read_stream = Arc::new(srtcp_session.listen(self.ssrc).await?); let mut stream = self.rtcp_read_stream.lock().await; *stream = Some(rtcp_read_stream); } { let srtp_session = self.rtp_transport.get_srtp_session().await; let mut session = self.rtp_write_session.lock().await; *session = srtp_session; } Ok(()) } pub async fn close(&self) -> Result<()> { let stream = self.rtcp_read_stream.lock().await; if let Some(rtcp_read_stream) = &*stream { rtcp_read_stream.close().await } else { Ok(()) } } pub async fn read(&self, b: &mut [u8]) -> Result<usize> { { let stream = self.rtcp_read_stream.lock().await; if let Some(rtcp_read_stream) = &*stream { return rtcp_read_stream.read(b).await; } } self.init(false).await?; { let stream = self.rtcp_read_stream.lock().await; if let Some(rtcp_read_stream) = &*stream { rtcp_read_stream.read(b).await } else { Err(Error::ErrDtlsTransportNotStarted.into()) } } } pub async fn write_rtp(&self, packet: &rtp::packet::Packet) -> Result<usize> { { let session = self.rtp_write_session.lock().await; if let Some(rtp_write_session) = &*session { return rtp_write_session.write_rtp(packet).await; } } self.init(true).await?; { let session = self.rtp_write_session.lock().await; if let Some(rtp_write_session) = &*session { rtp_write_session.write_rtp(packet).await } else { Err(Error::ErrDtlsTransportNotStarted.into()) } } } pub async fn write(&self, b: &Bytes) -> Result<usize> { { let session = self.rtp_write_session.lock().await; if let Some(rtp_write_session) = &*session { return rtp_write_session.write(b, true).await; } } self.init(true).await?; { let session = self.rtp_write_session.lock().await; if let Some(rtp_write_session) = &*session { rtp_write_session.write(b, true).await } else { Err(Error::ErrDtlsTransportNotStarted.into()) } } } }
33.030303
103
0.538303
01d8c71ffd54b574d21224051e7cb33802876057
2,135
// https://leetcode-cn.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/ // Runtime: 84 ms // Memory Usage: 22.6 MB pub fn count_sub_trees(n: i32, edges: Vec<Vec<i32>>, labels: String) -> Vec<i32> { let n = n as usize; let mut adj = vec![Vec::new(); n]; for e in edges { let u = e[0] as usize; let v = e[1] as usize; adj[u].push(v); adj[v].push(u); } let mut visited = vec![false; n]; let mut counts: Vec<usize> = vec![0; 26]; let mut res = vec![0; n]; let labels = labels.bytes().collect::<Vec<u8>>(); dfs(0, &mut visited, &mut counts, &mut res, &adj, &labels); res } fn dfs( u: usize, visited: &mut Vec<bool>, counts: &mut Vec<usize>, sizes: &mut Vec<i32>, adj: &[Vec<usize>], labels: &[u8], ) { visited[u] = true; let i = (labels[u] - b'a') as usize; let last_count = counts[i]; counts[i] += 1; for &v in adj[u].iter() { if !visited[v] { dfs(v, visited, counts, sizes, adj, labels); } } sizes[u] = (counts[i] - last_count) as i32; } // breadth_first_search depth_first_search #[test] fn test2_1519() { use leetcode_prelude::vec2; assert_eq!( count_sub_trees( 7, vec2![[0, 1], [0, 2], [1, 4], [1, 5], [2, 3], [2, 6]], "abaedcd".to_string() ), vec![2, 1, 1, 1, 1, 1, 1] ); assert_eq!( count_sub_trees(4, vec2![[0, 1], [1, 2], [0, 3]], "bbbb".to_string()), vec![4, 2, 1, 1] ); assert_eq!( count_sub_trees( 5, vec2![[0, 1], [0, 2], [1, 3], [0, 4]], "aabab".to_string() ), vec![3, 2, 1, 1, 1] ); assert_eq!( count_sub_trees( 6, vec2![[0, 1], [0, 2], [1, 3], [3, 4], [4, 5]], "cbabaa".to_string() ), vec![1, 2, 1, 1, 2, 1] ); assert_eq!( count_sub_trees( 7, vec2![[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]], "aaabaaa".to_string() ), vec![6, 5, 4, 1, 3, 2, 1] ); }
26.358025
88
0.459016
e47e9e2adb963e3b86010108bb7fd62d1d3da9d6
14,259
use embedded_time::duration::{Extensions, Generic}; use crate::endpoint::{Endpoint, EndpointAddress, EndpointDirection, EndpointType}; use crate::{Result, UsbDirection, UsbError}; use core::cell::RefCell; use core::mem; use core::ptr; use core::sync::atomic::{AtomicPtr, Ordering}; /// A trait for device-specific USB peripherals. Implement this to add support for a new hardware /// platform. /// /// The UsbBus is shared by reference between the global [`UsbDevice`](crate::device::UsbDevice) as /// well as [`UsbClass`](crate::class::UsbClass)es, and therefore any required mutability must be /// implemented using interior mutability. Most operations that may mutate the bus object itself /// take place before [`enable`](UsbBus::enable) is called. After the bus is enabled, in practice /// most access won't mutate the object itself but only endpoint-specific registers and buffers, the /// access to which is mostly arbitrated by endpoint handles. pub trait UsbBus: Sync + Sized { /// Allocates an endpoint and specified endpoint parameters. This method is called by the device /// and class implementations to allocate endpoints, and can only be called before /// [`enable`](UsbBus::enable) is called. /// /// # Arguments /// /// * `ep_dir` - The endpoint direction. /// * `ep_addr` - A static endpoint address to allocate. If Some, the implementation should /// attempt to return an endpoint with the specified address. If None, the implementation /// should return the next available one. /// * `max_packet_size` - Maximum packet size in bytes. /// * `interval` - Polling interval parameter for interrupt endpoints. /// /// # Errors /// /// * [`EndpointOverflow`](crate::UsbError::EndpointOverflow) - Available total number of /// endpoints, endpoints of the specified type, or endpoind packet memory has been exhausted. /// This is generally caused when a user tries to add too many classes to a composite device. /// * [`InvalidEndpoint`](crate::UsbError::InvalidEndpoint) - A specific `ep_addr` was specified /// but the endpoint in question has already been allocated. fn alloc_ep( &mut self, ep_dir: UsbDirection, ep_addr: Option<EndpointAddress>, ep_type: EndpointType, max_packet_size: u16, interval: Generic<u32>, ) -> Result<EndpointAddress>; /// Enables and initializes the USB peripheral. Soon after enabling the device will be reset, so /// there is no need to perform a USB reset in this method. fn enable(&mut self); /// Called when the host resets the device. This will be soon called after /// [`poll`](crate::device::UsbDevice::poll) returns [`PollResult::Reset`]. This method should /// reset the state of all endpoints and peripheral flags back to a state suitable for /// enumeration, as well as ensure that all endpoints previously allocated with alloc_ep are /// initialized as specified. fn reset(&self); /// Sets the device USB address to `addr`. fn set_device_address(&self, addr: u8); /// Writes a single packet of data to the specified endpoint and returns number of bytes /// actually written. /// /// The only reason for a short write is if the caller passes a slice larger than the amount of /// memory allocated earlier, and this is generally an error in the class implementation. /// /// # Errors /// /// * [`InvalidEndpoint`](crate::UsbError::InvalidEndpoint) - The `ep_addr` does not point to a /// valid endpoint that was previously allocated with [`UsbBus::alloc_ep`]. /// * [`WouldBlock`](crate::UsbError::WouldBlock) - A previously written packet is still pending /// to be sent. /// * [`BufferOverflow`](crate::UsbError::BufferOverflow) - The packet is too long to fit in the /// transmission buffer. This is generally an error in the class implementation, because the /// class shouldn't provide more data than the `max_packet_size` it specified when allocating /// the endpoint. /// /// Implementations may also return other errors if applicable. fn write(&self, ep_addr: EndpointAddress, buf: &[u8]) -> Result<usize>; /// Reads a single packet of data from the specified endpoint and returns the actual length of /// the packet. /// /// This should also clear any NAK flags and prepare the endpoint to receive the next packet. /// /// # Errors /// /// * [`InvalidEndpoint`](crate::UsbError::InvalidEndpoint) - The `ep_addr` does not point to a /// valid endpoint that was previously allocated with [`UsbBus::alloc_ep`]. /// * [`WouldBlock`](crate::UsbError::WouldBlock) - There is no packet to be read. Note that /// this is different from a received zero-length packet, which is valid in USB. A zero-length /// packet will return `Ok(0)`. /// * [`BufferOverflow`](crate::UsbError::BufferOverflow) - The received packet is too long to /// fit in `buf`. This is generally an error in the class implementation, because the class /// should use a buffer that is large enough for the `max_packet_size` it specified when /// allocating the endpoint. /// /// Implementations may also return other errors if applicable. fn read(&self, ep_addr: EndpointAddress, buf: &mut [u8]) -> Result<usize>; /// Sets or clears the STALL condition for an endpoint. If the endpoint is an OUT endpoint, it /// should be prepared to receive data again. fn set_stalled(&self, ep_addr: EndpointAddress, stalled: bool); /// Gets whether the STALL condition is set for an endpoint. fn is_stalled(&self, ep_addr: EndpointAddress) -> bool; /// Causes the USB peripheral to enter USB suspend mode, lowering power consumption and /// preparing to detect a USB wakeup event. This will be called after /// [`poll`](crate::device::UsbDevice::poll) returns [`PollResult::Suspend`]. The device will /// continue be polled, and it shall return a value other than `Suspend` from `poll` when it no /// longer detects the suspend condition. fn suspend(&self); /// Resumes from suspend mode. This may only be called after the peripheral has been previously /// suspended. fn resume(&self); /// Gets information about events and incoming data. Usually called in a loop or from an /// interrupt handler. See the [`PollResult`] struct for more information. fn poll(&self) -> PollResult; /// Simulates a disconnect from the USB bus, causing the host to reset and re-enumerate the /// device. /// /// The default implementation just returns `Unsupported`. /// /// # Errors /// /// * [`Unsupported`](crate::UsbError::Unsupported) - This UsbBus implementation doesn't support /// simulating a disconnect or it has not been enabled at creation time. fn force_reset(&self) -> Result<()> { Err(UsbError::Unsupported) } /// Indicates that `set_device_address` must be called before accepting the corresponding /// control transfer, not after. /// /// The default value for this constant is `false`, which corresponds to the USB 2.0 spec, 9.4.6 const QUIRK_SET_ADDRESS_BEFORE_STATUS: bool = false; } struct AllocatorState { next_interface_number: u8, next_string_index: u8, } /// Helper type used for UsbBus resource allocation and initialization. pub struct UsbBusAllocator<B: UsbBus> { bus: RefCell<B>, bus_ptr: AtomicPtr<B>, state: RefCell<AllocatorState>, } impl<B: UsbBus> UsbBusAllocator<B> { /// Creates a new [`UsbBusAllocator`] that wraps the provided [`UsbBus`]. Usually only called by /// USB driver implementations. pub fn new(bus: B) -> UsbBusAllocator<B> { UsbBusAllocator { bus: RefCell::new(bus), bus_ptr: AtomicPtr::new(ptr::null_mut()), state: RefCell::new(AllocatorState { next_interface_number: 0, next_string_index: 4, }), } } pub(crate) fn freeze(&self) -> &B { // Prevent further allocation by borrowing the allocation state permanently. mem::forget(self.state.borrow_mut()); // Enable the USB bus self.bus.borrow_mut().enable(); // An AtomicPtr is used for the reference from Endpoints to UsbBus, in order to ensure that // Endpoints stay Sync (if the Endpoints had a reference to a RefCell, they would not be // Sync) Set the pointer used by the Endpoints to access the UsbBus to point to the UsbBus // in the RefCell. let mut bus_ref = self.bus.borrow_mut(); let bus_ptr_v = &mut *bus_ref as *mut B; self.bus_ptr.store(bus_ptr_v, Ordering::SeqCst); // And then leave the RefCell borrowed permanently so that it cannot be borrowed mutably // anymore. mem::forget(bus_ref); // Return the reference to the UsbBus, for use by UsbDevice. unsafe { &*bus_ptr_v } } /// Allocates a new interface number. pub fn interface(&self) -> InterfaceNumber { let mut state = self.state.borrow_mut(); let number = state.next_interface_number; state.next_interface_number += 1; InterfaceNumber(number) } /// Allocates a new string index. pub fn string(&self) -> StringIndex { let mut state = self.state.borrow_mut(); let index = state.next_string_index; state.next_string_index += 1; StringIndex(index) } /// Allocates an endpoint with the specified direction and address. /// /// This directly delegates to [`UsbBus::alloc_ep`], so see that method for details. In most /// cases classes should call the endpoint type specific methods instead. pub fn alloc<D: EndpointDirection>( &self, ep_addr: Option<EndpointAddress>, ep_type: EndpointType, max_packet_size: u16, interval: Generic<u32>, ) -> Result<Endpoint<'_, B, D>> { self.bus .borrow_mut() .alloc_ep(D::DIRECTION, ep_addr, ep_type, max_packet_size, interval) .map(|a| Endpoint::new(&self.bus_ptr, a, ep_type, max_packet_size, interval)) } /// Allocates a control endpoint. /// /// This crate implements the control state machine only for endpoint 0. If classes want to /// support control requests in other endpoints, the state machine must be implemented manually. /// This should rarely be needed by classes. /// /// # Arguments /// /// * `max_packet_size` - Maximum packet size in bytes. Must be one of 8, 16, 32 or 64. /// /// # Panics /// /// Panics if endpoint allocation fails, because running out of endpoints or memory is not /// feasibly recoverable. #[inline] pub fn control<D: EndpointDirection>(&self, max_packet_size: u16) -> Endpoint<'_, B, D> { self.alloc( None, EndpointType::Control, max_packet_size, 0u32.milliseconds().into(), ) .expect("alloc_ep failed") } /// Allocates a bulk endpoint. /// /// # Arguments /// /// * `max_packet_size` - Maximum packet size in bytes. Must be one of 8, 16, 32 or 64. /// /// # Panics /// /// Panics if endpoint allocation fails, because running out of endpoints or memory is not /// feasibly recoverable. #[inline] pub fn bulk<D: EndpointDirection>(&self, max_packet_size: u16) -> Endpoint<'_, B, D> { self.alloc( None, EndpointType::Bulk, max_packet_size, 0u32.milliseconds().into(), ) .expect("alloc_ep failed") } /// Allocates an interrupt endpoint. /// /// * `max_packet_size` - Maximum packet size in bytes. Cannot exceed 64 bytes. /// /// # Panics /// /// Panics if endpoint allocation fails, because running out of endpoints or memory is not /// feasibly recoverable. #[inline] pub fn interrupt<D: EndpointDirection>( &self, max_packet_size: u16, interval: Generic<u32>, ) -> Endpoint<'_, B, D> { self.alloc(None, EndpointType::Interrupt, max_packet_size, interval) .expect("alloc_ep failed") } } /// A handle for a USB interface that contains its number. #[derive(Copy, Clone, Eq, PartialEq)] pub struct InterfaceNumber(u8); impl From<InterfaceNumber> for u8 { fn from(n: InterfaceNumber) -> u8 { n.0 } } /// A handle for a USB string descriptor that contains its index. #[derive(Copy, Clone, Eq, PartialEq)] pub struct StringIndex(u8); impl StringIndex { pub(crate) fn new(index: u8) -> StringIndex { StringIndex(index) } } impl From<StringIndex> for u8 { fn from(i: StringIndex) -> u8 { i.0 } } /// Event and incoming packet information returned by [`UsbBus::poll`]. pub enum PollResult { /// No events or packets to report. None, /// The USB reset condition has been detected. Reset, /// USB packets have been received or sent. Each data field is a bit-field where the least /// significant bit represents endpoint 0 etc., and a set bit signifies the event has occurred /// for the corresponding endpoint. Data { /// An OUT packet has been received. This event should continue to be reported until the /// packet is read. ep_out: u16, /// An IN packet has finished transmitting. This event should only be reported once for each /// completed transfer. ep_in_complete: u16, /// A SETUP packet has been received. This event should continue to be reported until the /// packet is read. The corresponding bit in `ep_out` may also be set but is ignored. ep_setup: u16, }, /// A USB suspend request has been detected or, in the case of self-powered devices, the device /// has been disconnected from the USB bus. Suspend, /// A USB resume request has been detected after being suspended or, in the case of self-powered /// devices, the device has been connected to the USB bus. Resume, }
40.393768
100
0.656778
1de95ead91137fb7a4402d33ffb48556dab7d2ea
7,045
use anyhow::{anyhow, Result}; use phf::phf_map; use crate::lox::Lox; use crate::token::{Token, TokenType}; static KEYWORDS: phf::Map<&'static str, TokenType> = phf_map! { "and" => TokenType::And, "class" => TokenType::Class, "else" => TokenType::Else, "false" => TokenType::False, "fun" => TokenType::Fun, "for" => TokenType::For, "if" => TokenType::If, "nil" => TokenType::Nil, "or" => TokenType::Or, "print" => TokenType::Print, "return" => TokenType::Return, "super" => TokenType::Super, "this" => TokenType::This, "true" => TokenType::True, "var" => TokenType::Var, "while" => TokenType::While, }; pub struct Scanner { source: Vec<char>, tokens: Vec<Token>, // TODO: Move to struct? start: usize, current: usize, line: i32, } impl Scanner { pub fn new(source: &str) -> Self { Self { source: source.chars().collect(), tokens: vec![], start: 0, current: 0, line: 1, } } fn is_at_end(&self) -> bool { self.current >= self.source.len() } fn advance(&mut self) -> char { let c = self.source.get(self.current).unwrap_or_else(|| { // clippy does not like expect() here for some reason panic!("advanced into exhausted source at index {}", self.current) }); self.current += 1; *c } fn current_lexeme(&self) -> String { self.source .get(self.start as usize..self.current as usize) .unwrap() .iter() .collect() } fn add_token(&mut self, token: TokenType) { self.tokens.push(Token { token_type: token, lexeme: self.current_lexeme(), line: self.line, }); } fn peek(&self, offset: usize) -> char { let pos = self.current + offset; if pos >= self.source.len() { '\0' } else { self.source[pos] } } fn match_(&mut self, expected: char) -> bool { if self.is_at_end() { return false; }; if self.peek(0) != expected { return false; }; self.current += 1; true } fn parse_string(&mut self) -> Result<()> { while self.peek(0) != '"' && !self.is_at_end() { if self.peek(0) == '\n' { self.line += 1; } self.advance(); } if self.is_at_end() { return Err(anyhow!("Unterminated string.")); } self.advance(); let current_lexeme = self.current_lexeme(); self.add_token(TokenType::String { literal: current_lexeme .get(1..current_lexeme.len() - 1) .unwrap() .to_owned(), }); Ok(()) } fn is_digit(c: char) -> bool { c.is_digit(10) } fn parse_number(&mut self) { while Self::is_digit(self.peek(0)) { self.advance(); } if self.peek(0) == '.' && Self::is_digit(self.peek(1)) { self.advance(); } while Self::is_digit(self.peek(0)) { self.advance(); } self.add_token(TokenType::Number { literal: self .current_lexeme() .parse() .expect("could not parse float"), }) } fn is_alpha(c: char) -> bool { c.is_ascii_alphabetic() || c == '_' } fn is_alphanumeric(c: char) -> bool { c.is_ascii_alphanumeric() || c == '_' } fn parse_identifier(&mut self) { while Self::is_alphanumeric(self.peek(0)) { self.advance(); } self.add_token({ if let Some(token) = KEYWORDS.get(&self.current_lexeme()[..]) { (*token).clone() } else { TokenType::Identifier } }) } fn scan_token(&mut self) -> Result<()> { let c = self.advance(); let maybe_token = match c { '(' => Some(TokenType::LeftParen), ')' => Some(TokenType::RightParen), '{' => Some(TokenType::LeftBrace), '}' => Some(TokenType::RightBrace), ',' => Some(TokenType::Comma), '.' => Some(TokenType::Dot), '-' => Some(TokenType::Minus), '+' => Some(TokenType::Plus), ';' => Some(TokenType::Semicolon), '*' => Some(TokenType::Star), '!' => { if self.match_('=') { Some(TokenType::BangEqual) } else { Some(TokenType::Bang) } } '=' => { if self.match_('=') { Some(TokenType::EqualEqual) } else { Some(TokenType::Equal) } } '<' => { if self.match_('=') { Some(TokenType::LessEqual) } else { Some(TokenType::Less) } } '>' => { if self.match_('=') { Some(TokenType::GreaterEqual) } else { Some(TokenType::Greater) } } '/' => { if self.match_('/') { while self.peek(0) != '\n' && !self.is_at_end() { self.advance(); } None } else { Some(TokenType::Slash) } } ' ' | '\r' | '\t' => None, '"' => { self.parse_string()?; None } '\n' => { self.line += 1; None } _ => { if Self::is_digit(c) { self.parse_number(); None } else if Self::is_alpha(c) { self.parse_identifier(); None } else { Some(TokenType::Unknown) } } }; if let Some(token) = maybe_token { if token == TokenType::Unknown { Err(anyhow!("Unexpected character: {}", c)) } else { self.add_token(token); Ok(()) } } else { Ok(()) } } pub fn scan_tokens<'a>(&mut self, lox: &'a mut Lox) -> &Vec<Token> { while !self.is_at_end() { self.start = self.current; if let Err(err) = self.scan_token() { lox.error(self.line, &err.to_string()); } } self.tokens.push(Token { token_type: TokenType::Eof, lexeme: "".to_owned(), line: self.line, }); &self.tokens } }
24.98227
78
0.417317
ed424b62fbf2a918ba8d131a148c4dd4aff542f7
46
pub mod client; pub mod oauth2; pub mod util;
11.5
15
0.73913
d72ae3ad7606486a71e4b8b99df9583ca373a0da
2,078
//! A collection of node-specific RPC methods. //! Substrate provides the `sc-rpc` crate, which defines the core RPC layer //! used by Substrate nodes. This file extends those RPC definitions with //! capabilities that are specific to this project's runtime configuration. #![warn(missing_docs)] use std::sync::Arc; use filecoin_bridge_runtime::{opaque::Block, AccountId, Balance, Index}; use sp_api::ProvideRuntimeApi; use sp_blockchain::{Error as BlockChainError, HeaderMetadata, HeaderBackend}; use sp_block_builder::BlockBuilder; pub use sc_rpc_api::DenyUnsafe; use sp_transaction_pool::TransactionPool; /// Full client dependencies. pub struct FullDeps<C, P> { /// The client instance to use. pub client: Arc<C>, /// Transaction pool instance. pub pool: Arc<P>, /// Whether to deny unsafe calls pub deny_unsafe: DenyUnsafe, } /// Instantiate all full RPC extensions. pub fn create_full<C, P>( deps: FullDeps<C, P>, ) -> jsonrpc_core::IoHandler<sc_rpc::Metadata> where C: ProvideRuntimeApi<Block>, C: HeaderBackend<Block> + HeaderMetadata<Block, Error=BlockChainError> + 'static, C: Send + Sync + 'static, C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>, C::Api: BlockBuilder<Block>, P: TransactionPool + 'static, { use substrate_frame_rpc_system::{FullSystem, SystemApi}; use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi}; let mut io = jsonrpc_core::IoHandler::default(); let FullDeps { client, pool, deny_unsafe, } = deps; io.extend_with( SystemApi::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe)) ); io.extend_with( TransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone())) ); // Extend this RPC with a custom API by using the following syntax. // `YourRpcStruct` should have a reference to a client, which is needed // to call into the runtime. // `io.extend_with(YourRpcTrait::to_delegate(YourRpcStruct::new(ReferenceToClient, ...)));` io }
31.969231
92
0.753609
169fc54eec48f6c9b9f738a0d81a14f24bddc6a7
3,605
//! All objects related to audio defined by Spotify API use serde::{Deserialize, Serialize}; use std::time::Duration; use crate::{ custom_serde::{duration_ms, modality}, Modality, TrackId, }; /// Audio Feature Object #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct AudioFeatures { pub acousticness: f32, pub analysis_url: String, pub danceability: f32, #[serde(with = "duration_ms", rename = "duration_ms")] pub duration: Duration, pub energy: f32, pub id: TrackId, pub instrumentalness: f32, pub key: i32, pub liveness: f32, pub loudness: f32, #[serde(with = "modality")] pub mode: Modality, pub speechiness: f32, pub tempo: f32, pub time_signature: i32, pub track_href: String, pub valence: f32, } /// Intermediate audio feature object wrapped by `Vec` #[derive(Deserialize)] pub struct AudioFeaturesPayload { pub audio_features: Vec<AudioFeatures>, } /// Audio analysis object #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct AudioAnalysis { pub bars: Vec<TimeInterval>, pub beats: Vec<TimeInterval>, pub meta: AudioAnalysisMeta, pub sections: Vec<AudioAnalysisSection>, pub segments: Vec<AudioAnalysisSegment>, pub tatums: Vec<TimeInterval>, pub track: AudioAnalysisTrack, } /// Time interval object #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)] pub struct TimeInterval { pub start: f32, pub duration: f32, pub confidence: f32, } /// Audio analysis section object #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct AudioAnalysisSection { #[serde(flatten)] pub time_interval: TimeInterval, pub loudness: f32, pub tempo: f32, pub tempo_confidence: f32, pub key: i32, pub key_confidence: f32, #[serde(with = "modality")] pub mode: Modality, pub mode_confidence: f32, pub time_signature: i32, pub time_signature_confidence: f32, } /// Audio analysis meta object #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)] pub struct AudioAnalysisMeta { pub analyzer_version: String, pub platform: String, pub detailed_status: String, pub status_code: i32, pub timestamp: u64, pub analysis_time: f32, pub input_process: String, } /// Audio analysis segment object #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)] pub struct AudioAnalysisSegment { #[serde(flatten)] pub time_interval: TimeInterval, pub loudness_start: f32, pub loudness_max_time: f32, pub loudness_max: f32, pub loudness_end: Option<f32>, pub pitches: Vec<f32>, pub timbre: Vec<f32>, } /// Audio analysis track object #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct AudioAnalysisTrack { pub num_samples: u32, pub duration: f32, pub sample_md5: String, pub offset_seconds: u32, pub window_seconds: u32, pub analysis_sample_rate: i32, pub analysis_channels: u32, pub end_of_fade_in: f32, pub start_of_fade_out: f32, pub loudness: f32, pub tempo: f32, pub tempo_confidence: f32, pub time_signature: i32, pub time_signature_confidence: f32, pub key: u32, pub key_confidence: f32, #[serde(with = "modality")] pub mode: Modality, pub mode_confidence: f32, pub codestring: String, pub code_version: f32, pub echoprintstring: String, pub echoprint_version: f32, pub synchstring: String, pub synch_version: f32, pub rhythmstring: String, pub rhythm_version: f32, }
26.902985
67
0.695423
6497de6b271e847532c6992b186d5c98851b5d2b
14,420
// Copyright 2019 The Grin Developers // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Common functions for wallet integration tests extern crate grin_wallet; use grin_wallet_config as config; use grin_wallet_impls::test_framework::LocalWalletClient; use grin_wallet_util::grin_util as util; use clap::{App, ArgMatches}; use std::path::PathBuf; use std::sync::Arc; use std::{env, fs}; use util::{Mutex, ZeroingString}; use grin_wallet_api::{EncryptedRequest, EncryptedResponse}; use grin_wallet_config::{GlobalWalletConfig, WalletConfig, GRIN_WALLET_DIR}; use grin_wallet_impls::{DefaultLCProvider, DefaultWalletImpl}; use grin_wallet_libwallet::{NodeClient, WalletInfo, WalletInst}; use grin_wallet_util::grin_core::global::{self, ChainTypes}; use grin_wallet_util::grin_keychain::ExtKeychain; use grin_wallet_util::grin_util::{from_hex, static_secp_instance}; use util::secp::key::{PublicKey, SecretKey}; use grin_wallet::cmd::wallet_args; use grin_wallet_util::grin_api as api; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::thread; use std::time::Duration; use url::Url; // Set up 2 wallets and launch the test proxy behind them #[macro_export] macro_rules! setup_proxy { ($test_dir: expr, $chain: ident, $wallet1: ident, $client1: ident, $mask1: ident, $wallet2: ident, $client2: ident, $mask2: ident) => { // Create a new proxy to simulate server and wallet responses let mut wallet_proxy: WalletProxy< DefaultLCProvider<LocalWalletClient, ExtKeychain>, LocalWalletClient, ExtKeychain, > = WalletProxy::new($test_dir); let $chain = wallet_proxy.chain.clone(); // load app yaml. If it don't exist, just say so and exit let yml = load_yaml!("../src/bin/grin-wallet.yml"); let app = App::from_yaml(yml); // wallet init let arg_vec = vec!["grin-wallet", "-p", "password", "init", "-h"]; // should create new wallet file let $client1 = LocalWalletClient::new("wallet1", wallet_proxy.tx.clone()); let target = std::path::PathBuf::from(format!("{}/wallet1/grin-wallet.toml", $test_dir)); println!("{:?}", target); if !target.exists() { execute_command(&app, $test_dir, "wallet1", &$client1, arg_vec.clone())?; } // add wallet to proxy let config1 = initial_setup_wallet($test_dir, "wallet1"); let wallet_config1 = config1.clone().members.unwrap().wallet; //config1.owner_api_listen_port = Some(13420); let ($wallet1, mask1_i) = instantiate_wallet( wallet_config1.clone(), $client1.clone(), "password", "default", )?; let $mask1 = (&mask1_i).as_ref(); wallet_proxy.add_wallet( "wallet1", $client1.get_send_instance(), $wallet1.clone(), mask1_i.clone(), ); // Create wallet 2, which will run a listener let $client2 = LocalWalletClient::new("wallet2", wallet_proxy.tx.clone()); let target = std::path::PathBuf::from(format!("{}/wallet2/grin-wallet.toml", $test_dir)); if !target.exists() { execute_command(&app, $test_dir, "wallet2", &$client2, arg_vec.clone())?; } let config2 = initial_setup_wallet($test_dir, "wallet2"); let wallet_config2 = config2.clone().members.unwrap().wallet; //config2.api_listen_port = 23415; let ($wallet2, mask2_i) = instantiate_wallet( wallet_config2.clone(), $client2.clone(), "password", "default", )?; let $mask2 = (&mask2_i).as_ref(); wallet_proxy.add_wallet( "wallet2", $client2.get_send_instance(), $wallet2.clone(), mask2_i.clone(), ); // Set the wallet proxy listener running thread::spawn(move || { if let Err(e) = wallet_proxy.run() { error!("Wallet Proxy error: {}", e); } }); }; } #[allow(dead_code)] pub fn clean_output_dir(test_dir: &str) { let _ = fs::remove_dir_all(test_dir); } #[allow(dead_code)] pub fn setup(test_dir: &str) { util::init_test_logger(); clean_output_dir(test_dir); global::set_mining_mode(ChainTypes::AutomatedTesting); } /// Create a wallet config file in the given current directory pub fn config_command_wallet( dir_name: &str, wallet_name: &str, ) -> Result<(), grin_wallet_controller::Error> { let mut current_dir; let mut default_config = GlobalWalletConfig::default(); current_dir = env::current_dir().unwrap_or_else(|e| { panic!("Error creating config file: {}", e); }); current_dir.push(dir_name); current_dir.push(wallet_name); let _ = fs::create_dir_all(current_dir.clone()); let mut config_file_name = current_dir.clone(); config_file_name.push("grin-wallet.toml"); if config_file_name.exists() { return Err(grin_wallet_controller::ErrorKind::ArgumentError( "grin-wallet.toml already exists in the target directory. Please remove it first" .to_owned(), ))?; } default_config.update_paths(&current_dir); default_config .write_to_file(config_file_name.to_str().unwrap()) .unwrap_or_else(|e| { panic!("Error creating config file: {}", e); }); println!( "File {} configured and created", config_file_name.to_str().unwrap(), ); Ok(()) } /// Handles setup and detection of paths for wallet #[allow(dead_code)] pub fn initial_setup_wallet(dir_name: &str, wallet_name: &str) -> GlobalWalletConfig { let mut current_dir; current_dir = env::current_dir().unwrap_or_else(|e| { panic!("Error creating config file: {}", e); }); current_dir.push(dir_name); current_dir.push(wallet_name); let _ = fs::create_dir_all(current_dir.clone()); let mut config_file_name = current_dir.clone(); config_file_name.push("grin-wallet.toml"); GlobalWalletConfig::new(config_file_name.to_str().unwrap()).unwrap() } fn get_wallet_subcommand<'a>( wallet_dir: &str, wallet_name: &str, args: ArgMatches<'a>, ) -> ArgMatches<'a> { match args.subcommand() { ("init", Some(init_args)) => { // wallet init command should spit out its config file then continue // (if desired) if init_args.is_present("here") { let _ = config_command_wallet(wallet_dir, wallet_name); } init_args.to_owned() } _ => ArgMatches::new(), } } // // Helper to create an instance of the LMDB wallet #[allow(dead_code)] pub fn instantiate_wallet( mut wallet_config: WalletConfig, node_client: LocalWalletClient, passphrase: &str, account: &str, ) -> Result< ( Arc< Mutex< Box< dyn WalletInst< 'static, DefaultLCProvider<'static, LocalWalletClient, ExtKeychain>, LocalWalletClient, ExtKeychain, >, >, >, >, Option<SecretKey>, ), grin_wallet_controller::Error, > { wallet_config.chain_type = None; let mut wallet = Box::new(DefaultWalletImpl::<LocalWalletClient>::new(node_client).unwrap()) as Box< dyn WalletInst< DefaultLCProvider<'static, LocalWalletClient, ExtKeychain>, LocalWalletClient, ExtKeychain, >, >; let lc = wallet.lc_provider().unwrap(); // legacy hack to avoid the need for changes in existing grin-wallet.toml files // remove `wallet_data` from end of path as // new lifecycle provider assumes grin_wallet.toml is in root of data directory let mut top_level_wallet_dir = PathBuf::from(wallet_config.clone().data_file_dir); if top_level_wallet_dir.ends_with(GRIN_WALLET_DIR) { top_level_wallet_dir.pop(); wallet_config.data_file_dir = top_level_wallet_dir.to_str().unwrap().into(); } let _ = lc.set_top_level_directory(&wallet_config.data_file_dir); let keychain_mask = lc .open_wallet(None, ZeroingString::from(passphrase), true, false) .unwrap(); let wallet_inst = lc.wallet_inst()?; wallet_inst.set_parent_key_id_by_name(account)?; Ok((Arc::new(Mutex::new(wallet)), keychain_mask)) } #[allow(dead_code)] pub fn execute_command( app: &App, test_dir: &str, wallet_name: &str, client: &LocalWalletClient, arg_vec: Vec<&str>, ) -> Result<String, grin_wallet_controller::Error> { let args = app.clone().get_matches_from(arg_vec); let _ = get_wallet_subcommand(test_dir, wallet_name, args.clone()); let config = initial_setup_wallet(test_dir, wallet_name); let mut wallet_config = config.clone().members.unwrap().wallet; let tor_config = config.clone().members.unwrap().tor; //unset chain type so it doesn't get reset wallet_config.chain_type = None; wallet_args::wallet_command( &args, wallet_config.clone(), tor_config, client.clone(), true, |_| {}, ) } // as above, but without necessarily setting up the wallet #[allow(dead_code)] pub fn execute_command_no_setup<C, F>( app: &App, test_dir: &str, wallet_name: &str, client: &C, arg_vec: Vec<&str>, f: F, ) -> Result<String, grin_wallet_controller::Error> where C: NodeClient + 'static + Clone, F: FnOnce( Arc< Mutex< Box< dyn WalletInst< 'static, DefaultLCProvider<'static, C, ExtKeychain>, C, ExtKeychain, >, >, >, >, ), { let args = app.clone().get_matches_from(arg_vec); let _ = get_wallet_subcommand(test_dir, wallet_name, args.clone()); let config = config::initial_setup_wallet(&ChainTypes::AutomatedTesting, None).unwrap(); let mut wallet_config = config.clone().members.unwrap().wallet; wallet_config.chain_type = None; wallet_config.api_secret_path = None; wallet_config.node_api_secret_path = None; let tor_config = config.members.unwrap().tor.clone(); wallet_args::wallet_command(&args, wallet_config, tor_config, client.clone(), true, f) } pub fn post<IN>(url: &Url, api_secret: Option<String>, input: &IN) -> Result<String, api::Error> where IN: Serialize, { // TODO: change create_post_request to accept a url instead of a &str let req = api::client::create_post_request(url.as_str(), api_secret, input)?; let res = api::client::send_request(req)?; Ok(res) } #[allow(dead_code)] pub fn send_request<OUT>( id: u64, dest: &str, req: &str, ) -> Result<Result<OUT, WalletAPIReturnError>, api::Error> where OUT: DeserializeOwned, { let url = Url::parse(dest).unwrap(); let req_val: Value = serde_json::from_str(req).unwrap(); let res = post(&url, None, &req_val).map_err(|e| { let err_string = format!("{}", e); println!("{}", err_string); thread::sleep(Duration::from_millis(200)); e })?; let res_val: Value = serde_json::from_str(&res).unwrap(); // encryption error, just return the string if res_val["error"] != json!(null) { return Ok(Err(WalletAPIReturnError { message: res_val["error"]["message"].as_str().unwrap().to_owned(), code: res_val["error"]["code"].as_i64().unwrap() as i32, })); } let res = serde_json::from_str(&res).unwrap(); let res = easy_jsonrpc::Response::from_json_response(res).unwrap(); let res = res.outputs.get(&id).unwrap().clone().unwrap(); if res["Err"] != json!(null) { Ok(Err(WalletAPIReturnError { message: res["Err"].as_str().unwrap().to_owned(), code: res["error"]["code"].as_i64().unwrap() as i32, })) } else { // deserialize result into expected type let value: OUT = serde_json::from_value(res["Ok"].clone()).unwrap(); Ok(Ok(value)) } } #[allow(dead_code)] pub fn send_request_enc<OUT>( sec_req_id: u64, internal_request_id: u32, dest: &str, req: &str, shared_key: &SecretKey, ) -> Result<Result<OUT, WalletAPIReturnError>, api::Error> where OUT: DeserializeOwned, { let url = Url::parse(dest).unwrap(); let req_val: Value = serde_json::from_str(req).unwrap(); let req = EncryptedRequest::from_json(sec_req_id, &req_val, &shared_key).unwrap(); let res = post(&url, None, &req).map_err(|e| { let err_string = format!("{}", e); println!("{}", err_string); thread::sleep(Duration::from_millis(200)); e })?; let res_val: Value = serde_json::from_str(&res).unwrap(); //println!("RES_VAL: {}", res_val); // encryption error, just return the string if res_val["error"] != json!(null) { return Ok(Err(WalletAPIReturnError { message: res_val["error"]["message"].as_str().unwrap().to_owned(), code: res_val["error"]["code"].as_i64().unwrap() as i32, })); } let enc_resp: EncryptedResponse = serde_json::from_str(&res).unwrap(); let res = enc_resp.decrypt(shared_key).unwrap(); if res["error"] != json!(null) { return Ok(Err(WalletAPIReturnError { message: res["error"]["message"].as_str().unwrap().to_owned(), code: res["error"]["code"].as_i64().unwrap() as i32, })); } let res = easy_jsonrpc::Response::from_json_response(res).unwrap(); let res = res .outputs .get(&(internal_request_id as u64)) .unwrap() .clone() .unwrap(); //println!("RES: {}", res); if res["Err"] != json!(null) { Ok(Err(WalletAPIReturnError { message: res["Err"].as_str().unwrap().to_owned(), code: res_val["error"]["code"].as_i64().unwrap() as i32, })) } else { // deserialize result into expected type let raw_value = res["Ok"].clone(); let raw_value_str = serde_json::to_string_pretty(&raw_value).unwrap(); //println!("Raw value: {}", raw_value_str); let ok_val = serde_json::from_str(&raw_value_str); match ok_val { Ok(v) => { let value: OUT = v; Ok(Ok(value)) } Err(_) => { //println!("Error deserializing: {:?}", e); let value: OUT = serde_json::from_value(json!("Null")).unwrap(); Ok(Ok(value)) } } } } #[allow(dead_code)] pub fn derive_ecdh_key(sec_key_str: &str, other_pubkey: &PublicKey) -> SecretKey { let sec_key_bytes = from_hex(sec_key_str.to_owned()).unwrap(); let sec_key = { let secp_inst = static_secp_instance(); let secp = secp_inst.lock(); SecretKey::from_slice(&secp, &sec_key_bytes).unwrap() }; let secp_inst = static_secp_instance(); let secp = secp_inst.lock(); let mut shared_pubkey = other_pubkey.clone(); shared_pubkey.mul_assign(&secp, &sec_key).unwrap(); let x_coord = shared_pubkey.serialize_vec(&secp, true); SecretKey::from_slice(&secp, &x_coord[1..]).unwrap() } // Types to make working with json responses easier #[derive(Clone, Debug, Serialize, Deserialize)] pub struct WalletAPIReturnError { pub message: String, pub code: i32, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct RetrieveSummaryInfoResp(pub bool, pub WalletInfo);
30.486258
136
0.698128
e21093c22cb0691e350da22e58fda413e65b19c1
1,203
use std::pin::Pin; use futures::{ task::{Context, Poll}, Future, }; use tokio::sync::{ mpsc, oneshot::{self, Receiver, Sender}, }; use crate::adaptors::throttle::FreezeUntil; pub(super) fn channel() -> (RequestLock, RequestWaiter) { let (tx, rx) = oneshot::channel(); let tx = RequestLock(tx); let rx = RequestWaiter(rx); (tx, rx) } #[must_use] pub(super) struct RequestLock(Sender<(bool, mpsc::Sender<FreezeUntil>)>); #[must_use] #[pin_project::pin_project] pub(super) struct RequestWaiter(#[pin] Receiver<(bool, mpsc::Sender<FreezeUntil>)>); impl RequestLock { pub(super) fn unlock(self, retry: bool, freeze: mpsc::Sender<FreezeUntil>) -> Result<(), ()> { self.0.send((retry, freeze)).map_err(drop) } } impl Future for RequestWaiter { type Output = (bool, mpsc::Sender<FreezeUntil>); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); match this.0.poll(cx) { Poll::Ready(Ok(ret)) => Poll::Ready(ret), Poll::Ready(Err(_)) => panic!("`RequestLock` is dropped by the throttle worker"), Poll::Pending => Poll::Pending, } } }
26.152174
98
0.610973
3362b34638e91f069e0817a0b8736c1cd2943770
6,601
#![allow(dead_code)] use std::{env, path::PathBuf}; struct Environment { host: String, emit_debug_info: bool, target_compiler: Option<String>, target_os: String, target_env: Option<String>, mode: String, static_crt: bool, } struct Context { root: PathBuf, builder: cc::Build, env: Environment, includes: Vec<PathBuf>, } #[cfg(not(feature = "use-cmake"))] include!("cc.rs"); #[cfg(feature = "use-cmake")] include!("cmake.rs"); fn main() { // Use the optimization level to determine the build profile to pass, we // don't use cfg!(debug_assertions) here because I'm not sure what happens // with that when build dependencies are configured to be debug and the // actual target is meant to be release, so this seems safer let build_mode = match env::var("OPT_LEVEL") .ok() .and_then(|s| s.parse::<i32>().ok()) .unwrap_or(1) { 0 => "debug", _ => "profile", }; let target = env::var("TARGET").expect("TARGET not specified"); let host = env::var("HOST").expect("HOST not specified"); // Acquire the user-specified c++ compiler if one has been set, in the same // order and manner that cc-rs will do it let compiler = { env::var(&format!("CXX_{}", target)) .or_else(|_| { let target_under = target.replace("-", "_"); env::var(&format!("CXX_{}", target_under)) }) .or_else(|_| env::var("TARGET_CXX")) .or_else(|_| env::var("CXX")) .ok() }; { let target_os = env::var("CARGO_CFG_TARGET_OS").expect("target os not specified"); let target_env = env::var("CARGO_CFG_TARGET_ENV").ok(); let static_crt = env::var("CARGO_CFG_TARGET_FEATURE") .unwrap_or_default() .contains("crt-static"); let environment = Environment { emit_debug_info: env::var("DEBUG") .ok() .and_then(|s| s.parse::<bool>().ok()) .unwrap_or(false), target_compiler: compiler.clone(), target_os, target_env, mode: build_mode.to_owned(), host: host.clone(), static_crt, }; #[cfg(feature = "use-cmake")] cmake_compile(environment); #[cfg(not(feature = "use-cmake"))] cc_compile(environment); } let mut cc_builder = cc::Build::new(); let physx_cc = cc_builder .cpp(true) .opt_level(3) .debug(false) .use_plt(false) .warnings(false) .extra_warnings(false) .define("NDEBUG", None) .define("PX_PHYSX_STATIC_LIB", None) .include("PhysX/physx/include") .include("PhysX/pxshared/include") .include("PhysX/physx/source/foundation/include"); if compiler.is_none() && host.contains("-linux-") { physx_cc.compiler("clang++"); } physx_cc.flag(if physx_cc.get_compiler().is_like_msvc() { "/std:c++14" } else { "-std=c++14" }); use std::ffi::OsString; let output_dir_path = PathBuf::from(env::var("OUT_DIR").expect("output directory not specified")); let include_path = if env::var("CARGO_FEATURE_STRUCTGEN").is_ok() { let mut structgen_path = output_dir_path.join("structgen"); let structgen_compiler = physx_cc.get_compiler(); let mut cmd = structgen_compiler.to_command(); if structgen_compiler.is_like_msvc() { let mut s = OsString::from("/Fe"); s.push(&structgen_path); cmd.arg(s); let mut s = OsString::from("/Fo"); s.push(&structgen_path); s.push(".obj"); cmd.arg(s); } else { cmd.arg("-o").arg(&structgen_path); } cmd.arg("src/structgen/structgen.cpp"); cmd.status().expect("c++ compiler failed to execute"); // The above status check has been shown to fail, ie, the compiler // fails to output a binary, but reports success anyway if host.contains("-windows-") { structgen_path.set_extension("exe"); } std::fs::metadata(&structgen_path) .expect("failed to compile structgen even though compiler reported no failures"); let mut structgen = if target.starts_with("aarch64-") { let mut structgen = std::process::Command::new("qemu-aarch64"); structgen.arg(&structgen_path); structgen } else { std::process::Command::new(&structgen_path) }; structgen.current_dir(&output_dir_path); structgen.status().expect("structgen failed to execute"); output_dir_path } else { let mut include = PathBuf::from("src/generated"); match target.as_str() { "x86_64-apple-darwin" | "x86_64-pc-windows-msvc" | "aarch64-linux-android" => { include.push(target); } nix if nix.starts_with("x86_64-unknown-linux") => { include.push("x86_64-unknown-linux"); } _ => panic!("unknown TARGET triple '{}'", target), } include }; // gcc gives this: // warning: src/physx_generated.hpp:6777:7: warning: // ‘void* memcpy(void*, const void*, size_t)’ reading 2 bytes from a region of size 1 [-Wstringop-overflow=] // which from cursory glance seems to be an erroneous warning as the type it is talking // about is inside a struct containing a single u16, so.... if physx_cc.get_compiler().is_like_gnu() { physx_cc.flag("-Wno-stringop-overflow"); } physx_cc .include(include_path) .file("src/physx_api.cpp") .compile("physx_api"); println!("cargo:rerun-if-changed=src/structgen/structgen.cpp"); println!("cargo:rerun-if-changed=src/structgen/structgen.hpp"); println!("cargo:rerun-if-changed=src/lib.rs"); println!("cargo:rerun-if-changed=src/physx_generated.hpp"); println!("cargo:rerun-if-changed=src/physx_generated.rs"); println!("cargo:rerun-if-changed=src/physx_api.cpp"); // TODO: use the cloned git revision number instead println!("cargo:rerun-if-changed=PhysX/physx/include/PxPhysicsVersion.h"); // Remove PxConfig.h since we're only allowed to modify OUT_DIR. if cfg!(feature = "use-cmake") { let _ = std::fs::remove_file( env::current_dir() .unwrap() .join("PhysX/physx/include/PxConfig.h"), ); } }
32.517241
112
0.580215
f99a699db7baed08edc15490569d2d1a92199a1e
11,098
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::REG1 { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct POSLIMIT_BUCK_INR { bits: u8, } impl POSLIMIT_BUCK_INR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct POSLIMIT_BOOST_INR { bits: u8, } impl POSLIMIT_BOOST_INR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { self.bits } } #[doc = r" Value of the field"] pub struct DCDC_LOOPCTRL_CM_HST_THRESHR { bits: bool, } impl DCDC_LOOPCTRL_CM_HST_THRESHR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct DCDC_LOOPCTRL_DF_HST_THRESHR { bits: bool, } impl DCDC_LOOPCTRL_DF_HST_THRESHR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct DCDC_LOOPCTRL_EN_CM_HYSTR { bits: bool, } impl DCDC_LOOPCTRL_EN_CM_HYSTR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct DCDC_LOOPCTRL_EN_DF_HYSTR { bits: bool, } impl DCDC_LOOPCTRL_EN_DF_HYSTR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Proxy"] pub struct _POSLIMIT_BUCK_INW<'a> { w: &'a mut W, } impl<'a> _POSLIMIT_BUCK_INW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 127; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _POSLIMIT_BOOST_INW<'a> { w: &'a mut W, } impl<'a> _POSLIMIT_BOOST_INW<'a> { #[doc = r" Writes raw bits to the field"] #[inline] pub unsafe fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 127; const OFFSET: u8 = 7; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _DCDC_LOOPCTRL_CM_HST_THRESHW<'a> { w: &'a mut W, } impl<'a> _DCDC_LOOPCTRL_CM_HST_THRESHW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 21; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _DCDC_LOOPCTRL_DF_HST_THRESHW<'a> { w: &'a mut W, } impl<'a> _DCDC_LOOPCTRL_DF_HST_THRESHW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 22; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _DCDC_LOOPCTRL_EN_CM_HYSTW<'a> { w: &'a mut W, } impl<'a> _DCDC_LOOPCTRL_EN_CM_HYSTW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 23; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _DCDC_LOOPCTRL_EN_DF_HYSTW<'a> { w: &'a mut W, } impl<'a> _DCDC_LOOPCTRL_EN_DF_HYSTW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:6 - Upper limit duty cycle limit in DC-DC converter"] #[inline] pub fn poslimit_buck_in(&self) -> POSLIMIT_BUCK_INR { let bits = { const MASK: u8 = 127; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 }; POSLIMIT_BUCK_INR { bits } } #[doc = "Bits 7:13 - Upper limit duty cycle limit in DC-DC converter"] #[inline] pub fn poslimit_boost_in(&self) -> POSLIMIT_BOOST_INR { let bits = { const MASK: u8 = 127; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) as u8 }; POSLIMIT_BOOST_INR { bits } } #[doc = "Bit 21 - Enable hysteresis in switching converter common mode analog comparators"] #[inline] pub fn dcdc_loopctrl_cm_hst_thresh(&self) -> DCDC_LOOPCTRL_CM_HST_THRESHR { let bits = { const MASK: bool = true; const OFFSET: u8 = 21; ((self.bits >> OFFSET) & MASK as u32) != 0 }; DCDC_LOOPCTRL_CM_HST_THRESHR { bits } } #[doc = "Bit 22 - Enable hysteresis in switching converter differential mode analog comparators"] #[inline] pub fn dcdc_loopctrl_df_hst_thresh(&self) -> DCDC_LOOPCTRL_DF_HST_THRESHR { let bits = { const MASK: bool = true; const OFFSET: u8 = 22; ((self.bits >> OFFSET) & MASK as u32) != 0 }; DCDC_LOOPCTRL_DF_HST_THRESHR { bits } } #[doc = "Bit 23 - Enable hysteresis in switching converter common mode analog comparators"] #[inline] pub fn dcdc_loopctrl_en_cm_hyst(&self) -> DCDC_LOOPCTRL_EN_CM_HYSTR { let bits = { const MASK: bool = true; const OFFSET: u8 = 23; ((self.bits >> OFFSET) & MASK as u32) != 0 }; DCDC_LOOPCTRL_EN_CM_HYSTR { bits } } #[doc = "Bit 24 - Enable hysteresis in switching converter differential mode analog comparators"] #[inline] pub fn dcdc_loopctrl_en_df_hyst(&self) -> DCDC_LOOPCTRL_EN_DF_HYSTR { let bits = { const MASK: bool = true; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) != 0 }; DCDC_LOOPCTRL_EN_DF_HYSTR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 1557020 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:6 - Upper limit duty cycle limit in DC-DC converter"] #[inline] pub fn poslimit_buck_in(&mut self) -> _POSLIMIT_BUCK_INW { _POSLIMIT_BUCK_INW { w: self } } #[doc = "Bits 7:13 - Upper limit duty cycle limit in DC-DC converter"] #[inline] pub fn poslimit_boost_in(&mut self) -> _POSLIMIT_BOOST_INW { _POSLIMIT_BOOST_INW { w: self } } #[doc = "Bit 21 - Enable hysteresis in switching converter common mode analog comparators"] #[inline] pub fn dcdc_loopctrl_cm_hst_thresh(&mut self) -> _DCDC_LOOPCTRL_CM_HST_THRESHW { _DCDC_LOOPCTRL_CM_HST_THRESHW { w: self } } #[doc = "Bit 22 - Enable hysteresis in switching converter differential mode analog comparators"] #[inline] pub fn dcdc_loopctrl_df_hst_thresh(&mut self) -> _DCDC_LOOPCTRL_DF_HST_THRESHW { _DCDC_LOOPCTRL_DF_HST_THRESHW { w: self } } #[doc = "Bit 23 - Enable hysteresis in switching converter common mode analog comparators"] #[inline] pub fn dcdc_loopctrl_en_cm_hyst(&mut self) -> _DCDC_LOOPCTRL_EN_CM_HYSTW { _DCDC_LOOPCTRL_EN_CM_HYSTW { w: self } } #[doc = "Bit 24 - Enable hysteresis in switching converter differential mode analog comparators"] #[inline] pub fn dcdc_loopctrl_en_df_hyst(&mut self) -> _DCDC_LOOPCTRL_EN_DF_HYSTW { _DCDC_LOOPCTRL_EN_DF_HYSTW { w: self } } }
28.976501
101
0.55893
0303bfe6b2b47273299e1af5dd5f0034426f35d1
1,858
use core::intrinsics::{sqrtf32, sqrtf64}; use core::{f32, f64}; pub trait Sqrt { fn sqrt(&self) -> Self; } macro_rules! trait_sqrt { ($t:ident, $a:ident, $f:ident) => ( impl Sqrt for $t { #[inline(always)] fn sqrt(&self) -> Self { if *self <= 0 as $t { 0 as $t } else { unsafe { $f(*self as $a) as $t } } } } ); } macro_rules! trait_sqrt_no_cast { ($t:ident, $f:ident) => ( impl Sqrt for $t { #[inline(always)] fn sqrt(&self) -> Self { if *self < 0.0 { $t::NAN } else { unsafe { $f(*self) } } } } ); } trait_sqrt!(usize, f64, sqrtf64); trait_sqrt!(u8, f32, sqrtf32); trait_sqrt!(u16, f32, sqrtf32); trait_sqrt!(u32, f64, sqrtf64); trait_sqrt!(u64, f64, sqrtf64); trait_sqrt!(isize, f64, sqrtf64); trait_sqrt!(i8, f32, sqrtf32); trait_sqrt!(i16, f32, sqrtf32); trait_sqrt!(i32, f64, sqrtf64); trait_sqrt!(i64, f64, sqrtf64); trait_sqrt_no_cast!(f32, sqrtf32); trait_sqrt_no_cast!(f64, sqrtf64); #[cfg(test)] mod test { use ::Sqrt; fn test_sqrt<T: Sqrt>(x: T) -> T { x.sqrt() } #[test] fn sqrt() { assert_eq!(test_sqrt(4u8), 2u8); assert_eq!(test_sqrt(4u16), 2u16); assert_eq!(test_sqrt(4u32), 2u32); assert_eq!(test_sqrt(4u64), 2u64); assert_eq!(test_sqrt(4i8), 2i8); assert_eq!(test_sqrt(4i16), 2i16); assert_eq!(test_sqrt(4i32), 2i32); assert_eq!(test_sqrt(4i64), 2i64); assert_eq!(test_sqrt(4f32), 2f32); assert_eq!(test_sqrt(4f64), 2f64); } }
22.658537
45
0.477395
bf1ce233f9504c58493b5d0cfc841413f6971c76
536
use mmtk::vm::ReferenceGlue; use mmtk::util::ObjectReference; use mmtk::util::opaque_pointer::VMWorkerThread; use crate::DummyVM; pub struct VMReferenceGlue {} impl ReferenceGlue<DummyVM> for VMReferenceGlue { fn set_referent(_reference: ObjectReference, _referent: ObjectReference) { unimplemented!() } fn get_referent(_object: ObjectReference) -> ObjectReference { unimplemented!() } fn enqueue_references(_references: &[ObjectReference], _tls: VMWorkerThread) { unimplemented!() } }
28.210526
82
0.718284
0ee0637232ca4d444237c8b054ac4623a3ba2af9
154
// compile-pass #![feature(no_core, lang_items)] #![no_core] #![crate_type = "lib"] #[lang = "sized"] trait Sized {} extern { pub static A: u32; }
11.846154
32
0.603896
8f9ec2e90287620c74e4bbb57dfbab703b0c4d60
3,463
#[doc = "Register `EVENTS_LASTRX` reader"] pub struct R(crate::R<EVENTS_LASTRX_SPEC>); impl core::ops::Deref for R { type Target = crate::R<EVENTS_LASTRX_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<EVENTS_LASTRX_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<EVENTS_LASTRX_SPEC>) -> Self { R(reader) } } #[doc = "Register `EVENTS_LASTRX` writer"] pub struct W(crate::W<EVENTS_LASTRX_SPEC>); impl core::ops::Deref for W { type Target = crate::W<EVENTS_LASTRX_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<EVENTS_LASTRX_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<EVENTS_LASTRX_SPEC>) -> Self { W(writer) } } #[doc = "Field `EVENTS_LASTRX` reader - "] pub struct EVENTS_LASTRX_R(crate::FieldReader<bool, bool>); impl EVENTS_LASTRX_R { pub(crate) fn new(bits: bool) -> Self { EVENTS_LASTRX_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for EVENTS_LASTRX_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `EVENTS_LASTRX` writer - "] pub struct EVENTS_LASTRX_W<'a> { w: &'a mut W, } impl<'a> EVENTS_LASTRX_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 0"] #[inline(always)] pub fn events_lastrx(&self) -> EVENTS_LASTRX_R { EVENTS_LASTRX_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 0"] #[inline(always)] pub fn events_lastrx(&mut self) -> EVENTS_LASTRX_W { EVENTS_LASTRX_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "Byte boundary, starting to receive the last byte\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [events_lastrx](index.html) module"] pub struct EVENTS_LASTRX_SPEC; impl crate::RegisterSpec for EVENTS_LASTRX_SPEC { type Ux = u32; } #[doc = "`read()` method returns [events_lastrx::R](R) reader structure"] impl crate::Readable for EVENTS_LASTRX_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [events_lastrx::W](W) writer structure"] impl crate::Writable for EVENTS_LASTRX_SPEC { type Writer = W; } #[doc = "`reset()` method sets EVENTS_LASTRX to value 0"] impl crate::Resettable for EVENTS_LASTRX_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
30.646018
442
0.615074
e5f7d20a5f6edfc758ac43a4a01e6aa6852713af
295
use ethernet::EthNetDriver; pub use stm_eth::StmEth; pub fn is_supported() -> bool { #[cfg(any(feature = "stm32f407"))] return true; #[cfg(all(not(feature = "stmf407")))] return false; return true; } pub fn net_init() { let mut eth = StmEth::new(); eth.init(); }
16.388889
41
0.6
f510dadd86e4f2ea79346092d10c3094d984056f
14,985
// Copyright (c) 2020-2021 Via Technology Ltd. All Rights Reserved. // // 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. //! OpenCL Event Object API. #![allow(non_camel_case_types)] pub use super::ffi::cl_egl::{ CL_COMMAND_ACQUIRE_EGL_OBJECTS_KHR, CL_COMMAND_EGL_FENCE_SYNC_OBJECT_KHR, CL_COMMAND_RELEASE_EGL_OBJECTS_KHR, }; pub use super::ffi::cl_ext::{ CL_COMMAND_MEMADVISE_INTEL, CL_COMMAND_MEMCPY_INTEL, CL_COMMAND_MEMFILL_INTEL, CL_COMMAND_MIGRATEMEM_INTEL, }; pub use cl_sys::{ CL_COMMAND_ACQUIRE_GL_OBJECTS, CL_COMMAND_BARRIER, CL_COMMAND_COPY_BUFFER, CL_COMMAND_COPY_BUFFER_RECT, CL_COMMAND_COPY_BUFFER_TO_IMAGE, CL_COMMAND_COPY_IMAGE, CL_COMMAND_COPY_IMAGE_TO_BUFFER, CL_COMMAND_FILL_BUFFER, CL_COMMAND_FILL_IMAGE, CL_COMMAND_MAP_BUFFER, CL_COMMAND_MAP_IMAGE, CL_COMMAND_MARKER, CL_COMMAND_MIGRATE_MEM_OBJECTS, CL_COMMAND_NATIVE_KERNEL, CL_COMMAND_NDRANGE_KERNEL, CL_COMMAND_READ_BUFFER, CL_COMMAND_READ_BUFFER_RECT, CL_COMMAND_READ_IMAGE, CL_COMMAND_RELEASE_GL_OBJECTS, CL_COMMAND_SVM_FREE, CL_COMMAND_SVM_MAP, CL_COMMAND_SVM_MEMCPY, CL_COMMAND_SVM_MEMFILL, CL_COMMAND_SVM_UNMAP, CL_COMMAND_TASK, CL_COMMAND_UNMAP_MEM_OBJECT, CL_COMMAND_USER, CL_COMMAND_WRITE_BUFFER, CL_COMMAND_WRITE_BUFFER_RECT, CL_COMMAND_WRITE_IMAGE, CL_COMPLETE, CL_QUEUED, CL_RUNNING, CL_SUBMITTED, }; // #ifdef CL_VERSION_3_0 pub const CL_COMMAND_SVM_MIGRATE_MEM: cl_uint = 0x120E; use super::error_codes::{CL_INVALID_VALUE, CL_SUCCESS}; use super::info_type::InfoType; use super::types::{ cl_command_type, cl_context, cl_event, cl_event_info, cl_int, cl_profiling_info, cl_uint, cl_ulong, }; use cl_sys::{ clCreateUserEvent, clGetEventInfo, clGetEventProfilingInfo, clReleaseEvent, clRetainEvent, clSetEventCallback, clSetUserEventStatus, clWaitForEvents, }; use super::{api_info_size, api_info_value, api_info_vector}; use libc::{c_void, intptr_t, size_t}; use std::fmt; use std::mem; use std::ptr; /// Wait for OpenCL events to complete. /// Calls clWaitForEvents. /// /// * `events` - a slice of OpenCL events. /// /// returns an empty Result or the error code from the OpenCL C API function. #[inline] pub fn wait_for_events(events: &[cl_event]) -> Result<(), cl_int> { let status: cl_int = unsafe { clWaitForEvents(events.len() as cl_uint, events.as_ptr()) }; if CL_SUCCESS != status { Err(status) } else { Ok(()) } } /// Get data about an OpenCL event. /// Calls clGetEventInfo to get the desired data about the event. pub fn get_event_data( event: cl_event, param_name: cl_event_info, ) -> Result<Vec<u8>, cl_int> { api_info_size!(get_size, clGetEventInfo); let size = get_size(event, param_name)?; api_info_vector!(get_vector, u8, clGetEventInfo); Ok(get_vector(event, param_name, size)?) } // cl_event_info #[derive(Clone, Copy, Debug)] pub enum EventInfo { CL_EVENT_COMMAND_QUEUE = 0x11D0, CL_EVENT_COMMAND_TYPE = 0x11D1, CL_EVENT_REFERENCE_COUNT = 0x11D2, CL_EVENT_COMMAND_EXECUTION_STATUS = 0x11D3, CL_EVENT_CONTEXT = 0x11D4, } /// Get specific information about an OpenCL event. /// Calls clGetEventInfo to get the desired information about the event. /// /// * `event` - the OpenCL event. /// * `param_name` - the type of program information being queried, see: /// [Event Object Queries](https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_API.html#event-info-table). /// /// returns a Result containing the desired information in an InfoType enum /// or the error code from the OpenCL C API function. pub fn get_event_info(event: cl_event, param_name: EventInfo) -> Result<InfoType, cl_int> { let param_id = param_name as cl_event_info; match param_name { EventInfo::CL_EVENT_COMMAND_EXECUTION_STATUS => { api_info_value!(get_value, cl_int, clGetEventInfo); Ok(InfoType::Int(get_value(event, param_id)?)) } EventInfo::CL_EVENT_COMMAND_TYPE | EventInfo::CL_EVENT_REFERENCE_COUNT => { api_info_value!(get_value, cl_uint, clGetEventInfo); Ok(InfoType::Uint(get_value(event, param_id)?)) } EventInfo::CL_EVENT_COMMAND_QUEUE | EventInfo::CL_EVENT_CONTEXT => { api_info_value!(get_value, intptr_t, clGetEventInfo); Ok(InfoType::Ptr(get_value(event, param_id)?)) } } } /// Create an OpenCL user event object. /// Calls clCreateUserEvent to create an OpenCL event. /// /// * `context` - a valid OpenCL context. /// /// returns a Result containing the new OpenCL event object /// or the error code from the OpenCL C API function. #[inline] pub fn create_user_event(context: cl_context) -> Result<cl_event, cl_int> { let mut status: cl_int = CL_INVALID_VALUE; let event: cl_event = unsafe { clCreateUserEvent(context, &mut status) }; if CL_SUCCESS != status { Err(status) } else { Ok(event) } } /// Retain an OpenCL event. /// Calls clRetainEvent to increment the event reference count. /// /// * `event` - the OpenCL event. /// /// returns an empty Result or the error code from the OpenCL C API function. #[inline] pub fn retain_event(event: cl_event) -> Result<(), cl_int> { let status: cl_int = unsafe { clRetainEvent(event) }; if CL_SUCCESS != status { Err(status) } else { Ok(()) } } /// Release an OpenCL event. /// Calls clReleaseEvent to decrement the event reference count. /// /// * `event` - the OpenCL event. /// /// returns an empty Result or the error code from the OpenCL C API function. #[inline] pub fn release_event(event: cl_event) -> Result<(), cl_int> { let status: cl_int = unsafe { clReleaseEvent(event) }; if CL_SUCCESS != status { Err(status) } else { Ok(()) } } /// Set the execution status of a user event object. /// Calls clSetUserEventStatus to set the execution status. /// /// * `event` - the OpenCL event. /// * `execution_status` - the OpenCL execution_status. /// /// returns an empty Result or the error code from the OpenCL C API function. #[inline] pub fn set_user_event_status(event: cl_event, execution_status: cl_int) -> Result<(), cl_int> { let status: cl_int = unsafe { clSetUserEventStatus(event, execution_status) }; if CL_SUCCESS != status { Err(status) } else { Ok(()) } } /// Register a user callback function for a specific command execution status, /// Calls clSetEventCallback to register a callback function. /// /// * `event` - the OpenCL event. /// * `pfn_notify` - function pointer to the callback function. /// * `user_data` - passed as an argument when pfn_notify is called, or ptr::null_mut(). /// /// returns an empty Result or the error code from the OpenCL C API function. #[inline] pub fn set_event_callback( event: cl_event, command_exec_callback_type: cl_int, pfn_notify: extern "C" fn(cl_event, cl_int, *mut c_void), user_data: *mut c_void, ) -> Result<(), cl_int> { let status: cl_int = unsafe { clSetEventCallback( event, command_exec_callback_type, Some(pfn_notify), user_data, ) }; if CL_SUCCESS != status { Err(status) } else { Ok(()) } } /// Get profiling data about an OpenCL event. /// Calls clGetEventProfilingInfo to get the desired profiling data about the event. pub fn get_event_profiling_data( event: cl_event, param_name: cl_profiling_info, ) -> Result<Vec<u8>, cl_int> { api_info_size!(get_size, clGetEventProfilingInfo); let size = get_size(event, param_name)?; api_info_vector!(get_vector, u8, clGetEventProfilingInfo); Ok(get_vector(event, param_name, size)?) } // cl_profiling_info #[derive(Clone, Copy, Debug)] pub enum ProfilingInfo { CL_PROFILING_COMMAND_QUEUED = 0x1280, CL_PROFILING_COMMAND_SUBMIT = 0x1281, CL_PROFILING_COMMAND_START = 0x1282, CL_PROFILING_COMMAND_END = 0x1283, // CL_VERSION_2_0 CL_PROFILING_COMMAND_COMPLETE = 0x1284, } /// Get profiling information for a command associated with an event when /// profiling is enabled. /// Calls clGetEventProfilingInfo to get the desired information. /// /// * `event` - the OpenCL event. /// * `param_name` - the type of event profiling information being queried, see: /// [Event Profiling Queries](https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/OpenCL_API.html#event-profiling-info-table). /// /// returns a Result containing the desired information in an InfoType enum /// or the error code from the OpenCL C API function. pub fn get_event_profiling_info( event: cl_event, param_name: ProfilingInfo, ) -> Result<InfoType, cl_int> { let param_id = param_name as cl_profiling_info; match param_name { ProfilingInfo::CL_PROFILING_COMMAND_QUEUED | ProfilingInfo::CL_PROFILING_COMMAND_SUBMIT | ProfilingInfo::CL_PROFILING_COMMAND_START | ProfilingInfo::CL_PROFILING_COMMAND_END | ProfilingInfo::CL_PROFILING_COMMAND_COMPLETE // CL_VERSION_2_0 => { api_info_value!(get_value, cl_ulong, clGetEventProfilingInfo); Ok(InfoType::Ulong(get_value(event, param_id)?)) } } } pub fn status_text(status: cl_int) -> &'static str { match status { CL_COMPLETE => "CL_COMPLETE", CL_RUNNING => "CL_RUNNING", CL_SUBMITTED => "CL_SUBMITTED", CL_QUEUED => "CL_QUEUED", _ => "UNKNOWN_STATUS", } } #[derive(Debug)] /// CommandExecutionStatus is a newtype around the OpenCL command execution status pub struct CommandExecutionStatus(pub cl_int); /// Implement the From trait impl From<cl_int> for CommandExecutionStatus { fn from(status: cl_int) -> Self { CommandExecutionStatus(status) } } /// Implement the Display trait impl fmt::Display for CommandExecutionStatus { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", status_text(self.0)) } } pub fn command_type_text(command_type: cl_command_type) -> &'static str { match command_type { CL_COMMAND_NDRANGE_KERNEL => "CL_COMMAND_NDRANGE_KERNEL", CL_COMMAND_TASK => "CL_COMMAND_TASK", CL_COMMAND_NATIVE_KERNEL => "CL_COMMAND_NATIVE_KERNEL", CL_COMMAND_READ_BUFFER => "CL_COMMAND_READ_BUFFER", CL_COMMAND_WRITE_BUFFER => "CL_COMMAND_WRITE_BUFFER", CL_COMMAND_COPY_BUFFER => "CL_COMMAND_COPY_BUFFER", CL_COMMAND_READ_IMAGE => "CL_COMMAND_READ_IMAGE", CL_COMMAND_WRITE_IMAGE => "CL_COMMAND_WRITE_IMAGE", CL_COMMAND_COPY_IMAGE => "CL_COMMAND_COPY_IMAGE", CL_COMMAND_COPY_IMAGE_TO_BUFFER => "CL_COMMAND_COPY_IMAGE_TO_BUFFER", CL_COMMAND_COPY_BUFFER_TO_IMAGE => "CL_COMMAND_COPY_BUFFER_TO_IMAGE", CL_COMMAND_MAP_BUFFER => "CL_COMMAND_MAP_BUFFER", CL_COMMAND_MAP_IMAGE => "CL_COMMAND_MAP_IMAGE", CL_COMMAND_UNMAP_MEM_OBJECT => "CL_COMMAND_UNMAP_MEM_OBJECT", CL_COMMAND_MARKER => "CL_COMMAND_MARKER", CL_COMMAND_ACQUIRE_GL_OBJECTS => "CL_COMMAND_ACQUIRE_GL_OBJECTS", CL_COMMAND_RELEASE_GL_OBJECTS => "CL_COMMAND_RELEASE_GL_OBJECTS", CL_COMMAND_READ_BUFFER_RECT => "CL_COMMAND_READ_BUFFER_RECT", CL_COMMAND_WRITE_BUFFER_RECT => "CL_COMMAND_WRITE_BUFFER_RECT", CL_COMMAND_COPY_BUFFER_RECT => "CL_COMMAND_COPY_BUFFER_RECT", CL_COMMAND_USER => "CL_COMMAND_USER", CL_COMMAND_BARRIER => "CL_COMMAND_BARRIER", CL_COMMAND_MIGRATE_MEM_OBJECTS => "CL_COMMAND_MIGRATE_MEM_OBJECTS", CL_COMMAND_FILL_BUFFER => "CL_COMMAND_FILL_BUFFER", CL_COMMAND_FILL_IMAGE => "CL_COMMAND_FILL_IMAGE", CL_COMMAND_SVM_FREE => "CL_COMMAND_SVM_FREE", CL_COMMAND_SVM_MEMCPY => "CL_COMMAND_SVM_MEMCPY", CL_COMMAND_SVM_MEMFILL => "CL_COMMAND_SVM_MEMFILL", CL_COMMAND_SVM_MAP => "CL_COMMAND_SVM_MAP", CL_COMMAND_SVM_UNMAP => "CL_COMMAND_SVM_UNMAP", CL_COMMAND_SVM_MIGRATE_MEM => "CL_COMMAND_SVM_MIGRATE_MEM", // cl_egl values CL_COMMAND_ACQUIRE_EGL_OBJECTS_KHR => "CL_COMMAND_ACQUIRE_EGL_OBJECTS_KHR", CL_COMMAND_RELEASE_EGL_OBJECTS_KHR => "CL_COMMAND_RELEASE_EGL_OBJECTS_KHR", CL_COMMAND_EGL_FENCE_SYNC_OBJECT_KHR => "CL_COMMAND_EGL_FENCE_SYNC_OBJECT_KHR", // cl_ext values CL_COMMAND_MEMFILL_INTEL => "CL_COMMAND_MEMFILL_INTEL", CL_COMMAND_MEMCPY_INTEL => "CL_COMMAND_MEMCPY_INTEL", CL_COMMAND_MIGRATEMEM_INTEL => "CL_COMMAND_MIGRATEMEM_INTEL", CL_COMMAND_MEMADVISE_INTEL => "CL_COMMAND_MEMADVISE_INTEL", _ => "UNKNOWN_COMMAND_TYPE", } } #[derive(Debug)] /// EventCommandType is a newtype around the OpenCL cl_command_type pub struct EventCommandType(pub cl_command_type); /// Implement the From trait for EventCommandType impl From<cl_command_type> for EventCommandType { fn from(command_type: cl_command_type) -> Self { EventCommandType(command_type) } } /// Implement the Display trait for EventCommandType impl fmt::Display for EventCommandType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", command_type_text(self.0)) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_status_text() { let text = status_text(CL_COMPLETE); assert_eq!("CL_COMPLETE", text); let text = status_text(CL_RUNNING); assert_eq!("CL_RUNNING", text); let text = status_text(CL_SUBMITTED); assert_eq!("CL_SUBMITTED", text); let text = status_text(CL_QUEUED); assert_eq!("CL_QUEUED", text); let text = status_text(CL_QUEUED + 1); assert_eq!("UNKNOWN_STATUS", text); } #[test] fn test_command_type_text() { let text = command_type_text(CL_COMMAND_NDRANGE_KERNEL); assert_eq!("CL_COMMAND_NDRANGE_KERNEL", text); let text = command_type_text(CL_COMMAND_COPY_IMAGE); assert_eq!("CL_COMMAND_COPY_IMAGE", text); let text = command_type_text(CL_COMMAND_READ_BUFFER_RECT); assert_eq!("CL_COMMAND_READ_BUFFER_RECT", text); let text = command_type_text(CL_COMMAND_BARRIER); assert_eq!("CL_COMMAND_BARRIER", text); let text = command_type_text(CL_COMMAND_SVM_FREE); assert_eq!("CL_COMMAND_SVM_FREE", text); let text = command_type_text(CL_COMMAND_SVM_MIGRATE_MEM + 1); assert_eq!("UNKNOWN_COMMAND_TYPE", text); } }
36.195652
137
0.707774
1a84ff2d8f3bb9fac62cfd909b169df43ed29ce2
14,170
//! Handler for stable XDG shell clients. use libc; use wayland_sys::server::WAYLAND_SERVER_HANDLE; use wlroots_sys::wlr_xdg_surface; use {compositor, surface, shell::xdg_shell::{self, SurfaceState}, utils::Handleable}; /// Handles events from the client stable XDG shells. #[allow(unused_variables)] pub trait Handler { /// Called when the surface recieve a request event. fn on_commit(&mut self, compositor_handle: compositor::Handle, surface_handle: surface::Handle, xdg_shell_handle: xdg_shell::Handle) {} /// Called when the wayland shell is destroyed (e.g by the user) fn destroyed(&mut self, compositor::Handle, xdg_shell::Handle) {} /// Called when the ping request timed out. /// /// This usually indicates something is wrong with the client. fn ping_timeout(&mut self, compositor_handle: compositor::Handle, surface_handle: surface::Handle, xdg_shell_handle: xdg_shell::Handle) {} /// Called when a new popup appears in the xdg tree. fn new_popup(&mut self, compositor_handle: compositor::Handle, surface_handle: surface::Handle, xdg_shell_handle: xdg_shell::Handle) {} /// Called when there is a request to maximize the XDG surface. fn maximize_request(&mut self, compositor_handle: compositor::Handle, surface_handle: surface::Handle, xdg_shell_handle: xdg_shell::Handle) {} /// Called when there is a request to minimize the XDG surface. fn minimize_request(&mut self, compositor_handle: compositor::Handle, surface_handle: surface::Handle, xdg_shell_handle: xdg_shell::Handle) {} /// Called when there is a request to move the shell surface somewhere else. fn move_request(&mut self, compositor_handle: compositor::Handle, surface_handle: surface::Handle, xdg_shell_handle: xdg_shell::Handle, event: &xdg_shell::event::Move) { } /// Called when there is a request to resize the shell surface. fn resize_request(&mut self, compositor_handle: compositor::Handle, surface_handle: surface::Handle, xdg_shell_handle: xdg_shell::Handle, event: &xdg_shell::event::Resize) { } /// Called when there is a request to make the shell surface fullscreen. fn fullscreen_request(&mut self, compositor_handle: compositor::Handle, surface_handle: surface::Handle, xdg_shell_handle: xdg_shell::Handle, event: &xdg_shell::event::SetFullscreen) { } /// Called when there is a request to show the window menu. fn show_window_menu_request(&mut self, compositor_handle: compositor::Handle, surface_handle: surface::Handle, xdg_shell_handle: xdg_shell::Handle, event: &xdg_shell::event::ShowWindowMenu) { } /// Called when the surface is ready to be mapped. It should be added to the list of views at /// this time. fn map_request(&mut self, compositor_handle: compositor::Handle, surface_handle: surface::Handle, xdg_shell_handle: xdg_shell::Handle) { } /// Called when the surface should be unmapped. It should be removed from the list of views at /// this time, but may be remapped at a later time. fn unmap_request(&mut self, compositor_handle: compositor::Handle, surface_handle: surface::Handle, xdg_shell_handle: xdg_shell::Handle) { } } wayland_listener!(pub(crate) XdgShell, (xdg_shell::Surface, Option<Box<Handler>>), [ destroy_listener => destroy_notify: |this: &mut XdgShell, data: *mut libc::c_void,| unsafe { let (ref shell_surface, ref mut manager) = this.data; let compositor = match compositor::handle() { Some(handle) => handle, None => return }; if let Some(ref mut manager) = manager.as_mut() { manager.destroyed(compositor, shell_surface.weak_reference()); } let surface_ptr = data as *mut wlr_xdg_surface; let shell_state_ptr = (*surface_ptr).data as *mut SurfaceState; Box::from_raw((*shell_state_ptr).shell); }; commit_listener => commit_notify: |this: &mut XdgShell, _data: *mut libc::c_void,| unsafe { let (ref mut shell_surface, ref mut manager) = match &mut this.data { (_, None) => return, (ss, Some(manager)) => (ss, manager) }; let surface = shell_surface.surface(); let compositor = match compositor::handle() { Some(handle) => handle, None => return }; manager.on_commit(compositor, surface, shell_surface.weak_reference()); }; ping_timeout_listener => ping_timeout_notify: |this: &mut XdgShell, _data: *mut libc::c_void,| unsafe { let (ref mut shell_surface, ref mut manager) = match &mut this.data { (_, None) => return, (ss, Some(manager)) => (ss, manager) }; let surface = shell_surface.surface(); let compositor = match compositor::handle() { Some(handle) => handle, None => return }; manager.ping_timeout(compositor, surface, shell_surface.weak_reference()); }; new_popup_listener => new_popup_notify: |this: &mut XdgShell, _data: *mut libc::c_void,| unsafe { let (ref mut shell_surface, ref mut manager) = match &mut this.data { (_, None) => return, (ss, Some(manager)) => (ss, manager) }; let surface = shell_surface.surface(); let compositor = match compositor::handle() { Some(handle) => handle, None => return }; manager.new_popup(compositor, surface, shell_surface.weak_reference()); }; maximize_listener => maximize_notify: |this: &mut XdgShell, _event: *mut libc::c_void,| unsafe { let (ref mut shell_surface, ref mut manager) = match &mut this.data { (_, None) => return, (ss, Some(manager)) => (ss, manager) }; let surface = shell_surface.surface(); let compositor = match compositor::handle() { Some(handle) => handle, None => return }; manager.maximize_request(compositor, surface, shell_surface.weak_reference()); }; fullscreen_listener => fullscreen_notify: |this: &mut XdgShell, event: *mut libc::c_void,| unsafe { let (ref mut shell_surface, ref mut manager) = match &mut this.data { (_, None) => return, (ss, Some(manager)) => (ss, manager) }; let surface = shell_surface.surface(); let compositor = match compositor::handle() { Some(handle) => handle, None => return }; let event = xdg_shell::event::SetFullscreen::from_ptr(event as _); manager.fullscreen_request(compositor, surface, shell_surface.weak_reference(), &event); }; minimize_listener => minimize_notify: |this: &mut XdgShell, _event: *mut libc::c_void,| unsafe { let (ref mut shell_surface, ref mut manager) = match &mut this.data { (_, None) => return, (ss, Some(manager)) => (ss, manager) }; let surface = shell_surface.surface(); let compositor = match compositor::handle() { Some(handle) => handle, None => return }; manager.minimize_request(compositor, surface, shell_surface.weak_reference()); }; move_listener => move_notify: |this: &mut XdgShell, event: *mut libc::c_void,| unsafe { let (ref mut shell_surface, ref mut manager) = match &mut this.data { (_, None) => return, (ss, Some(manager)) => (ss, manager) }; let surface = shell_surface.surface(); let compositor = match compositor::handle() { Some(handle) => handle, None => return }; let event = xdg_shell::event::Move::from_ptr(event as _); manager.move_request(compositor, surface, shell_surface.weak_reference(), &event); }; resize_listener => resize_notify: |this: &mut XdgShell, event: *mut libc::c_void,| unsafe { let (ref mut shell_surface, ref mut manager) = match &mut this.data { (_, None) => return, (ss, Some(manager)) => (ss, manager) }; let surface = shell_surface.surface(); let compositor = match compositor::handle() { Some(handle) => handle, None => return }; let event = xdg_shell::event::Resize::from_ptr(event as _); manager.resize_request(compositor, surface, shell_surface.weak_reference(), &event); }; show_window_menu_listener => show_window_menu_notify: |this: &mut XdgShell, event: *mut libc::c_void,| unsafe { let (ref mut shell_surface, ref mut manager) = match &mut this.data { (_, None) => return, (ss, Some(manager)) => (ss, manager) }; let surface = shell_surface.surface(); let compositor = match compositor::handle() { Some(handle) => handle, None => return }; let event = xdg_shell::event::ShowWindowMenu::from_ptr(event as _); manager.show_window_menu_request(compositor, surface, shell_surface.weak_reference(), &event); }; map_listener => map_notify: |this: &mut XdgShell, _event: *mut libc::c_void,| unsafe { let (ref mut shell_surface, ref mut manager) = match &mut this.data { (_, None) => return, (ss, Some(manager)) => (ss, manager) }; let surface = shell_surface.surface(); let compositor = match compositor::handle() { Some(handle) => handle, None => return }; manager.map_request(compositor, surface, shell_surface.weak_reference()); }; unmap_listener => unmap_notify: |this: &mut XdgShell, _event: *mut libc::c_void,| unsafe { let (ref mut shell_surface, ref mut manager) = match &mut this.data { (_, None) => return, (ss, Some(manager)) => (ss, manager) }; let surface = shell_surface.surface(); let compositor = match compositor::handle() { Some(handle) => handle, None => return }; manager.unmap_request(compositor, surface, shell_surface.weak_reference()); }; ]); impl XdgShell { pub(crate) fn surface_mut(&mut self) -> xdg_shell::Handle { self.data.0.weak_reference() } } impl Drop for XdgShell { fn drop(&mut self) { unsafe { ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_list_remove, &mut (*self.destroy_listener()).link as *mut _ as _); ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_list_remove, &mut (*self.commit_listener()).link as *mut _ as _); ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_list_remove, &mut (*self.ping_timeout_listener()).link as *mut _ as _); ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_list_remove, &mut (*self.new_popup_listener()).link as *mut _ as _); ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_list_remove, &mut (*self.maximize_listener()).link as *mut _ as _); ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_list_remove, &mut (*self.fullscreen_listener()).link as *mut _ as _); ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_list_remove, &mut (*self.minimize_listener()).link as *mut _ as _); ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_list_remove, &mut (*self.move_listener()).link as *mut _ as _); ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_list_remove, &mut (*self.resize_listener()).link as *mut _ as _); ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_list_remove, &mut (*self.show_window_menu_listener()).link as *mut _ as _); ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_list_remove, &mut (*self.map_listener()).link as *mut _ as _); ffi_dispatch!(WAYLAND_SERVER_HANDLE, wl_list_remove, &mut (*self.unmap_listener()).link as *mut _ as _); } } }
40.953757
98
0.532392
6a04caf4ae87359676b33996b88d7f2e28228e5a
4,577
use bear_lib_terminal::Color; /// Indicates how the given object is rendered on a map. #[derive(Clone, Debug)] pub struct Renderable { /// The character used to render the object. pub char: Option<char>, /// The color used to render the object. pub foreground_color: Option<Color>, /// The color used to render the object. pub background_color: Option<Color>, } /// Indicates how the given object is rendered on a map. impl Renderable { /// Constructor. pub fn new() -> Renderable { trace!("Entering Renderable::to_north()."); Renderable { char: None, foreground_color: None, background_color: None, } } /// Return a modified version of this renderable. pub fn with_char(&self, char: Option<char>) -> Renderable { Renderable { char: char, foreground_color: self.foreground_color, background_color: self.background_color, } } /// Return a modified version of this renderable. pub fn with_foreground_color(&self, foreground_color: Option<Color>) -> Renderable { Renderable { char: self.char, foreground_color: foreground_color, background_color: self.background_color, } } /// Return a modified version of this renderable. pub fn with_background_color(&self, background_color: Option<Color>) -> Renderable { Renderable { char: self.char, foreground_color: self.foreground_color, background_color: background_color, } } } /// Creates a default instance. impl Default for Renderable { /// Creates a default instance. fn default() -> Self { Renderable::new() } } /// A factory for renderables. #[derive(Clone, Copy, Debug)] pub enum Factory { /// The PC. Player, /// An orc. Orc, /// A troll. Troll, /// A goblin. Goblin, /// A kobold. Kobold, /// A chicken. Chicken, /// A mushroom. Mushroom, /// Moss. Moss, /// A human, Human, /// A floor (dark). Floor, /// A wall (dark). Wall, } impl Factory { /// Creates a renderable for the given value. pub fn create(self) -> Renderable { trace!("Entering Factory::create()."); use Factory::*; match self { Player => Renderable { char: Some('@'), foreground_color: Some(Color::from_rgb(255, 255, 255)), background_color: None, }, Orc => Renderable { char: Some('o'), foreground_color: Some(Color::from_rgb(64, 128, 64)), background_color: None, }, Troll => Renderable { char: Some('T'), foreground_color: Some(Color::from_rgb(0, 255, 0)), background_color: None, }, Goblin => Renderable { char: Some('g'), foreground_color: Some(Color::from_rgb(0, 164, 96)), background_color: None, }, Kobold => Renderable { char: Some('k'), foreground_color: Some(Color::from_rgb(0, 255, 128)), background_color: None, }, Chicken => Renderable { char: Some('c'), foreground_color: Some(Color::from_rgb(230, 230, 230)), background_color: None, }, Mushroom => Renderable { char: Some('🍄'), foreground_color: Some(Color::from_rgb(230, 230, 230)), background_color: None, }, Moss => Renderable { char: Some('#'), foreground_color: Some(Color::from_rgb(173, 223, 173)), background_color: None, }, Human => Renderable { char: Some('h'), foreground_color: Some(Color::from_rgb(115, 115, 255)), background_color: None, }, Floor => Renderable { char: Some('.'), foreground_color: Some(Color::from_rgb(0, 0, 0)), background_color: Some(Color::from_rgb(32, 32, 32)), }, Wall => Renderable { char: Some('#'), foreground_color: Some(Color::from_rgb(0, 0, 0)), background_color: Some(Color::from_rgb(16, 16, 16)), }, } } }
28.786164
88
0.516932
18f30483c5d90140990036842155b1d618066552
2,885
use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use cosmwasm_std::{CanonicalAddr, Decimal, Order, StdResult, Storage, Uint128}; use cosmwasm_storage::{singleton_read, ReadonlyBucket}; use crate::state::{store_config, store_pool_info, Config, PoolInfo, KEY_CONFIG, PREFIX_POOL_INFO}; #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct LegacyConfig { pub owner: CanonicalAddr, pub mirror_token: CanonicalAddr, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] pub struct LegacyPoolInfo { pub staking_token: CanonicalAddr, pub pending_reward: Uint128, // not distributed amount due to zero bonding pub total_bond_amount: Uint128, pub reward_index: Decimal, } fn read_legacy_config<S: Storage>(storage: &S) -> StdResult<LegacyConfig> { singleton_read(storage, KEY_CONFIG).load() } fn read_legacy_pool_infos<S: Storage>( storage: &S, ) -> StdResult<Vec<(CanonicalAddr, LegacyPoolInfo)>> { let pool_info_bucket: ReadonlyBucket<S, LegacyPoolInfo> = ReadonlyBucket::new(PREFIX_POOL_INFO, storage); pool_info_bucket .range(None, None, Order::Ascending) .map(|item| { let (k, v) = item?; Ok((CanonicalAddr::from(k), v)) }) .collect() } pub fn migrate_config<S: Storage>( storage: &mut S, mint_contract: CanonicalAddr, oracle_contract: CanonicalAddr, terraswap_factory: CanonicalAddr, base_denom: String, premium_min_update_interval: u64, ) -> StdResult<()> { let legacy_config = read_legacy_config(storage)?; store_config( storage, &Config { owner: legacy_config.owner, mirror_token: legacy_config.mirror_token, mint_contract, oracle_contract, terraswap_factory, base_denom, premium_min_update_interval, }, ) } pub fn migrate_pool_infos<S: Storage>(storage: &mut S) -> StdResult<()> { let legacy_pool_infos: Vec<(CanonicalAddr, LegacyPoolInfo)> = read_legacy_pool_infos(storage)?; for (asset_token, legacy_pool_info) in legacy_pool_infos.iter() { store_pool_info( storage, &asset_token, &PoolInfo { staking_token: legacy_pool_info.staking_token.clone(), pending_reward: legacy_pool_info.pending_reward, total_bond_amount: legacy_pool_info.total_bond_amount, reward_index: legacy_pool_info.reward_index, short_pending_reward: Uint128::zero(), total_short_amount: Uint128::zero(), short_reward_index: Decimal::zero(), premium_rate: Decimal::zero(), short_reward_weight: Decimal::zero(), premium_updated_time: 0, }, )?; } Ok(()) }
32.784091
99
0.651993
d5d64094f7af98df207e83baaf35fd74f7de91a7
12,523
// Copyright 2016 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // See the License for the specific language governing permissions and // limitations under the License. use std::io::{Read, Write}; use super::{Error, Result}; use util::codec::number::{NumberDecoder, NumberEncoder}; const ENC_GROUP_SIZE: usize = 8; const ENC_MARKER: u8 = b'\xff'; const ENC_PADDING: [u8; ENC_GROUP_SIZE] = [0; ENC_GROUP_SIZE]; // returns the maximum encoded bytes size. pub fn max_encoded_bytes_size(n: usize) -> usize { (n / ENC_GROUP_SIZE + 1) * (ENC_GROUP_SIZE + 1) } pub trait BytesEncoder: NumberEncoder { /// Refer: https://github.com/facebook/mysql-5.6/wiki/MyRocks-record-format#memcomparable-format fn encode_bytes(&mut self, key: &[u8], desc: bool) -> Result<()> { let len = key.len(); let mut index = 0; let mut buf = [0; ENC_GROUP_SIZE]; while index <= len { let remain = len - index; let mut pad: usize = 0; if remain > ENC_GROUP_SIZE { self.write_all(adjust_bytes_order( &key[index..index + ENC_GROUP_SIZE], desc, &mut buf, ))?; } else { pad = ENC_GROUP_SIZE - remain; self.write_all(adjust_bytes_order(&key[index..], desc, &mut buf))?; self.write_all(adjust_bytes_order(&ENC_PADDING[..pad], desc, &mut buf))?; } self.write_all(adjust_bytes_order( &[ENC_MARKER - (pad as u8)], desc, &mut buf, ))?; index += ENC_GROUP_SIZE; } Ok(()) } /// `encode_compact_bytes` joins bytes with its length into a byte slice. It is more /// efficient in both space and time compare to `encode_bytes`. Note that the encoded /// result is not memcomparable. fn encode_compact_bytes(&mut self, data: &[u8]) -> Result<()> { self.encode_var_i64(data.len() as i64)?; self.write_all(data).map_err(From::from) } } fn adjust_bytes_order<'a>(bs: &'a [u8], desc: bool, buf: &'a mut [u8]) -> &'a [u8] { if desc { let mut buf_idx = 0; for &b in bs { buf[buf_idx] = !b; buf_idx += 1; } &buf[..buf_idx] } else { bs } } impl<T: Write> BytesEncoder for T {} pub fn encode_bytes(bs: &[u8]) -> Vec<u8> { encode_order_bytes(bs, false) } pub fn encode_bytes_desc(bs: &[u8]) -> Vec<u8> { encode_order_bytes(bs, true) } fn encode_order_bytes(bs: &[u8], desc: bool) -> Vec<u8> { let cap = max_encoded_bytes_size(bs.len()); let mut encoded = Vec::with_capacity(cap); encoded.encode_bytes(bs, desc).unwrap(); encoded.shrink_to_fit(); encoded } /// Get the first compactly encoded bytes's length in encoded. /// /// Please note that, this function won't check the whether the bytes /// is encoded correctly. pub fn encoded_compact_len(mut encoded: &[u8]) -> usize { let last_encoded = encoded.as_ptr() as usize; let total_len = encoded.len(); let vn = match encoded.decode_var_i64() { Ok(vn) => vn as usize, Err(e) => { debug!("failed to decode bytes' length: {:?}", e); return total_len; } }; vn + (encoded.as_ptr() as usize - last_encoded) } pub trait CompactBytesDecoder: NumberDecoder { /// `decode_compact_bytes` decodes bytes which is encoded by `encode_compact_bytes` before. fn decode_compact_bytes(&mut self) -> Result<Vec<u8>> { let vn = self.decode_var_i64()? as usize; let mut data = vec![0; vn]; self.read_exact(&mut data)?; Ok(data) } } impl<T: Read> CompactBytesDecoder for T {} /// Get the first encoded bytes's length in encoded. /// /// Please note that, this function won't check the whether the bytes /// is encoded correctly. pub fn encoded_bytes_len(encoded: &[u8], desc: bool) -> usize { let mut idx = ENC_GROUP_SIZE; loop { if encoded.len() < idx + 1 { return encoded.len(); } let marker = encoded[idx]; if desc && marker != 0 || !desc && marker != ENC_MARKER { return idx + 1; } idx += ENC_GROUP_SIZE + 1; } } pub trait BytesDecoder: NumberDecoder + CompactBytesDecoder { /// Get the remaining length in bytes of current reader. fn remaining(&self) -> usize; fn peak_u8(&self) -> Option<u8>; fn decode_bytes(&mut self, desc: bool) -> Result<Vec<u8>> { let mut key = Vec::with_capacity(self.remaining()); let mut chunk = [0; ENC_GROUP_SIZE + 1]; loop { self.read_exact(&mut chunk)?; let (&marker, bytes) = chunk.split_last().unwrap(); let pad_size = if desc { marker as usize } else { (ENC_MARKER - marker) as usize }; if pad_size == 0 { key.write_all(bytes).unwrap(); continue; } if pad_size > ENC_GROUP_SIZE { return Err(Error::KeyPadding); } let (bytes, padding) = bytes.split_at(ENC_GROUP_SIZE - pad_size); key.write_all(bytes).unwrap(); let pad_byte = if desc { !0 } else { 0 }; if padding.iter().any(|x| *x != pad_byte) { return Err(Error::KeyPadding); } key.shrink_to_fit(); if desc { for k in &mut key { *k = !*k; } } return Ok(key); } } } impl<'a> BytesDecoder for &'a [u8] { fn remaining(&self) -> usize { self.len() } fn peak_u8(&self) -> Option<u8> { if self.is_empty() { None } else { Some(self[0]) } } } #[cfg(test)] mod tests { use super::*; use util::codec::{bytes, number}; use std::cmp::Ordering; #[test] fn test_enc_dec_bytes() { let pairs = vec![ ( vec![], vec![0, 0, 0, 0, 0, 0, 0, 0, 247], vec![255, 255, 255, 255, 255, 255, 255, 255, 8], ), ( vec![0], vec![0, 0, 0, 0, 0, 0, 0, 0, 248], vec![255, 255, 255, 255, 255, 255, 255, 255, 7], ), ( vec![1, 2, 3], vec![1, 2, 3, 0, 0, 0, 0, 0, 250], vec![254, 253, 252, 255, 255, 255, 255, 255, 5], ), ( vec![1, 2, 3, 0], vec![1, 2, 3, 0, 0, 0, 0, 0, 251], vec![254, 253, 252, 255, 255, 255, 255, 255, 4], ), ( vec![1, 2, 3, 4, 5, 6, 7], vec![1, 2, 3, 4, 5, 6, 7, 0, 254], vec![254, 253, 252, 251, 250, 249, 248, 255, 1], ), ( vec![0, 0, 0, 0, 0, 0, 0, 0], vec![0, 0, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 247], vec![ 255, 255, 255, 255, 255, 255, 255, 255, 0, 255, 255, 255, 255, 255, 255, 255, 255, 8, ], ), ( vec![1, 2, 3, 4, 5, 6, 7, 8], vec![1, 2, 3, 4, 5, 6, 7, 8, 255, 0, 0, 0, 0, 0, 0, 0, 0, 247], vec![ 254, 253, 252, 251, 250, 249, 248, 247, 0, 255, 255, 255, 255, 255, 255, 255, 255, 8, ], ), ( vec![1, 2, 3, 4, 5, 6, 7, 8, 9], vec![1, 2, 3, 4, 5, 6, 7, 8, 255, 9, 0, 0, 0, 0, 0, 0, 0, 248], vec![ 254, 253, 252, 251, 250, 249, 248, 247, 0, 246, 255, 255, 255, 255, 255, 255, 255, 7, ], ), ]; for (source, asc, desc) in pairs { assert_eq!(encode_bytes(&source), asc); assert_eq!(encode_bytes_desc(&source), desc); let asc_offset = asc.as_ptr() as usize; let mut asc_input = asc.as_slice(); assert_eq!(source, asc_input.decode_bytes(false).unwrap()); assert_eq!(asc_input.as_ptr() as usize - asc_offset, asc.len()); let desc_offset = desc.as_ptr() as usize; let mut desc_input = desc.as_slice(); assert_eq!(source, desc_input.decode_bytes(true).unwrap()); assert_eq!(desc_input.as_ptr() as usize - desc_offset, desc.len()); } } #[test] fn test_dec_bytes_fail() { let invalid_bytes = vec![ vec![1, 2, 3, 4], vec![0, 0, 0, 0, 0, 0, 0, 247], vec![0, 0, 0, 0, 0, 0, 0, 0, 246], vec![0, 0, 0, 0, 0, 0, 0, 1, 247], vec![1, 2, 3, 4, 5, 6, 7, 8, 0], vec![1, 2, 3, 4, 5, 6, 7, 8, 255, 1], vec![1, 2, 3, 4, 5, 6, 7, 8, 255, 1, 2, 3, 4, 5, 6, 7, 8], vec![1, 2, 3, 4, 5, 6, 7, 8, 255, 1, 2, 3, 4, 5, 6, 7, 8, 255], vec![1, 2, 3, 4, 5, 6, 7, 8, 255, 1, 2, 3, 4, 5, 6, 7, 8, 0], ]; for x in invalid_bytes { assert!(x.as_slice().decode_bytes(false).is_err()); } } #[test] fn test_encode_bytes_compare() { let pairs: Vec<(&[u8], &[u8], _)> = vec![ (b"", b"\x00", Ordering::Less), (b"\x00", b"\x00", Ordering::Equal), (b"\xFF", b"\x00", Ordering::Greater), (b"\xFF", b"\xFF\x00", Ordering::Less), (b"a", b"b", Ordering::Less), (b"a", b"\x00", Ordering::Greater), (b"\x00", b"\x01", Ordering::Less), (b"\x00\x01", b"\x00\x00", Ordering::Greater), (b"\x00\x00\x00", b"\x00\x00", Ordering::Greater), (b"\x00\x00\x00", b"\x00\x00", Ordering::Greater), ( b"\x00\x00\x00\x00\x00\x00\x00\x00", b"\x00\x00\x00\x00\x00\x00\x00\x00\x00", Ordering::Less, ), (b"\x01\x02\x03\x00", b"\x01\x02\x03", Ordering::Greater), (b"\x01\x03\x03\x04", b"\x01\x03\x03\x05", Ordering::Less), ( b"\x01\x02\x03\x04\x05\x06\x07", b"\x01\x02\x03\x04\x05\x06\x07\x08", Ordering::Less, ), ( b"\x01\x02\x03\x04\x05\x06\x07\x08\x09", b"\x01\x02\x03\x04\x05\x06\x07\x08", Ordering::Greater, ), ( b"\x01\x02\x03\x04\x05\x06\x07\x08\x00", b"\x01\x02\x03\x04\x05\x06\x07\x08", Ordering::Greater, ), ]; for (x, y, ord) in pairs { assert_eq!(encode_bytes(x).cmp(&encode_bytes(y)), ord); assert_eq!( encode_bytes_desc(x).cmp(&encode_bytes_desc(y)), ord.reverse() ); } } #[test] fn test_max_encoded_bytes_size() { let n = bytes::ENC_GROUP_SIZE; let tbl: Vec<(usize, usize)> = vec![(0, n + 1), (n / 2, n + 1), (n, 2 * (n + 1))]; for (x, y) in tbl { assert_eq!(max_encoded_bytes_size(x), y); } } #[test] fn test_compact_codec() { let tests = vec!["", "hello", "世界"]; for &s in &tests { let max_size = s.len() + number::MAX_VAR_I64_LEN; let mut buf = Vec::with_capacity(max_size); buf.encode_compact_bytes(s.as_bytes()).unwrap(); assert!(buf.len() <= max_size); let mut input = buf.as_slice(); let decoded = input.decode_compact_bytes().unwrap(); assert!(input.is_empty()); assert_eq!(decoded, s.as_bytes()); } } use test::Bencher; #[bench] fn bench_encode(b: &mut Bencher) { let key = [b'x'; 20]; b.iter(|| encode_bytes(&key)); } #[bench] fn bench_decode(b: &mut Bencher) { let key = [b'x'; 2000000]; let encoded = encode_bytes(&key); b.iter(|| encoded.as_slice().decode_bytes(false)); } }
32.955263
100
0.485187
397132060e4086ff2de9ce29664d0e5780267e99
7,280
// Copyright 2021. The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. use std::{fmt, io, net::TcpListener}; use libtor::{LogDestination, LogLevel, TorFlag}; use log::*; use multiaddr::Multiaddr; use rand::{distributions::Alphanumeric, thread_rng, Rng}; use tari_common::{ exit_codes::{ExitCode, ExitError}, CommsTransport, TorControlAuthentication, }; use tari_shutdown::ShutdownSignal; use tempfile::{tempdir, NamedTempFile, TempDir, TempPath}; use tor_hash_passwd::EncryptedKey; const LOG_TARGET: &str = "tari_libtor"; pub struct TorPassword(Option<String>); impl fmt::Debug for TorPassword { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "TorPassword: ...") } } #[derive(Debug)] pub struct Tor { control_port: u16, data_dir: String, log_destination: String, log_level: LogLevel, passphrase: TorPassword, socks_port: u16, temp_dir: Option<TempDir>, temp_file: Option<TempPath>, } impl Default for Tor { fn default() -> Tor { Tor { control_port: 19_051, data_dir: "/tmp/tor-data".into(), log_destination: "/tmp/tor.log".into(), log_level: LogLevel::Err, passphrase: TorPassword(None), socks_port: 19_050, temp_dir: None, temp_file: None, } } } impl Tor { /// Returns a new Tor instance with random options. /// The data directory, passphrase, and log destination are temporary and randomized. /// Two TCP ports will be provided by the operating system. /// These ports are used for the control and socks ports, the onion address and port info are still loaded from the /// node identity file. pub fn initialize() -> Result<Tor, ExitError> { debug!(target: LOG_TARGET, "Initializing libtor"); let mut instance = Tor::default(); // check for unused ports to assign let (socks_port, control_port) = get_available_ports()?; instance.socks_port = socks_port; instance.control_port = control_port; // generate a random passphrase let passphrase: String = thread_rng() .sample_iter(&Alphanumeric) .take(30) .map(char::from) .collect(); instance.passphrase = TorPassword(Some(passphrase)); // data dir let temp = tempdir()?; let dir = temp.path().to_string_lossy().to_string(); instance.temp_dir = Some(temp); instance.data_dir = dir; // log destination let temp = NamedTempFile::new()?.into_temp_path(); let file = temp.to_string_lossy().to_string(); instance.temp_file = Some(temp); instance.log_destination = file; debug!(target: LOG_TARGET, "tor instance: {:?}", instance); Ok(instance) } /// Override a given Tor comms transport with the control address and auth from this instance pub fn update_comms_transport(&self, transport: CommsTransport) -> Result<CommsTransport, ExitError> { debug!(target: LOG_TARGET, "updating comms transport"); if let CommsTransport::TorHiddenService { socks_address_override, forward_address, auth, onion_port, tor_proxy_bypass_addresses, tor_proxy_bypass_for_outbound_tcp, .. } = transport { let control_server_address = format!("/ip4/127.0.0.1/tcp/{}", self.control_port).parse::<Multiaddr>()?; let auth = if let Some(ref passphrase) = self.passphrase.0 { TorControlAuthentication::Password(passphrase.to_owned()) } else { auth }; let transport = CommsTransport::TorHiddenService { control_server_address, socks_address_override, forward_address, auth, onion_port, tor_proxy_bypass_addresses, tor_proxy_bypass_for_outbound_tcp, }; debug!(target: LOG_TARGET, "updated comms transport: {:?}", transport); Ok(transport) } else { let e = format!("Expected a TorHiddenService comms transport, received: {:?}", transport); Err(ExitError::new(ExitCode::ConfigError, e)) } } /// Run the Tor instance until the shutdown signal is received pub async fn run(self, mut shutdown_signal: ShutdownSignal) -> Result<(), ExitError> { info!(target: LOG_TARGET, "Starting Tor instance"); let Tor { data_dir, socks_port, control_port, log_level, log_destination, passphrase, .. } = self; let mut tor = libtor::Tor::new(); tor.flag(TorFlag::DataDirectory(data_dir.clone())) .flag(TorFlag::SocksPort(socks_port)) .flag(TorFlag::ControlPort(control_port)) .flag(TorFlag::Hush()) .flag(TorFlag::LogTo(log_level, LogDestination::File(log_destination))); if let Some(secret) = passphrase.0 { let hash = EncryptedKey::hash_password(&secret).to_string(); tor.flag(TorFlag::HashedControlPassword(hash)); } tor.start_background(); shutdown_signal.wait().await; info!(target: LOG_TARGET, "Shutting down Tor instance"); Ok(()) } } /// Attempt to find 2 available TCP ports fn get_available_ports() -> Result<(u16, u16), io::Error> { let localhost = "127.0.0.1"; let listener1 = TcpListener::bind((localhost, 0))?; let port1 = listener1.local_addr()?.port(); let listener2 = TcpListener::bind((localhost, 0))?; let port2 = listener2.local_addr()?.port(); Ok((port1, port2)) }
36.954315
119
0.641071
14807afe2803d40ba9b41c6dae2da0266e626ebf
11,298
//! The intermediate representation of a RegEx //! in a tree based structure. use crate::{Parser, Span}; use bitflags::bitflags; bitflags! { pub struct Flags: u8 { /// With this flag the search looks for all matches, without this flag /// only the first match is returned const G = 0b00000001; /// Multiline mode const M = 0b00000010; /// Case-insensitive search const I = 0b00000100; /// "dotall" mode, that allows `.` to match newlines (`\n`) const S = 0b00001000; /// Enables full unicode support const U = 0b00010000; /// "Sticky" mode const Y = 0b00100000; } } /// The structure that represents a regular expression. /// /// It contains the actual RegEx node, and the flags for this expression. #[derive(Debug, Clone)] pub struct Regex { pub node: Node, pub flags: Flags, } /// The tree structure that is used to represent parsed /// RegEx patterns. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Node { /// An empty regex node. Empty, /// An "either or". (e.g. `a|b`) Disjunction(Span, Vec<Node>), /// A single assertion. Assertion(Span, AssertionKind), /// A concatenation of regex nodes. (e.g. `ab`) Alternative(Span, Vec<Node>), /// A single character literal. The String represents the raw string representing the literal /// which is used to turn the node back into a string without writing explicit newlines for example. Literal(Span, char, String), /// Matches a character class (e.g. `\d` or `\w`). /// /// The bool argument indicates if this perl class is negated. PerlClass(Span, ClassPerlKind, bool), /// A back reference to a previous group (`\1`, `\2`, ...). BackReference(Span, u32), /// A `.` that matches everything. Dot(Span), /// A class of multiple characters such as `[A-Z0-9]` CharacterClass(Span, CharacterClass), /// A grouped pattern Group(Span, Group), /// A quantifier which optionally matches or matches multiple times. /// `bool` indicates whether a lazy quantifier (`?`) is present after it. Quantifier(Span, Box<Node>, QuantifierKind, bool), /// A reference to a group using a name NamedBackReference(Span, String), } impl Node { /// if this node is an alternative, yield an iterator over those nodes, otherwise yield the node itself. pub fn expanded_nodes(&mut self) -> Box<dyn Iterator<Item = &mut Node> + '_> { if let Node::Alternative(_, nodes) = self { Box::new((*nodes).iter_mut()) } else { Box::new(Some(self).into_iter()) } } /// get the span of this node, returns [`None`] if the node is an empty node. pub fn span(&self) -> Option<Span> { Some( match self { Node::Empty => return None, Node::Disjunction(s, _) => s, Node::Assertion(s, _) => s, Node::Alternative(s, _) => s, Node::Literal(s, _, _) => s, Node::PerlClass(s, _, _) => s, Node::BackReference(s, _) => s, Node::Dot(s) => s, Node::CharacterClass(s, _) => s, Node::Group(s, _) => s, Node::Quantifier(s, _, _, _) => s, Node::NamedBackReference(s, _) => s, } .to_owned(), ) } /// check if this node is equal to some text pub fn is(&self, src: impl AsRef<str>, text: impl AsRef<str>) -> bool { if let Some(span) = self.span() { &src.as_ref()[span.as_range()] == text.as_ref() } else { text.as_ref().is_empty() } } pub fn text<'a>(&self, src: &'a str) -> &'a str { if let Some(span) = self.span() { &src[span.as_range()] } else { "" } } /// create a new node from a string. This method is mostly just used for making simple nodes /// for replacement. pub fn from_string(string: impl AsRef<str>) -> Option<Self> { Parser::new_from_pattern_and_flags( string.as_ref(), 0, 0, crate::EcmaVersion::ES2021, false, Flags::empty(), ) .parse() .ok() .map(|x| x.node) } } impl ToString for Node { fn to_string(&self) -> String { match self { Node::Alternative(_, nodes) => nodes .iter() .map(|x| x.to_string()) .collect::<Vec<_>>() .join(""), Node::Empty => Default::default(), Node::Disjunction(_, nodes) => nodes .iter() .map(|x| x.to_string()) .collect::<Vec<_>>() .join("|"), Node::Assertion(_, kind) => kind.to_string(), Node::Literal(_, _, string) => string.to_owned(), Node::Dot(_) => ".".to_string(), Node::NamedBackReference(_, string) => { format!("\\k<{}>", string) } Node::BackReference(_, num) => { format!("\\{}", num) } Node::CharacterClass(_, CharacterClass { members, negated }) => { format!( "[{}{}]", if *negated { "^" } else { "" }, members .iter() .map(|x| x.to_string()) .collect::<Vec<_>>() .join("") ) } Node::Quantifier(_, node, kind, lazy) => { let kind_string = match kind { QuantifierKind::AtLeastOne => "+".to_string(), QuantifierKind::Multiple => "*".to_string(), QuantifierKind::Optional => "?".to_string(), QuantifierKind::Number(num) => format!("{{{}}}", num), QuantifierKind::Between(from, to) => format!( "{{{},{}}}", from, to.map(|x| x.to_string()).unwrap_or_default() ), }; format!( "{}{}{}", node.to_string(), kind_string, if *lazy { "?" } else { "" } ) } Node::Group( _, Group { name, noncapturing, inner, }, ) => { format!( "({}{})", if *noncapturing { "?:".to_string() } else if let Some(name) = name { format!("\\<{}>", name) } else { "".to_string() }, inner.to_string() ) } Node::PerlClass(_, kind, negative) => match kind { ClassPerlKind::Digit if *negative => "\\D".to_string(), ClassPerlKind::Digit => "\\d".to_string(), ClassPerlKind::Space if *negative => "\\S".to_string(), ClassPerlKind::Space => "\\s".to_string(), ClassPerlKind::Word if *negative => "\\W".to_string(), ClassPerlKind::Word => "\\w".to_string(), ClassPerlKind::Unicode(a, b) => { format!( "\\{}{{{}{}}}", if *negative { "P" } else { "p" }, if let Some(a) = a { format!("{}=", a) } else { "".to_string() }, b ) } }, } } } impl ToString for AssertionKind { fn to_string(&self) -> String { match self { AssertionKind::StartOfLine => "^".to_string(), AssertionKind::EndOfLine => "$".to_string(), AssertionKind::WordBoundary => r"\b".to_string(), AssertionKind::NonWordBoundary => r"\B".to_string(), AssertionKind::Lookahead(node) => format!("(?={})", node.to_string()), AssertionKind::NegativeLookahead(node) => format!("(?!{})", node.to_string()), AssertionKind::Lookbehind(node) => format!("(?<={})", node.to_string()), AssertionKind::NegativeLookbehind(node) => format!("(?<!{})", node.to_string()), } } } impl ToString for CharacterClassMember { fn to_string(&self) -> String { match self { CharacterClassMember::Range(a, b) => format!("{}-{}", a.to_string(), b.to_string()), CharacterClassMember::Single(node) => node.to_string(), } } } /// A grouped pattern which can later be referred to #[derive(Debug, Clone, PartialEq, Eq)] pub struct Group { /// Whether this group cannot be later referred to with `$0` for example pub noncapturing: bool, pub inner: Box<Node>, pub name: Option<String>, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum QuantifierKind { /// `?` Optional, /// `*` Multiple, /// `+` AtLeastOne, /// `{number}` Number(u32), /// `{number,number}`. if the second option is None it is "between X and unlimited times" Between(u32, Option<u32>), } impl QuantifierKind { /// Returns `true` if the quantifier_kind is [`QuantifierKind::AtLeastOne`]. pub fn is_at_least_one(&self) -> bool { matches!(self, Self::AtLeastOne) } /// Returns `true` if the quantifier_kind is [`QuantifierKind::Multiple`]. pub fn is_multiple(&self) -> bool { matches!(self, Self::Multiple) } /// Returns `true` if the quantifier_kind is [`QuantifierKind::Optional`]. pub fn is_optional(&self) -> bool { matches!(self, Self::Optional) } } /// A class matching multiple characters or ranges of characters #[derive(Debug, Clone, PartialEq, Eq)] pub struct CharacterClass { pub negated: bool, pub members: Vec<CharacterClassMember>, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum CharacterClassMember { Range(Node, Node), Single(Node), } impl CharacterClassMember { pub fn is(&self, src: impl AsRef<str>, text: impl AsRef<str>) -> bool { let src = src.as_ref(); match self { CharacterClassMember::Range(a, b) => { format!("{}-{}", a.text(src), b.text(src)) == text.as_ref() } CharacterClassMember::Single(node) => node.text(src) == text.as_ref(), } } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum AssertionKind { /// `^` StartOfLine, /// `$` EndOfLine, /// `\b` WordBoundary, /// `\B` NonWordBoundary, /// `x(?=y)` Lookahead(Box<Node>), /// `x(?!y)` NegativeLookahead(Box<Node>), /// `(?<=y)x` Lookbehind(Box<Node>), /// `(?<!y)x` NegativeLookbehind(Box<Node>), } #[derive(Debug, Clone, PartialEq, Eq)] pub enum ClassPerlKind { Digit, Word, Space, Unicode(Option<String>, String), }
32.653179
108
0.490795
4a7b196c840f62e0f170473b856082590c0be9a7
1,553
use crate::pre_structs::Solution; ///204. 计数质数 impl Solution { //772MS,2.1MB pub fn count_primes(n: i32) -> i32 { fn is_primes(num: i32) -> bool { let _cnt = 0; if num < 2 { return false; } if num == 2 { return true; } for i in 2..=f32::sqrt(num as f32) as i32 { if num % i == 0 { return false; } } true } let mut cnt = 0; for i in 0..n { if is_primes(i) { cnt += 1; } } cnt } //排除法 埃拉托色尼筛选法 //12MS,3.4MB pub fn count_primes2(n: i32) -> i32 { if n < 2 { return 0; } let mut bit_set = vec![true; n as usize]; let mut i = 2; while i * i < n { if bit_set[i as usize] { let mut j = i * i; while j < n { bit_set[j as usize] = false; j += i; } } i += 1; } let cnt = bit_set .iter() .enumerate() .filter(|(i, &x)| i >= &2 && i < &(n as usize) && x == true) .count(); cnt as i32 } } #[cfg(test)] mod test { use crate::pre_structs::Solution; #[test] fn count_primes() { let ret = Solution::count_primes(10); let ret2 = Solution::count_primes2(10); assert!(ret == ret2); } }
22.507246
72
0.370895
fb875e53887bbe4eff48e8c22d6fae2e1fb5b30b
32,478
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StorageSyncError { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<StorageSyncApiError>, #[serde(default, skip_serializing_if = "Option::is_none")] pub innererror: Option<StorageSyncApiError>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StorageSyncApiError { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub details: Option<StorageSyncErrorDetails>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StorageSyncErrorDetails { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SubscriptionState { #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option<subscription_state::State>, #[serde(default, skip_serializing_if = "Option::is_none")] pub istransitioning: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<SubscriptionStateProperties>, } pub mod subscription_state { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum State { Registered, Unregistered, Warned, Suspended, Deleted, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StorageSyncService { #[serde(flatten)] pub tracked_resource: TrackedResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<StorageSyncServiceProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SyncGroup { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<SyncGroupProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudEndpoint { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CloudEndpointProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RecallActionParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub pattern: Option<String>, #[serde(rename = "recallPath", default, skip_serializing_if = "Option::is_none")] pub recall_path: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StorageSyncServiceCreateParameters { pub location: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SyncGroupCreateParameters { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<SyncGroupCreateParametersProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SyncGroupCreateParametersProperties {} #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudEndpointCreateParameters { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CloudEndpointCreateParametersProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudEndpointCreateParametersProperties { #[serde(rename = "storageAccountResourceId", default, skip_serializing_if = "Option::is_none")] pub storage_account_resource_id: Option<String>, #[serde(rename = "azureFileShareName", default, skip_serializing_if = "Option::is_none")] pub azure_file_share_name: Option<String>, #[serde(rename = "storageAccountTenantId", default, skip_serializing_if = "Option::is_none")] pub storage_account_tenant_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServerEndpointCreateParameters { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ServerEndpointCreateParametersProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServerEndpointCreateParametersProperties { #[serde(rename = "serverLocalPath", default, skip_serializing_if = "Option::is_none")] pub server_local_path: Option<PhysicalPath>, #[serde(rename = "cloudTiering", default, skip_serializing_if = "Option::is_none")] pub cloud_tiering: Option<FeatureStatus>, #[serde(rename = "volumeFreeSpacePercent", default, skip_serializing_if = "Option::is_none")] pub volume_free_space_percent: Option<i64>, #[serde(rename = "tierFilesOlderThanDays", default, skip_serializing_if = "Option::is_none")] pub tier_files_older_than_days: Option<i64>, #[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")] pub friendly_name: Option<String>, #[serde(rename = "serverResourceId", default, skip_serializing_if = "Option::is_none")] pub server_resource_id: Option<ResourceId>, #[serde(rename = "offlineDataTransfer", default, skip_serializing_if = "Option::is_none")] pub offline_data_transfer: Option<FeatureStatus>, #[serde(rename = "offlineDataTransferShareName", default, skip_serializing_if = "Option::is_none")] pub offline_data_transfer_share_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TriggerRolloverRequest { #[serde(rename = "serverCertificate", default, skip_serializing_if = "Option::is_none")] pub server_certificate: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegisteredServerCreateParameters { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RegisteredServerCreateParametersProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegisteredServerCreateParametersProperties { #[serde(rename = "serverCertificate", default, skip_serializing_if = "Option::is_none")] pub server_certificate: Option<String>, #[serde(rename = "agentVersion", default, skip_serializing_if = "Option::is_none")] pub agent_version: Option<String>, #[serde(rename = "serverOSVersion", default, skip_serializing_if = "Option::is_none")] pub server_os_version: Option<String>, #[serde(rename = "lastHeartBeat", default, skip_serializing_if = "Option::is_none")] pub last_heart_beat: Option<String>, #[serde(rename = "serverRole", default, skip_serializing_if = "Option::is_none")] pub server_role: Option<String>, #[serde(rename = "clusterId", default, skip_serializing_if = "Option::is_none")] pub cluster_id: Option<String>, #[serde(rename = "clusterName", default, skip_serializing_if = "Option::is_none")] pub cluster_name: Option<String>, #[serde(rename = "serverId", default, skip_serializing_if = "Option::is_none")] pub server_id: Option<String>, #[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")] pub friendly_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServerEndpointUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ServerEndpointUpdateProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServerEndpoint { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ServerEndpointProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegisteredServer { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RegisteredServerProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourcesMoveInfo { #[serde(rename = "targetResourceGroup", default, skip_serializing_if = "Option::is_none")] pub target_resource_group: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub resources: Vec<ResourceId>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Workflow { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<WorkflowProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationEntityListResult { #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<OperationEntity>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationEntity { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<OperationDisplayInfo>, #[serde(default, skip_serializing_if = "Option::is_none")] pub origin: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationDisplayInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationDisplayResource { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CheckNameAvailabilityParameters { pub name: String, #[serde(rename = "type")] pub type_: check_name_availability_parameters::Type, } pub mod check_name_availability_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { #[serde(rename = "Microsoft.StorageSync/storageSyncServices")] MicrosoftStorageSyncStorageSyncServices, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CheckNameAvailabilityResult { #[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")] pub name_available: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reason: Option<check_name_availability_result::Reason>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } pub mod check_name_availability_result { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Reason { Invalid, AlreadyExists, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PostRestoreRequest { #[serde(default, skip_serializing_if = "Option::is_none")] pub partition: Option<String>, #[serde(rename = "replicaGroup", default, skip_serializing_if = "Option::is_none")] pub replica_group: Option<String>, #[serde(rename = "requestId", default, skip_serializing_if = "Option::is_none")] pub request_id: Option<String>, #[serde(rename = "azureFileShareUri", default, skip_serializing_if = "Option::is_none")] pub azure_file_share_uri: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<String>, #[serde(rename = "sourceAzureFileShareUri", default, skip_serializing_if = "Option::is_none")] pub source_azure_file_share_uri: Option<String>, #[serde(rename = "failedFileList", default, skip_serializing_if = "Option::is_none")] pub failed_file_list: Option<String>, #[serde(rename = "restoreFileSpec", default, skip_serializing_if = "Vec::is_empty")] pub restore_file_spec: Vec<RestoreFileSpec>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PreRestoreRequest { #[serde(default, skip_serializing_if = "Option::is_none")] pub partition: Option<String>, #[serde(rename = "replicaGroup", default, skip_serializing_if = "Option::is_none")] pub replica_group: Option<String>, #[serde(rename = "requestId", default, skip_serializing_if = "Option::is_none")] pub request_id: Option<String>, #[serde(rename = "azureFileShareUri", default, skip_serializing_if = "Option::is_none")] pub azure_file_share_uri: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<String>, #[serde(rename = "sourceAzureFileShareUri", default, skip_serializing_if = "Option::is_none")] pub source_azure_file_share_uri: Option<String>, #[serde(rename = "backupMetadataPropertyBag", default, skip_serializing_if = "Option::is_none")] pub backup_metadata_property_bag: Option<String>, #[serde(rename = "restoreFileSpec", default, skip_serializing_if = "Vec::is_empty")] pub restore_file_spec: Vec<RestoreFileSpec>, #[serde( rename = "pauseWaitForSyncDrainTimePeriodInSeconds", default, skip_serializing_if = "Option::is_none" )] pub pause_wait_for_sync_drain_time_period_in_seconds: Option<i64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BackupRequest { #[serde(rename = "azureFileShare", default, skip_serializing_if = "Option::is_none")] pub azure_file_share: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PostBackupResponse { #[serde(rename = "backupMetadata", default, skip_serializing_if = "Option::is_none")] pub backup_metadata: Option<PostBackupResponseProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RestoreFileSpec { #[serde(default, skip_serializing_if = "Option::is_none")] pub path: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub isdir: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StorageSyncServiceArray { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<StorageSyncService>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SyncGroupArray { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<SyncGroup>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudEndpointArray { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<CloudEndpoint>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServerEndpointArray { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ServerEndpoint>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegisteredServerArray { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<RegisteredServer>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WorkflowArray { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Workflow>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SubscriptionStateProperties {} #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PostBackupResponseProperties { #[serde(rename = "cloudEndpointName", default, skip_serializing_if = "Option::is_none")] pub cloud_endpoint_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StorageSyncServiceUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<StorageSyncServiceUpdateProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StorageSyncServiceUpdateProperties {} #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StorageSyncServiceProperties { #[serde(rename = "storageSyncServiceStatus", default, skip_serializing_if = "Option::is_none")] pub storage_sync_service_status: Option<i64>, #[serde(rename = "storageSyncServiceUid", default, skip_serializing_if = "Option::is_none")] pub storage_sync_service_uid: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WorkflowProperties { #[serde(rename = "lastStepName", default, skip_serializing_if = "Option::is_none")] pub last_step_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<WorkflowStatus>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<OperationDirection>, #[serde(default, skip_serializing_if = "Option::is_none")] pub steps: Option<String>, #[serde(rename = "lastOperationId", default, skip_serializing_if = "Option::is_none")] pub last_operation_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SyncGroupProperties { #[serde(rename = "uniqueId", default, skip_serializing_if = "Option::is_none")] pub unique_id: Option<String>, #[serde(rename = "syncGroupStatus", default, skip_serializing_if = "Option::is_none")] pub sync_group_status: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegisteredServerProperties { #[serde(rename = "serverCertificate", default, skip_serializing_if = "Option::is_none")] pub server_certificate: Option<String>, #[serde(rename = "agentVersion", default, skip_serializing_if = "Option::is_none")] pub agent_version: Option<String>, #[serde(rename = "serverOSVersion", default, skip_serializing_if = "Option::is_none")] pub server_os_version: Option<String>, #[serde(rename = "serverManagementErrorCode", default, skip_serializing_if = "Option::is_none")] pub server_management_error_code: Option<i64>, #[serde(rename = "lastHeartBeat", default, skip_serializing_if = "Option::is_none")] pub last_heart_beat: Option<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[serde(rename = "serverRole", default, skip_serializing_if = "Option::is_none")] pub server_role: Option<String>, #[serde(rename = "clusterId", default, skip_serializing_if = "Option::is_none")] pub cluster_id: Option<String>, #[serde(rename = "clusterName", default, skip_serializing_if = "Option::is_none")] pub cluster_name: Option<String>, #[serde(rename = "serverId", default, skip_serializing_if = "Option::is_none")] pub server_id: Option<String>, #[serde(rename = "storageSyncServiceUid", default, skip_serializing_if = "Option::is_none")] pub storage_sync_service_uid: Option<String>, #[serde(rename = "lastWorkflowId", default, skip_serializing_if = "Option::is_none")] pub last_workflow_id: Option<String>, #[serde(rename = "lastOperationName", default, skip_serializing_if = "Option::is_none")] pub last_operation_name: Option<String>, #[serde(rename = "discoveryEndpointUri", default, skip_serializing_if = "Option::is_none")] pub discovery_endpoint_uri: Option<String>, #[serde(rename = "resourceLocation", default, skip_serializing_if = "Option::is_none")] pub resource_location: Option<String>, #[serde(rename = "serviceLocation", default, skip_serializing_if = "Option::is_none")] pub service_location: Option<String>, #[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")] pub friendly_name: Option<String>, #[serde(rename = "managementEndpointUri", default, skip_serializing_if = "Option::is_none")] pub management_endpoint_uri: Option<String>, #[serde(rename = "monitoringConfiguration", default, skip_serializing_if = "Option::is_none")] pub monitoring_configuration: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudEndpointProperties { #[serde(rename = "storageAccountResourceId", default, skip_serializing_if = "Option::is_none")] pub storage_account_resource_id: Option<String>, #[serde(rename = "azureFileShareName", default, skip_serializing_if = "Option::is_none")] pub azure_file_share_name: Option<String>, #[serde(rename = "storageAccountTenantId", default, skip_serializing_if = "Option::is_none")] pub storage_account_tenant_id: Option<String>, #[serde(rename = "partnershipId", default, skip_serializing_if = "Option::is_none")] pub partnership_id: Option<String>, #[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")] pub friendly_name: Option<String>, #[serde(rename = "backupEnabled", default, skip_serializing_if = "Option::is_none")] pub backup_enabled: Option<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[serde(rename = "lastWorkflowId", default, skip_serializing_if = "Option::is_none")] pub last_workflow_id: Option<String>, #[serde(rename = "lastOperationName", default, skip_serializing_if = "Option::is_none")] pub last_operation_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServerEndpointUpdateProperties { #[serde(rename = "cloudTiering", default, skip_serializing_if = "Option::is_none")] pub cloud_tiering: Option<FeatureStatus>, #[serde(rename = "volumeFreeSpacePercent", default, skip_serializing_if = "Option::is_none")] pub volume_free_space_percent: Option<i64>, #[serde(rename = "tierFilesOlderThanDays", default, skip_serializing_if = "Option::is_none")] pub tier_files_older_than_days: Option<i64>, #[serde(rename = "offlineDataTransfer", default, skip_serializing_if = "Option::is_none")] pub offline_data_transfer: Option<FeatureStatus>, #[serde(rename = "offlineDataTransferShareName", default, skip_serializing_if = "Option::is_none")] pub offline_data_transfer_share_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServerEndpointProperties { #[serde(rename = "serverLocalPath", default, skip_serializing_if = "Option::is_none")] pub server_local_path: Option<PhysicalPath>, #[serde(rename = "cloudTiering", default, skip_serializing_if = "Option::is_none")] pub cloud_tiering: Option<FeatureStatus>, #[serde(rename = "volumeFreeSpacePercent", default, skip_serializing_if = "Option::is_none")] pub volume_free_space_percent: Option<i64>, #[serde(rename = "tierFilesOlderThanDays", default, skip_serializing_if = "Option::is_none")] pub tier_files_older_than_days: Option<i64>, #[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")] pub friendly_name: Option<String>, #[serde(rename = "serverResourceId", default, skip_serializing_if = "Option::is_none")] pub server_resource_id: Option<ResourceId>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[serde(rename = "lastWorkflowId", default, skip_serializing_if = "Option::is_none")] pub last_workflow_id: Option<String>, #[serde(rename = "lastOperationName", default, skip_serializing_if = "Option::is_none")] pub last_operation_name: Option<String>, #[serde(rename = "syncStatus", default, skip_serializing_if = "Option::is_none")] pub sync_status: Option<ServerEndpointSyncStatus>, #[serde(rename = "offlineDataTransfer", default, skip_serializing_if = "Option::is_none")] pub offline_data_transfer: Option<FeatureStatus>, #[serde( rename = "offlineDataTransferStorageAccountResourceId", default, skip_serializing_if = "Option::is_none" )] pub offline_data_transfer_storage_account_resource_id: Option<String>, #[serde( rename = "offlineDataTransferStorageAccountTenantId", default, skip_serializing_if = "Option::is_none" )] pub offline_data_transfer_storage_account_tenant_id: Option<String>, #[serde(rename = "offlineDataTransferShareName", default, skip_serializing_if = "Option::is_none")] pub offline_data_transfer_share_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServerEndpointSyncStatus { #[serde(rename = "downloadHealth", default, skip_serializing_if = "Option::is_none")] pub download_health: Option<HealthState>, #[serde(rename = "uploadHealth", default, skip_serializing_if = "Option::is_none")] pub upload_health: Option<HealthState>, #[serde(rename = "combinedHealth", default, skip_serializing_if = "Option::is_none")] pub combined_health: Option<HealthState>, #[serde(rename = "syncActivity", default, skip_serializing_if = "Option::is_none")] pub sync_activity: Option<SyncActivityState>, #[serde(rename = "totalPersistentFilesNotSyncingCount", default, skip_serializing_if = "Option::is_none")] pub total_persistent_files_not_syncing_count: Option<i64>, #[serde(rename = "lastUpdatedTimestamp", default, skip_serializing_if = "Option::is_none")] pub last_updated_timestamp: Option<String>, #[serde(rename = "uploadStatus", default, skip_serializing_if = "Option::is_none")] pub upload_status: Option<SyncSessionStatus>, #[serde(rename = "downloadStatus", default, skip_serializing_if = "Option::is_none")] pub download_status: Option<SyncSessionStatus>, #[serde(rename = "uploadActivity", default, skip_serializing_if = "Option::is_none")] pub upload_activity: Option<SyncActivityStatus>, #[serde(rename = "downloadActivity", default, skip_serializing_if = "Option::is_none")] pub download_activity: Option<SyncActivityStatus>, #[serde(rename = "offlineDataTransferStatus", default, skip_serializing_if = "Option::is_none")] pub offline_data_transfer_status: Option<OfflineDataTransferState>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SyncSessionStatus { #[serde(rename = "lastSyncResult", default, skip_serializing_if = "Option::is_none")] pub last_sync_result: Option<i32>, #[serde(rename = "lastSyncTimestamp", default, skip_serializing_if = "Option::is_none")] pub last_sync_timestamp: Option<String>, #[serde(rename = "lastSyncSuccessTimestamp", default, skip_serializing_if = "Option::is_none")] pub last_sync_success_timestamp: Option<String>, #[serde(rename = "lastSyncPerItemErrorCount", default, skip_serializing_if = "Option::is_none")] pub last_sync_per_item_error_count: Option<i64>, #[serde(rename = "persistentFilesNotSyncingCount", default, skip_serializing_if = "Option::is_none")] pub persistent_files_not_syncing_count: Option<i64>, #[serde(rename = "transientFilesNotSyncingCount", default, skip_serializing_if = "Option::is_none")] pub transient_files_not_syncing_count: Option<i64>, #[serde(rename = "filesNotSyncingErrors", default, skip_serializing_if = "Vec::is_empty")] pub files_not_syncing_errors: Vec<FilesNotSyncingError>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SyncActivityStatus { #[serde(default, skip_serializing_if = "Option::is_none")] pub timestamp: Option<String>, #[serde(rename = "perItemErrorCount", default, skip_serializing_if = "Option::is_none")] pub per_item_error_count: Option<i64>, #[serde(rename = "appliedItemCount", default, skip_serializing_if = "Option::is_none")] pub applied_item_count: Option<i64>, #[serde(rename = "totalItemCount", default, skip_serializing_if = "Option::is_none")] pub total_item_count: Option<i64>, #[serde(rename = "appliedBytes", default, skip_serializing_if = "Option::is_none")] pub applied_bytes: Option<i64>, #[serde(rename = "totalBytes", default, skip_serializing_if = "Option::is_none")] pub total_bytes: Option<i64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FilesNotSyncingError { #[serde(rename = "errorCode", default, skip_serializing_if = "Option::is_none")] pub error_code: Option<i32>, #[serde(rename = "persistentCount", default, skip_serializing_if = "Option::is_none")] pub persistent_count: Option<i64>, #[serde(rename = "transientCount", default, skip_serializing_if = "Option::is_none")] pub transient_count: Option<i64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PhysicalPath {} #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceId {} #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TagsObject {} #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum FeatureStatus { #[serde(rename = "on")] On, #[serde(rename = "off")] Off, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum HealthState { Healthy, Error, SyncBlockedForRestore, SyncBlockedForChangeDetectionPostRestore, NoActivity, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum SyncActivityState { Upload, Download, UploadAndDownload, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum OfflineDataTransferState { InProgress, Stopping, NotRunning, Complete, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum WorkflowStatus { #[serde(rename = "active")] Active, #[serde(rename = "expired")] Expired, #[serde(rename = "succeeded")] Succeeded, #[serde(rename = "aborted")] Aborted, #[serde(rename = "failed")] Failed, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum OperationDirection { #[serde(rename = "do")] Do, #[serde(rename = "undo")] Undo, #[serde(rename = "cancel")] Cancel, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProgressType { #[serde(rename = "none")] None, #[serde(rename = "initialize")] Initialize, #[serde(rename = "download")] Download, #[serde(rename = "upload")] Upload, #[serde(rename = "recall")] Recall, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TrackedResource { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, pub location: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProxyResource { #[serde(flatten)] pub resource: Resource, }
47.832106
110
0.728493
ed7e81795fea3c1014214994459cb1c64479e72e
227
use thiserror::Error; #[derive(Debug, Error)] pub enum FftError { #[error("Not a digit: {0}")] NotADigit(char), #[error("IoError: {source}")] IoError { #[from] source: std::io::Error, }, }
16.214286
33
0.53304